forked from scrtlabs/catalyst
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_security_list.py
349 lines (296 loc) · 12.3 KB
/
test_security_list.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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
# from datetime import timedelta
# import pandas as pd
# from testfixtures import TempDirectory
# from nose_parameterized import parameterized
from catalyst.algorithm import TradingAlgorithm
# from catalyst.errors import TradingControlViolation
# from catalyst.testing import (
# add_security_data,
# create_data_portal,
# security_list_copy,
# tmp_trading_env,
# tmp_dir,
# )
# from catalyst.testing.fixtures import (
# WithLogger,
# WithTradingEnvironment,
# CatalystTestCase,
# )
# from catalyst.utils import factory
from catalyst.utils.security_list import (
SecurityListSet,
load_from_directory,
)
LEVERAGED_ETFS = load_from_directory('leveraged_etf_list')
class RestrictedAlgoWithCheck(TradingAlgorithm):
def initialize(self, symbol):
self.rl = SecurityListSet(self.get_datetime, self.asset_finder)
self.set_asset_restrictions(self.rl.restrict_leveraged_etfs)
self.order_count = 0
self.sid = self.symbol(symbol)
def handle_data(self, data):
if not self.order_count:
if self.sid not in \
self.rl.leveraged_etf_list.\
current_securities(self.get_datetime()):
self.order(self.sid, 100)
self.order_count += 1
class RestrictedAlgoWithoutCheck(TradingAlgorithm):
def initialize(self, symbol):
self.rl = SecurityListSet(self.get_datetime, self.asset_finder)
self.set_asset_restrictions(self.rl.restrict_leveraged_etfs)
self.order_count = 0
self.sid = self.symbol(symbol)
def handle_data(self, data):
self.order(self.sid, 100)
self.order_count += 1
class RestrictedAlgoWithoutCheckSetDoNotOrderList(TradingAlgorithm):
def initialize(self, symbol):
self.rl = SecurityListSet(self.get_datetime, self.asset_finder)
self.set_do_not_order_list(self.rl.leveraged_etf_list)
self.order_count = 0
self.sid = self.symbol(symbol)
def handle_data(self, data):
self.order(self.sid, 100)
self.order_count += 1
class IterateRLAlgo(TradingAlgorithm):
def initialize(self, symbol):
self.rl = SecurityListSet(self.get_datetime, self.asset_finder)
self.set_asset_restrictions(self.rl.restrict_leveraged_etfs)
self.order_count = 0
self.sid = self.symbol(symbol)
self.found = False
def handle_data(self, data):
for stock in self.rl.leveraged_etf_list.\
current_securities(self.get_datetime()):
if stock == self.sid:
self.found = True
"""
class SecurityListTestCase(WithLogger,
WithTradingEnvironment,
CatalystTestCase):
@classmethod
def init_class_fixtures(cls):
super(SecurityListTestCase, cls).init_class_fixtures()
# this is ugly, but we need to create two different
# TradingEnvironment/DataPortal pairs
cls.start = pd.Timestamp(list(LEVERAGED_ETFS.keys())[0])
end = pd.Timestamp('2015-02-17', tz='utc')
cls.extra_knowledge_date = pd.Timestamp('2015-01-27', tz='utc')
cls.trading_day_before_first_kd = pd.Timestamp('2015-01-23', tz='utc')
symbols = ['AAPL', 'GOOG', 'BZQ', 'URTY', 'JFT']
cls.env = cls.enter_class_context(tmp_trading_env(
equities=pd.DataFrame.from_records([{
'start_date': cls.start,
'end_date': end,
'symbol': symbol,
'exchange': "TEST",
} for symbol in symbols]),
load=cls.make_load_function(),
))
cls.sim_params = factory.create_simulation_parameters(
start=cls.start,
num_days=4,
trading_calendar=cls.trading_calendar
)
cls.sim_params2 = sp2 = factory.create_simulation_parameters(
start=cls.trading_day_before_first_kd, num_days=4
)
cls.env2 = cls.enter_class_context(tmp_trading_env(
equities=pd.DataFrame.from_records([{
'start_date': sp2.start_session,
'end_date': sp2.end_session,
'symbol': symbol,
'exchange': "TEST",
} for symbol in symbols]),
load=cls.make_load_function(),
))
cls.tempdir = cls.enter_class_context(tmp_dir())
cls.tempdir2 = cls.enter_class_context(tmp_dir())
cls.data_portal = create_data_portal(
asset_finder=cls.env.asset_finder,
tempdir=cls.tempdir,
sim_params=cls.sim_params,
sids=range(0, 5),
trading_calendar=cls.trading_calendar,
)
cls.data_portal2 = create_data_portal(
asset_finder=cls.env2.asset_finder,
tempdir=cls.tempdir2,
sim_params=cls.sim_params2,
sids=range(0, 5),
trading_calendar=cls.trading_calendar,
)
def test_iterate_over_restricted_list(self):
algo = IterateRLAlgo(symbol='BZQ', sim_params=self.sim_params,
env=self.env)
algo.run(self.data_portal)
self.assertTrue(algo.found)
def test_security_list(self):
# set the knowledge date to the first day of the
# leveraged etf knowledge date.
def get_datetime():
return self.start
rl = SecurityListSet(get_datetime, self.env.asset_finder)
# assert that a sample from the leveraged list are in restricted
should_exist = [
asset.sid for asset in
[self.env.asset_finder.lookup_symbol(
symbol,
as_of_date=self.extra_knowledge_date)
for symbol in ["BZQ", "URTY", "JFT"]]
]
for sid in should_exist:
self.assertIn(
sid, rl.leveraged_etf_list.current_securities(get_datetime()))
# assert that a sample of allowed stocks are not in restricted
shouldnt_exist = [
asset.sid for asset in
[self.env.asset_finder.lookup_symbol(
symbol,
as_of_date=self.extra_knowledge_date)
for symbol in ["AAPL", "GOOG"]]
]
for sid in shouldnt_exist:
self.assertNotIn(
sid, rl.leveraged_etf_list.current_securities(get_datetime()))
def test_security_add(self):
def get_datetime():
return pd.Timestamp("2015-01-27", tz='UTC')
with security_list_copy():
add_security_data(['AAPL', 'GOOG'], [])
rl = SecurityListSet(get_datetime, self.env.asset_finder)
should_exist = [
asset.sid for asset in
[self.env.asset_finder.lookup_symbol(
symbol,
as_of_date=self.extra_knowledge_date
) for symbol in ["AAPL", "GOOG", "BZQ", "URTY"]]
]
for sid in should_exist:
self.assertIn(
sid,
rl.leveraged_etf_list.current_securities(get_datetime())
)
def test_security_add_delete(self):
with security_list_copy():
def get_datetime():
return pd.Timestamp("2015-01-27", tz='UTC')
rl = SecurityListSet(get_datetime, self.env.asset_finder)
self.assertNotIn(
"BZQ",
rl.leveraged_etf_list.current_securities(get_datetime())
)
self.assertNotIn(
"URTY",
rl.leveraged_etf_list.current_securities(get_datetime())
)
def test_algo_without_rl_violation_via_check(self):
algo = RestrictedAlgoWithCheck(symbol='BZQ',
sim_params=self.sim_params,
env=self.env)
algo.run(self.data_portal)
def test_algo_without_rl_violation(self):
algo = RestrictedAlgoWithoutCheck(symbol='AAPL',
sim_params=self.sim_params,
env=self.env)
algo.run(self.data_portal)
@parameterized.expand([
('using_set_do_not_order_list',
RestrictedAlgoWithoutCheckSetDoNotOrderList),
('using_set_restrictions', RestrictedAlgoWithoutCheck),
])
def test_algo_with_rl_violation(self, name, algo_class):
algo = algo_class(symbol='BZQ',
sim_params=self.sim_params,
env=self.env)
with self.assertRaises(TradingControlViolation) as ctx:
algo.run(self.data_portal)
self.check_algo_exception(algo, ctx, 0)
# repeat with a symbol from a different lookup date
algo = RestrictedAlgoWithoutCheck(symbol='JFT',
sim_params=self.sim_params,
env=self.env)
with self.assertRaises(TradingControlViolation) as ctx:
algo.run(self.data_portal)
self.check_algo_exception(algo, ctx, 0)
def test_algo_with_rl_violation_after_knowledge_date(self):
sim_params = factory.create_simulation_parameters(
start=self.start + timedelta(days=7),
num_days=5
)
data_portal = create_data_portal(
self.env.asset_finder,
self.tempdir,
sim_params=sim_params,
sids=range(0, 5),
trading_calendar=self.trading_calendar,
)
algo = RestrictedAlgoWithoutCheck(symbol='BZQ',
sim_params=sim_params,
env=self.env)
with self.assertRaises(TradingControlViolation) as ctx:
algo.run(data_portal)
self.check_algo_exception(algo, ctx, 0)
def test_algo_with_rl_violation_cumulative(self):
#
#Add a new restriction, run a test long after both
#knowledge dates, make sure stock from original restriction
#set is still disallowed.
#
sim_params = factory.create_simulation_parameters(
start=self.start + timedelta(days=7),
num_days=4
)
with security_list_copy():
add_security_data(['AAPL'], [])
algo = RestrictedAlgoWithoutCheck(
symbol='BZQ', sim_params=sim_params, env=self.env)
with self.assertRaises(TradingControlViolation) as ctx:
algo.run(self.data_portal)
self.check_algo_exception(algo, ctx, 0)
def test_algo_without_rl_violation_after_delete(self):
sim_params = factory.create_simulation_parameters(
start=self.extra_knowledge_date,
num_days=4,
)
equities = pd.DataFrame.from_records([{
'symbol': 'BZQ',
'start_date': sim_params.start_session,
'end_date': sim_params.end_session,
'exchange': "TEST",
}])
with TempDirectory() as new_tempdir, \
security_list_copy(), \
tmp_trading_env(equities=equities,
load=self.make_load_function()) as env:
# add a delete statement removing bzq
# write a new delete statement file to disk
add_security_data([], ['BZQ'])
data_portal = create_data_portal(
env.asset_finder,
new_tempdir,
sim_params,
range(0, 5),
trading_calendar=self.trading_calendar,
)
algo = RestrictedAlgoWithoutCheck(
symbol='BZQ', sim_params=sim_params, env=env
)
algo.run(data_portal)
def test_algo_with_rl_violation_after_add(self):
with security_list_copy():
add_security_data(['AAPL'], [])
algo = RestrictedAlgoWithoutCheck(symbol='AAPL',
sim_params=self.sim_params2,
env=self.env2)
with self.assertRaises(TradingControlViolation) as ctx:
algo.run(self.data_portal2)
self.check_algo_exception(algo, ctx, 2)
def check_algo_exception(self, algo, ctx, expected_order_count):
self.assertEqual(algo.order_count, expected_order_count)
exc = ctx.exception
self.assertEqual(TradingControlViolation, type(exc))
exc_msg = str(ctx.exception)
self.assertTrue("RestrictedListOrder" in exc_msg)
"""