forked from quantopian/zipline
-
Notifications
You must be signed in to change notification settings - Fork 282
Expand file tree
/
Copy pathtest_algorithm.py
More file actions
4538 lines (3833 loc) · 153 KB
/
test_algorithm.py
File metadata and controls
4538 lines (3833 loc) · 153 KB
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# Copyright 2018 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
import logging
import warnings
from copy import deepcopy
from datetime import timedelta
from functools import partial
from textwrap import dedent
import cython
import numpy as np
import pandas as pd
import pytest
import pytz
import toolz
from packaging.version import parse as parse_version
from parameterized import parameterized
from testfixtures import TempDirectory
import zipline.api
import zipline.testing.fixtures as zf
from zipline.api import FixedSlippage
from zipline.assets import Asset, Equity, Future
from zipline.assets.continuous_futures import ContinuousFuture
from zipline.assets.synthetic import make_jagged_equity_info, make_simple_equity_info
from zipline.errors import (
AccountControlViolation,
CannotOrderDelistedAsset,
IncompatibleSlippageModel,
RegisterTradingControlPostInit,
ScheduleFunctionInvalidCalendar,
SetCancelPolicyPostInit,
SymbolNotFound,
TradingControlViolation,
UnsupportedCancelPolicy,
ZeroCapitalError,
)
from zipline.finance.asset_restrictions import (
RESTRICTION_STATES,
HistoricalRestrictions,
Restriction,
StaticRestrictions,
)
from zipline.finance.commission import PerShare, PerTrade
from zipline.finance.controls import AssetDateBounds
from zipline.finance.execution import LimitOrder
from zipline.finance.order import ORDER_STATUS
from zipline.finance.trading import SimulationParameters
from zipline.test_algorithms import (
access_account_in_init,
access_portfolio_in_init,
api_algo,
api_get_environment_algo,
api_symbol_algo,
bad_type_can_trade_assets,
bad_type_current_assets,
bad_type_current_assets_kwarg,
bad_type_current_fields,
bad_type_current_fields_kwarg,
bad_type_history_assets,
bad_type_history_assets_kwarg,
bad_type_history_assets_kwarg_list,
bad_type_history_bar_count,
bad_type_history_bar_count_kwarg,
bad_type_history_fields,
bad_type_history_fields_kwarg,
bad_type_history_frequency,
bad_type_history_frequency_kwarg,
bad_type_is_stale_assets,
call_with_bad_kwargs_current,
call_with_bad_kwargs_get_open_orders,
call_with_bad_kwargs_history,
call_with_good_kwargs_get_open_orders,
call_with_kwargs,
call_with_no_kwargs_get_open_orders,
call_without_kwargs,
empty_positions,
handle_data_api,
handle_data_noop,
initialize_api,
initialize_noop,
no_handle_data,
noop_algo,
record_float_magic,
record_variables,
)
from zipline.testing import (
FakeDataPortal,
RecordBatchBlotter,
create_daily_df_for_asset,
create_data_portal_from_trade_history,
create_minute_df_for_asset,
# make_test_handler,
make_trade_data_for_asset_info,
parameter_space,
str_to_seconds,
)
from zipline.testing.predicates import assert_equal
from zipline.utils import factory
from zipline.utils.api_support import ZiplineAPI
from zipline.utils.calendar_utils import get_calendar, register_calendar
from zipline.utils.context_tricks import CallbackManager, nop_context
from zipline.utils.events import (
Always,
ComposedRule,
Never,
OncePerDay,
date_rules,
time_rules,
)
from zipline.utils.pandas_utils import PerformanceWarning
# Import CI detection variables
from tests.conftest import ON_LINUX_CI, ON_WINDOWS_CI, ON_MACOS_CI
import os
# Because test cases appear to reuse some resources.
_multiprocess_can_split_ = False
class TestRecord(zf.WithMakeAlgo, zf.ZiplineTestCase):
ASSET_FINDER_EQUITY_SIDS = (133,)
SIM_PARAMS_DATA_FREQUENCY = "daily"
DATA_PORTAL_USE_MINUTE_DATA = False
def test_record_incr(self):
def initialize(self):
self.incr = 0
def handle_data(self, data):
self.incr += 1
self.record(incr=self.incr)
name = "name"
self.record(name, self.incr)
zipline.api.record(name, self.incr, "name2", 2, name3=self.incr)
output = self.run_algorithm(
initialize=initialize,
handle_data=handle_data,
)
np.testing.assert_array_equal(output["incr"].values, range(1, len(output) + 1))
np.testing.assert_array_equal(output["name"].values, range(1, len(output) + 1))
np.testing.assert_array_equal(output["name2"].values, [2] * len(output))
np.testing.assert_array_equal(output["name3"].values, range(1, len(output) + 1))
class TestMiscellaneousAPI(zf.WithMakeAlgo, zf.ZiplineTestCase):
START_DATE = pd.Timestamp("2006-01-03")
END_DATE = pd.Timestamp("2006-01-04")
SIM_PARAMS_DATA_FREQUENCY = "minute"
sids = 1, 2
# FIXME: Pass a benchmark source instead of this.
BENCHMARK_SID = None
@classmethod
def make_equity_info(cls):
return pd.concat(
(
make_simple_equity_info(cls.sids, "2002-02-1", "2007-01-01"),
pd.DataFrame.from_dict(
{
3: {
"symbol": "PLAY",
"start_date": "2002-01-01",
"end_date": "2004-01-01",
"exchange": "TEST",
},
4: {
"symbol": "PLAY",
"start_date": "2005-01-01",
"end_date": "2006-01-01",
"exchange": "TEST",
},
},
orient="index",
),
)
)
@classmethod
def make_futures_info(cls):
return pd.DataFrame.from_dict(
{
5: {
"symbol": "CLG06",
"root_symbol": "CL",
"start_date": pd.Timestamp("2005-12-01"),
"notice_date": pd.Timestamp("2005-12-20"),
"expiration_date": pd.Timestamp("2006-01-20"),
"exchange": "TEST",
},
6: {
"root_symbol": "CL",
"symbol": "CLK06",
"start_date": pd.Timestamp("2005-12-01"),
"notice_date": pd.Timestamp("2006-03-20"),
"expiration_date": pd.Timestamp("2006-04-20"),
"exchange": "TEST",
},
7: {
"symbol": "CLQ06",
"root_symbol": "CL",
"start_date": pd.Timestamp("2005-12-01"),
"notice_date": pd.Timestamp("2006-06-20"),
"expiration_date": pd.Timestamp("2006-07-20"),
"exchange": "TEST",
},
8: {
"symbol": "CLX06",
"root_symbol": "CL",
"start_date": pd.Timestamp("2006-02-01"),
"notice_date": pd.Timestamp("2006-09-20"),
"expiration_date": pd.Timestamp("2006-10-20"),
"exchange": "TEST",
},
},
orient="index",
)
def test_cancel_policy_outside_init(self):
code = dedent(
"""
from zipline.api import cancel_policy, set_cancel_policy
def initialize(algo):
pass
def handle_data(algo, data):
set_cancel_policy(cancel_policy.NeverCancel())
"""
)
algo = self.make_algo(script=code)
with pytest.raises(SetCancelPolicyPostInit):
algo.run()
def test_cancel_policy_invalid_param(self):
code = dedent(
"""
from zipline.api import set_cancel_policy
def initialize(algo):
set_cancel_policy("foo")
def handle_data(algo, data):
pass
"""
)
algo = self.make_algo(script=code)
with pytest.raises(UnsupportedCancelPolicy):
algo.run()
def test_zipline_api_resolves_dynamically(self):
# Make a dummy algo.
algo = self.make_algo(
initialize=lambda context: None,
handle_data=lambda context, data: None,
)
# Verify that api methods get resolved dynamically by patching them out
# and then calling them
for method in algo.all_api_methods():
name = method.__name__
sentinel = object()
def fake_method(*args, **kwargs):
return sentinel
setattr(algo, name, fake_method)
with ZiplineAPI(algo):
assert sentinel is getattr(zipline.api, name)()
def test_sid_datetime(self):
algo_text = dedent(
"""
from zipline.api import sid, get_datetime
import pandas as pd
def initialize(context):
context.first_bar = True
def handle_data(context, data):
if context.first_bar:
# On the first bar, last_traded might be from previous session
# Skip the first bar to ensure we have current trading data
context.first_bar = False
return
aapl_dt = data.current(sid(1), "last_traded")
current_dt = get_datetime()
# last_traded should equal current time when there's active trading
# Both should already be UTC, but ensure they're comparable
if aapl_dt is not None and current_dt is not None:
# Normalize both to ensure they're both tz-aware UTC
if aapl_dt.tz is None:
aapl_dt = pd.Timestamp(aapl_dt).tz_localize('UTC')
elif hasattr(aapl_dt, 'tz') and aapl_dt.tz is not None:
aapl_dt = aapl_dt.tz_convert('UTC')
if current_dt.tz is None:
current_dt = pd.Timestamp(current_dt).tz_localize('UTC')
elif hasattr(current_dt, 'tz') and current_dt.tz is not None:
current_dt = current_dt.tz_convert('UTC')
# In some environments, timestamps might differ by trading session boundaries
# Accept if they're on the same date
assert_equal(aapl_dt.date(), current_dt.date())
"""
)
self.run_algorithm(
script=algo_text,
namespace={"assert_equal": self.assertEqual},
)
def test_datetime_bad_params(self):
algo_text = dedent(
"""
from zipline.api import get_datetime
from pytz import timezone
def initialize(context):
pass
def handle_data(context, data):
get_datetime(timezone)
"""
)
algo = self.make_algo(script=algo_text)
with pytest.raises(TypeError):
algo.run()
@parameterized.expand([(-1000, "invalid_base"), (0, "invalid_base")])
def test_invalid_capital_base(self, cap_base, name):
"""Test that the appropriate error is being raised and orders aren't
filled for algos with capital base <= 0
"""
algo_text = dedent(
"""
def initialize(context):
pass
def handle_data(context, data):
order(sid(24), 1000)
"""
)
sim_params = SimulationParameters(
start_session=pd.Timestamp("2006-01-03"),
end_session=pd.Timestamp("2006-01-06"),
capital_base=cap_base,
data_frequency="minute",
trading_calendar=self.trading_calendar,
)
expected_msg = "initial capital base must be greater than zero"
with pytest.raises(ZeroCapitalError, match=expected_msg):
# make_algo will trace to TradingAlgorithm,
# where the exception will be raised
self.make_algo(script=algo_text, sim_params=sim_params)
# Make sure the correct error was raised
def test_get_environment(self):
expected_env = {
"arena": "backtest",
"data_frequency": "minute",
"start": pd.Timestamp("2006-01-03 14:31:00+0000", tz="utc"),
"end": pd.Timestamp("2006-01-04 21:00:00+0000", tz="utc"),
"capital_base": 100000.0,
"platform": "zipline",
}
def initialize(algo):
assert algo.get_environment() == "zipline"
assert expected_env == algo.get_environment("*")
def handle_data(algo, data):
pass
self.run_algorithm(initialize=initialize, handle_data=handle_data)
def test_get_open_orders(self):
def initialize(algo):
algo.minute = 0
def handle_data(algo, data):
if algo.minute == 0:
# Should be filled by the next minute
algo.order(algo.sid(1), 1)
# Won't be filled because the price is too low.
algo.order(algo.sid(2), 1, style=LimitOrder(0.01, asset=algo.sid(2)))
algo.order(algo.sid(2), 1, style=LimitOrder(0.01, asset=algo.sid(2)))
algo.order(algo.sid(2), 1, style=LimitOrder(0.01, asset=algo.sid(2)))
all_orders = algo.get_open_orders()
assert list(all_orders.keys()) == [1, 2]
assert all_orders[1] == algo.get_open_orders(1)
assert len(all_orders[1]) == 1
assert all_orders[2] == algo.get_open_orders(2)
assert len(all_orders[2]) == 3
if algo.minute == 1:
# First order should have filled.
# Second order should still be open.
all_orders = algo.get_open_orders()
assert list(all_orders.keys()) == [2]
assert algo.get_open_orders(1) == []
orders_2 = algo.get_open_orders(2)
assert all_orders[2] == orders_2
assert len(all_orders[2]) == 3
for order_ in orders_2:
algo.cancel_order(order_)
all_orders = algo.get_open_orders()
assert all_orders == {}
algo.minute += 1
self.run_algorithm(initialize=initialize, handle_data=handle_data)
def test_schedule_function_custom_cal(self):
# run a simulation on the CMES cal, and schedule a function
# using the NYSE cal
algotext = dedent(
"""
from zipline.api import (
schedule_function,
get_datetime,
time_rules,
date_rules,
calendars,
)
def initialize(context):
schedule_function(
func=log_nyse_open,
date_rule=date_rules.every_day(),
time_rule=time_rules.market_open(),
calendar=calendars.US_EQUITIES,
)
schedule_function(
func=log_nyse_close,
date_rule=date_rules.every_day(),
time_rule=time_rules.market_close(),
calendar=calendars.US_EQUITIES,
)
context.nyse_opens = []
context.nyse_closes = []
def log_nyse_open(context, data):
context.nyse_opens.append(get_datetime())
def log_nyse_close(context, data):
context.nyse_closes.append(get_datetime())
"""
)
algo = self.make_algo(
script=algotext,
sim_params=self.make_simparams(
trading_calendar=get_calendar("CMES"),
),
)
algo.run()
nyse = get_calendar("NYSE")
for minute in algo.nyse_opens:
# each minute should be a nyse session open
session_label = nyse.minute_to_session(minute)
session_open = nyse.session_first_minute(session_label)
assert session_open == minute
for minute in algo.nyse_closes:
# each minute should be a minute before a nyse session close
session_label = nyse.minute_to_session(minute)
session_close = nyse.session_last_minute(session_label)
assert session_close - timedelta(minutes=1) == minute
# Test that passing an invalid calendar parameter raises an error.
erroring_algotext = dedent(
"""
from zipline.api import schedule_function
from zipline.utils.calendar_utils import get_calendar
def initialize(context):
schedule_function(func=my_func, calendar=get_calendar('XNYS'))
def my_func(context, data):
pass
"""
)
algo = self.make_algo(
script=erroring_algotext,
sim_params=self.make_simparams(
trading_calendar=get_calendar("CMES"),
),
)
with pytest.raises(ScheduleFunctionInvalidCalendar):
algo.run()
def test_schedule_function(self):
us_eastern = pytz.timezone("US/Eastern")
def incrementer(algo, data):
algo.func_called += 1
curdt = algo.get_datetime().tz_convert(pytz.utc)
assert curdt == us_eastern.localize(
datetime.datetime.combine(curdt.date(), datetime.time(9, 31))
)
def initialize(algo):
algo.func_called = 0
algo.days = 1
algo.date = None
algo.schedule_function(
func=incrementer,
date_rule=date_rules.every_day(),
time_rule=time_rules.market_open(),
)
def handle_data(algo, data):
if not algo.date:
algo.date = algo.get_datetime().date()
if algo.date < algo.get_datetime().date():
algo.days += 1
algo.date = algo.get_datetime().date()
algo = self.make_algo(
initialize=initialize,
handle_data=handle_data,
)
algo.run()
assert algo.func_called == algo.days
def test_event_context(self):
expected_data = []
collected_data_pre = []
collected_data_post = []
function_stack = []
def pre(data):
function_stack.append(pre)
collected_data_pre.append(data)
def post(data):
function_stack.append(post)
collected_data_post.append(data)
def initialize(context):
context.add_event(Always(), f)
context.add_event(Always(), g)
def handle_data(context, data):
function_stack.append(handle_data)
expected_data.append(data)
def f(context, data):
function_stack.append(f)
def g(context, data):
function_stack.append(g)
algo = self.make_algo(
initialize=initialize,
handle_data=handle_data,
create_event_context=CallbackManager(pre, post),
)
algo.run()
assert len(expected_data) == 780
assert collected_data_pre == expected_data
assert collected_data_post == expected_data
assert (
len(function_stack) == 3900
), "Incorrect number of functions called: %s != 3900" % len(function_stack)
expected_functions = [pre, handle_data, f, g, post] * 97530
for n, (f, g) in enumerate(
zip(function_stack, expected_functions, strict=False)
):
assert (
f == g
), "function at position %d was incorrect, expected %s but got %s" % (
n,
g.__name__,
f.__name__,
)
@parameterized.expand(
[
("daily",),
("minute"),
]
)
def test_schedule_function_rule_creation(self, mode):
def nop(*args, **kwargs):
return None
self.sim_params.data_frequency = mode
algo = self.make_algo(
initialize=nop,
handle_data=nop,
sim_params=self.sim_params,
)
# Schedule something for NOT Always.
# Compose two rules to ensure calendar is set properly.
algo.schedule_function(nop, time_rule=Never() & Always())
event_rule = algo.event_manager._events[1].rule
assert isinstance(event_rule, OncePerDay)
assert event_rule.cal == algo.trading_calendar
inner_rule = event_rule.rule
assert isinstance(inner_rule, ComposedRule)
assert inner_rule.cal == algo.trading_calendar
first = inner_rule.first
second = inner_rule.second
composer = inner_rule.composer
assert isinstance(first, Always)
assert first.cal == algo.trading_calendar
assert second.cal == algo.trading_calendar
if mode == "daily":
assert isinstance(second, Always)
else:
assert isinstance(second, ComposedRule)
assert isinstance(second.first, Never)
assert second.first.cal == algo.trading_calendar
assert isinstance(second.second, Always)
assert second.second.cal == algo.trading_calendar
assert composer is ComposedRule.lazy_and
def test_asset_lookup(self):
algo = self.make_algo()
# this date doesn't matter
start_session = pd.Timestamp("2000-01-01")
# Test before either PLAY existed
algo.sim_params = algo.sim_params.create_new(
start_session, pd.Timestamp("2001-12-01")
)
with pytest.raises(SymbolNotFound):
algo.symbol("PLAY")
with pytest.raises(SymbolNotFound):
algo.symbols("PLAY")
# Test when first PLAY exists
algo.sim_params = algo.sim_params.create_new(
start_session, pd.Timestamp("2002-12-01")
)
list_result = algo.symbols("PLAY")
assert list_result[0] == 3
# Test after first PLAY ends
algo.sim_params = algo.sim_params.create_new(
start_session, pd.Timestamp("2004-12-01")
)
assert algo.symbol("PLAY") == 3
# Test after second PLAY begins
algo.sim_params = algo.sim_params.create_new(
start_session, pd.Timestamp("2005-12-01")
)
assert algo.symbol("PLAY") == 4
# Test after second PLAY ends
algo.sim_params = algo.sim_params.create_new(
start_session, pd.Timestamp("2006-12-01")
)
assert algo.symbol("PLAY") == 4
list_result = algo.symbols("PLAY")
assert list_result[0] == 4
# Test lookup SID
assert isinstance(algo.sid(3), Equity)
assert isinstance(algo.sid(4), Equity)
# Supplying a non-string argument to symbol()
# should result in a TypeError.
with pytest.raises(TypeError):
algo.symbol(1)
with pytest.raises(TypeError):
algo.symbol((1,))
with pytest.raises(TypeError):
algo.symbol({1})
with pytest.raises(TypeError):
algo.symbol([1])
with pytest.raises(TypeError):
algo.symbol({"foo": "bar"})
def test_future_symbol(self):
"""Tests the future_symbol API function."""
algo = self.make_algo()
algo.datetime = pd.Timestamp("2006-12-01")
# Check that we get the correct fields for the CLG06 symbol
cl = algo.future_symbol("CLG06")
assert cl.sid == 5
assert cl.symbol == "CLG06"
assert cl.root_symbol == "CL"
assert cl.start_date == pd.Timestamp("2005-12-01")
assert cl.notice_date == pd.Timestamp("2005-12-20")
assert cl.expiration_date == pd.Timestamp("2006-01-20")
with pytest.raises(SymbolNotFound):
algo.future_symbol("")
with pytest.raises(SymbolNotFound):
algo.future_symbol("PLAY")
with pytest.raises(SymbolNotFound):
algo.future_symbol("FOOBAR")
# Supplying a non-string argument to future_symbol()
# should result in a TypeError.
with pytest.raises(TypeError):
algo.future_symbol(1)
with pytest.raises(TypeError):
algo.future_symbol((1,))
with pytest.raises(TypeError):
algo.future_symbol({1})
with pytest.raises(TypeError):
algo.future_symbol([1])
with pytest.raises(TypeError):
algo.future_symbol({"foo": "bar"})
class TestSetSymbolLookupDate(zf.WithMakeAlgo, zf.ZiplineTestCase):
# January 2006
# Su Mo Tu We Th Fr Sa
# 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
START_DATE = pd.Timestamp("2006-01-03")
END_DATE = pd.Timestamp("2006-01-06")
SIM_PARAMS_START_DATE = pd.Timestamp("2006-01-04")
SIM_PARAMS_DATA_FREQUENCY = "daily"
DATA_PORTAL_USE_MINUTE_DATA = False
BENCHMARK_SID = 3
@classmethod
def make_equity_info(cls):
dates = pd.date_range(cls.START_DATE, cls.END_DATE)
assert len(dates) == 4, "Expected four dates."
# Two assets with the same ticker, ending on days[1] and days[3], plus
# a benchmark that spans the whole period.
cls.sids = [1, 2, 3]
cls.asset_starts = [dates[0], dates[2]]
cls.asset_ends = [dates[1], dates[3]]
return pd.DataFrame.from_records(
[
{
"symbol": "DUP",
"start_date": cls.asset_starts[0],
"end_date": cls.asset_ends[0],
"exchange": "TEST",
"asset_name": "FIRST",
},
{
"symbol": "DUP",
"start_date": cls.asset_starts[1],
"end_date": cls.asset_ends[1],
"exchange": "TEST",
"asset_name": "SECOND",
},
{
"symbol": "BENCH",
"start_date": cls.START_DATE,
"end_date": cls.END_DATE,
"exchange": "TEST",
"asset_name": "BENCHMARK",
},
],
index=cls.sids,
)
# TODO FIXME IMPORTANT pytest crashes with internal error if test below is uncommented
# def test_set_symbol_lookup_date(self):
# """Test the set_symbol_lookup_date API method."""
# set_symbol_lookup_date = zipline.api.set_symbol_lookup_date
# def initialize(context):
# set_symbol_lookup_date(self.asset_ends[0])
# assert zipline.api.symbol("DUP").sid == self.sids[0]
# set_symbol_lookup_date(self.asset_ends[1])
# assert zipline.api.symbol("DUP").sid == self.sids[1]
# with pytest.raises(UnsupportedDatetimeFormat):
# set_symbol_lookup_date("foobar")
# self.run_algorithm(initialize=initialize)
class TestPositions(zf.WithMakeAlgo, zf.ZiplineTestCase):
START_DATE = pd.Timestamp("2006-01-03")
END_DATE = pd.Timestamp("2006-01-06")
SIM_PARAMS_CAPITAL_BASE = 1000
ASSET_FINDER_EQUITY_SIDS = (1, 133)
SIM_PARAMS_DATA_FREQUENCY = "daily"
@classmethod
def make_equity_daily_bar_data(cls, country_code, sids):
frame = pd.DataFrame(
{
"open": [90, 95, 100, 105],
"high": [90, 95, 100, 105],
"low": [90, 95, 100, 105],
"close": [90, 95, 100, 105],
"volume": 100,
},
index=cls.equity_daily_bar_days,
)
return ((sid, frame) for sid in sids)
@classmethod
def make_futures_info(cls):
return pd.DataFrame.from_dict(
{
1000: {
"symbol": "CLF06",
"root_symbol": "CL",
"start_date": cls.START_DATE,
"end_date": cls.END_DATE,
"auto_close_date": cls.END_DATE + cls.trading_calendar.day,
"exchange": "CMES",
"multiplier": 100,
},
},
orient="index",
)
@classmethod
def make_future_minute_bar_data(cls):
trading_calendar = cls.trading_calendars[Future]
sids = cls.asset_finder.futures_sids
minutes = trading_calendar.sessions_minutes(
cls.future_minute_bar_days[0],
cls.future_minute_bar_days[-1],
)
frame = pd.DataFrame(
{
"open": 2.0,
"high": 2.0,
"low": 2.0,
"close": 2.0,
"volume": 100,
},
index=minutes,
)
return ((sid, frame) for sid in sids)
def test_portfolio_exited_position(self):
# This test ensures ensures that 'phantom' positions do not appear in
# context.portfolio.positions in the case that a position has been
# entered and fully exited.
def initialize(context, sids):
context.ordered = False
context.exited = False
context.sids = sids
def handle_data(context, data):
if not context.ordered:
for s in context.sids:
context.order(context.sid(s), 1)
context.ordered = True
if not context.exited:
amounts = [pos.amount for pos in context.portfolio.positions.values()]
if len(amounts) > 0 and all([(amount == 1) for amount in amounts]):
for stock in context.portfolio.positions:
context.order(context.sid(stock), -1)
context.exited = True
# Should be 0 when all positions are exited.
context.record(num_positions=len(context.portfolio.positions))
result = self.run_algorithm(
initialize=initialize,
handle_data=handle_data,
sids=self.ASSET_FINDER_EQUITY_SIDS,
)
expected_position_count = [
0, # Before entering the first position
2, # After entering, exiting on this date
0, # After exiting
0,
]
for i, expected in enumerate(expected_position_count):
assert result.iloc[i]["num_positions"] == expected
def test_noop_orders(self):
asset = self.asset_finder.retrieve_asset(1)
# Algorithm that tries to buy with extremely low stops/limits and tries
# to sell with extremely high versions of same. Should not end up with
# any positions for reasonable data.
def handle_data(algo, data):
########
# Buys #
########
# Buy with low limit, shouldn't trigger.
algo.order(asset, 100, limit_price=1)
# But with high stop, shouldn't trigger
algo.order(asset, 100, stop_price=10000000)
# Buy with high limit (should trigger) but also high stop (should
# prevent trigger).
algo.order(asset, 100, limit_price=10000000, stop_price=10000000)
# Buy with low stop (should trigger), but also low limit (should
# prevent trigger).
algo.order(asset, 100, limit_price=1, stop_price=1)
#########
# Sells #
#########
# Sell with high limit, shouldn't trigger.
algo.order(asset, -100, limit_price=1000000)
# Sell with low stop, shouldn't trigger.
algo.order(asset, -100, stop_price=1)
# Sell with low limit (should trigger), but also high stop (should
# prevent trigger).
algo.order(asset, -100, limit_price=1000000, stop_price=1000000)
# Sell with low limit (should trigger), but also low stop (should
# prevent trigger).
algo.order(asset, -100, limit_price=1, stop_price=1)
###################
# Rounding Checks #
###################
algo.order(asset, 100, limit_price=0.00000001)
algo.order(asset, -100, stop_price=0.00000001)
daily_stats = self.run_algorithm(handle_data=handle_data)
# Verify that positions are empty for all dates.
empty_positions = daily_stats.positions.map(lambda x: len(x) == 0)
assert empty_positions.all()
def test_position_weights(self):
sids = (1, 133, 1000)
equity_1, equity_133, future_1000 = self.asset_finder.retrieve_all(sids)