forked from quantopian/zipline
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_events.py
504 lines (419 loc) · 16.8 KB
/
test_events.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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
#
# Copyright 2016 Quantopian, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import datetime
from inspect import isabstract
import random
from unittest import TestCase
import warnings
from nose_parameterized import parameterized
import pandas as pd
from six import iteritems
from six.moves import range, map
from trading_calendars import get_calendar
import zipline.utils.events
from zipline.utils.events import (
EventRule,
StatelessRule,
Always,
Never,
AfterOpen,
ComposedRule,
BeforeClose,
NotHalfDay,
NthTradingDayOfWeek,
NDaysBeforeLastTradingDayOfWeek,
NthTradingDayOfMonth,
NDaysBeforeLastTradingDayOfMonth,
StatefulRule,
OncePerDay,
_build_offset,
_build_date,
_build_time,
EventManager,
Event,
MAX_MONTH_RANGE,
MAX_WEEK_RANGE,
TradingDayOfMonthRule,
TradingDayOfWeekRule
)
def param_range(*args):
return ([n] for n in range(*args))
class TestUtils(TestCase):
@parameterized.expand([
('_build_date', _build_date),
('_build_time', _build_time),
])
def test_build_none(self, name, f):
with self.assertRaises(ValueError):
f(None, {})
def test_build_offset_default(self):
default = object()
self.assertIs(default, _build_offset(None, {}, default))
def test_build_offset_both(self):
with self.assertRaises(ValueError):
_build_offset(datetime.timedelta(minutes=1), {'minutes': 1}, None)
def test_build_offset_exc(self):
with self.assertRaises(TypeError):
# object() is not an instance of a timedelta.
_build_offset(object(), {}, None)
def test_build_offset_kwargs(self):
kwargs = {'minutes': 1}
self.assertEqual(
_build_offset(None, kwargs, None),
datetime.timedelta(**kwargs),
)
def test_build_offset_td(self):
td = datetime.timedelta(minutes=1)
self.assertEqual(
_build_offset(td, {}, None),
td,
)
def test_build_date_both(self):
with self.assertRaises(ValueError):
_build_date(
datetime.date(year=2014, month=9, day=25), {
'year': 2014,
'month': 9,
'day': 25,
},
)
def test_build_date_kwargs(self):
kwargs = {'year': 2014, 'month': 9, 'day': 25}
self.assertEqual(
_build_date(None, kwargs),
datetime.date(**kwargs),
)
def test_build_date_date(self):
date = datetime.date(year=2014, month=9, day=25)
self.assertEqual(
_build_date(date, {}),
date,
)
def test_build_time_both(self):
with self.assertRaises(ValueError):
_build_time(
datetime.time(hour=1, minute=5), {
'hour': 1,
'minute': 5,
},
)
def test_build_time_kwargs(self):
kwargs = {'hour': 1, 'minute': 5}
self.assertEqual(
_build_time(None, kwargs),
datetime.time(**kwargs),
)
class TestEventManager(TestCase):
def setUp(self):
self.em = EventManager()
self.event1 = Event(Always())
self.event2 = Event(Always())
def test_add_event(self):
self.em.add_event(self.event1)
self.assertEqual(len(self.em._events), 1)
def test_add_event_prepend(self):
self.em.add_event(self.event1)
self.em.add_event(self.event2, prepend=True)
self.assertEqual([self.event2, self.event1], self.em._events)
def test_add_event_append(self):
self.em.add_event(self.event1)
self.em.add_event(self.event2)
self.assertEqual([self.event1, self.event2], self.em._events)
def test_checks_should_trigger(self):
class CountingRule(Always):
count = 0
def should_trigger(self, dt):
CountingRule.count += 1
return True
for r in [CountingRule] * 5:
self.em.add_event(Event(r()))
self.em.handle_data(None, None, datetime.datetime.now())
self.assertEqual(CountingRule.count, 5)
class TestEventRule(TestCase):
def test_is_abstract(self):
with self.assertRaises(TypeError):
EventRule()
def test_not_implemented(self):
with self.assertRaises(NotImplementedError):
super(Always, Always()).should_trigger('a')
def minutes_for_days(cal, ordered_days=False):
"""
500 randomly selected days.
This is used to make sure our test coverage is unbiased towards any rules.
We use a random sample because testing on all the trading days took
around 180 seconds on my laptop, which is far too much for normal unit
testing.
We manually set the seed so that this will be deterministic.
Results of multiple runs were compared to make sure that this is actually
true.
This returns a generator of tuples each wrapping a single generator.
Iterating over this yields a single day, iterating over the day yields
the minutes for that day.
"""
random.seed('deterministic')
if ordered_days:
# Get a list of 500 trading days, in order. As a performance
# optimization in AfterOpen and BeforeClose, we rely on the fact that
# the clock only ever moves forward in a simulation. For those cases,
# we guarantee that the list of trading days we test is ordered.
ordered_session_list = random.sample(list(cal.all_sessions), 500)
ordered_session_list.sort()
def session_picker(day):
return ordered_session_list[day]
else:
# Other than AfterOpen and BeforeClose, we don't rely on the the nature
# of the clock, so we don't care.
def session_picker(day):
return random.choice(cal.all_sessions[:-1])
return [cal.minutes_for_session(session_picker(cnt))
for cnt in range(500)]
class RuleTestCase(object):
CALENDAR_STRING = "foo"
@classmethod
def setUpClass(cls):
# On the AfterOpen and BeforeClose tests, we want ensure that the
# functions are pure, and that running them with the same input will
# provide the same output, regardless of whether the function is run 1
# or N times. (For performance reasons, we cache some internal state
# in AfterOpen and BeforeClose, but we don't want it to affect
# purity). Hence, we use the same before_close and after_open across
# subtests.
cls.before_close = BeforeClose(hours=1, minutes=5)
cls.after_open = AfterOpen(hours=1, minutes=5)
cls.class_ = None # Mark that this is the base class.
cal = get_calendar(cls.CALENDAR_STRING)
cls.before_close.cal = cal
cls.after_open.cal = cal
def test_completeness(self):
"""
Tests that all rules are being tested.
"""
if not self.class_:
return # This is the base class testing, it is always complete.
classes_to_ignore = [TradingDayOfWeekRule, TradingDayOfMonthRule]
dem = {
k for k, v in iteritems(vars(zipline.utils.events))
if isinstance(v, type) and
issubclass(v, self.class_) and
v is not self.class_ and
v not in classes_to_ignore and
not isabstract(v)
}
ds = {
k[5:] for k in dir(self)
if k.startswith('test') and k[5:] in dem
}
self.assertTrue(
dem <= ds,
msg='This suite is missing tests for the following classes:\n' +
'\n'.join(map(repr, dem - ds)),
)
class StatelessRulesTests(RuleTestCase):
@classmethod
def setUpClass(cls):
super(StatelessRulesTests, cls).setUpClass()
cls.class_ = StatelessRule
cls.cal = get_calendar(cls.CALENDAR_STRING)
# First day of 09/2014 is closed whereas that for 10/2014 is open
cls.sept_sessions = cls.cal.sessions_in_range(
pd.Timestamp('2014-09-01', tz='UTC'),
pd.Timestamp('2014-09-30', tz='UTC'),
)
cls.oct_sessions = cls.cal.sessions_in_range(
pd.Timestamp('2014-10-01', tz='UTC'),
pd.Timestamp('2014-10-31', tz='UTC'),
)
cls.sept_week = cls.cal.minutes_for_sessions_in_range(
pd.Timestamp("2014-09-22", tz='UTC'),
pd.Timestamp("2014-09-26", tz='UTC')
)
cls.HALF_SESSION = None
cls.FULL_SESSION = None
def test_Always(self):
should_trigger = Always().should_trigger
for session_minutes in minutes_for_days(self.cal):
self.assertTrue(all(map(should_trigger, session_minutes)))
def test_Never(self):
should_trigger = Never().should_trigger
for session_minutes in minutes_for_days(self.cal):
self.assertFalse(any(map(should_trigger, session_minutes)))
def test_AfterOpen(self):
minute_groups = minutes_for_days(self.cal, ordered_days=True)
should_trigger = self.after_open.should_trigger
for session_minutes in minute_groups:
for i, minute in enumerate(session_minutes):
# Should only trigger at the 64th minute
if i != 64:
self.assertFalse(should_trigger(minute))
else:
self.assertTrue(should_trigger(minute))
def test_invalid_offset(self):
with self.assertRaises(ValueError):
AfterOpen(hours=12, minutes=1)
with self.assertRaises(ValueError):
AfterOpen(hours=0, minutes=0)
with self.assertRaises(ValueError):
BeforeClose(hours=12, minutes=1)
with self.assertRaises(ValueError):
BeforeClose(hours=0, minutes=0)
def test_BeforeClose(self):
minute_groups = minutes_for_days(self.cal, ordered_days=True)
should_trigger = self.before_close.should_trigger
for minute_group in minute_groups:
for minute in minute_group:
# Should only trigger at the 65th-to-last minute
if minute != minute_group[-66]:
self.assertFalse(should_trigger(minute))
else:
self.assertTrue(should_trigger(minute))
def test_NotHalfDay(self):
rule = NotHalfDay()
rule.cal = self.cal
if self.HALF_SESSION:
for minute in self.cal.minutes_for_session(self.HALF_SESSION):
self.assertFalse(rule.should_trigger(minute))
if self.FULL_SESSION:
for minute in self.cal.minutes_for_session(self.FULL_SESSION):
self.assertTrue(rule.should_trigger(minute))
def test_NthTradingDayOfWeek_day_zero(self):
"""
Test that we don't blow up when trying to call week_start's
should_trigger on the first day of a trading environment.
"""
rule = NthTradingDayOfWeek(0)
rule.cal = self.cal
first_open = self.cal.open_and_close_for_session(
self.cal.all_sessions[0]
)
self.assertTrue(first_open)
def test_NthTradingDayOfWeek(self):
for n in range(MAX_WEEK_RANGE):
rule = NthTradingDayOfWeek(n)
rule.cal = self.cal
should_trigger = rule.should_trigger
prev_period = self.cal.minute_to_session_label(self.sept_week[0])
n_tdays = 0
for minute in self.sept_week:
period = self.cal.minute_to_session_label(minute)
if prev_period < period:
n_tdays += 1
prev_period = period
if should_trigger(minute):
self.assertEqual(n_tdays, n)
else:
self.assertNotEqual(n_tdays, n)
def test_NDaysBeforeLastTradingDayOfWeek(self):
for n in range(MAX_WEEK_RANGE):
rule = NDaysBeforeLastTradingDayOfWeek(n)
rule.cal = self.cal
should_trigger = rule.should_trigger
for minute in self.sept_week:
if should_trigger(minute):
n_tdays = 0
session = self.cal.minute_to_session_label(
minute,
direction="none"
)
next_session = self.cal.next_session_label(session)
while next_session.dayofweek > session.dayofweek:
session = next_session
next_session = self.cal.next_session_label(session)
n_tdays += 1
self.assertEqual(n_tdays, n)
def test_NthTradingDayOfMonth(self):
for n in range(MAX_MONTH_RANGE):
rule = NthTradingDayOfMonth(n)
rule.cal = self.cal
should_trigger = rule.should_trigger
for sessions_list in (self.sept_sessions, self.oct_sessions):
for n_tdays, session in enumerate(sessions_list):
# just check the first 10 minutes of each session
for m in self.cal.minutes_for_session(session)[0:10]:
if should_trigger(m):
self.assertEqual(n_tdays, n)
else:
self.assertNotEqual(n_tdays, n)
def test_NDaysBeforeLastTradingDayOfMonth(self):
for n in range(MAX_MONTH_RANGE):
rule = NDaysBeforeLastTradingDayOfMonth(n)
rule.cal = self.cal
should_trigger = rule.should_trigger
sessions = reversed(self.oct_sessions)
for n_days_before, session in enumerate(sessions):
for m in self.cal.minutes_for_session(session)[0:10]:
if should_trigger(m):
self.assertEqual(n_days_before, n)
else:
self.assertNotEqual(n_days_before, n)
def test_ComposedRule(self):
minute_groups = minutes_for_days(self.cal)
rule1 = Always()
rule2 = Never()
for minute in minute_groups:
composed = rule1 & rule2
should_trigger = composed.should_trigger
self.assertIsInstance(composed, ComposedRule)
self.assertIs(composed.first, rule1)
self.assertIs(composed.second, rule2)
self.assertFalse(any(map(should_trigger, minute)))
@parameterized.expand([
('month_start', NthTradingDayOfMonth),
('month_end', NDaysBeforeLastTradingDayOfMonth),
('week_start', NthTradingDayOfWeek),
('week_end', NthTradingDayOfWeek),
])
def test_pass_float_to_day_of_period_rule(self, name, rule_type):
with warnings.catch_warnings(record=True) as raised_warnings:
warnings.simplefilter('always')
rule_type(n=3) # Shouldn't trigger a warning.
rule_type(n=3.0) # Should trigger a warning about float coercion.
self.assertEqual(len(raised_warnings), 1)
# We only implicitly convert from float to int when there's no loss of
# precision.
with self.assertRaises(TypeError):
rule_type(3.1)
def test_invalid_offsets(self):
with self.assertRaises(ValueError):
NthTradingDayOfWeek(5)
with self.assertRaises(ValueError):
NthTradingDayOfWeek(-1)
with self.assertRaises(ValueError):
NthTradingDayOfMonth(-1)
with self.assertRaises(ValueError):
NthTradingDayOfMonth(24)
class StatefulRulesTests(RuleTestCase):
CALENDAR_STRING = "NYSE"
@classmethod
def setUpClass(cls):
super(StatefulRulesTests, cls).setUpClass()
cls.class_ = StatefulRule
cls.cal = get_calendar(cls.CALENDAR_STRING)
def test_OncePerDay(self):
class RuleCounter(StatefulRule):
"""
A rule that counts the number of times another rule triggers
but forwards the results out.
"""
count = 0
def should_trigger(self, dt):
st = self.rule.should_trigger(dt)
if st:
self.count += 1
return st
for minute_group in minutes_for_days(self.cal):
rule = RuleCounter(OncePerDay())
for minute in minute_group:
rule.should_trigger(minute)
self.assertEqual(rule.count, 1)