forked from scrtlabs/catalyst
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathalgorithm.py
2503 lines (2159 loc) · 88 KB
/
algorithm.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
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 2015 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.
from collections import Iterable
try:
# optional cython based OrderedDict
from cyordereddict import OrderedDict
except ImportError:
from collections import OrderedDict
from copy import copy
import operator as op
import warnings
from datetime import tzinfo, time
import logbook
import pytz
import pandas as pd
from contextlib2 import ExitStack
from pandas.tseries.tools import normalize_date
import numpy as np
from itertools import chain, repeat
from numbers import Integral
from six import (
exec_,
iteritems,
itervalues,
string_types,
viewkeys,
viewvalues,
)
from zipline._protocol import handle_non_market_minutes
from zipline.assets.synthetic import make_simple_equity_info
from zipline.data.data_portal import DataPortal
from zipline.data.us_equity_pricing import PanelBarReader
from zipline.errors import (
AttachPipelineAfterInitialize,
HistoryInInitialize,
NoSuchPipeline,
OrderDuringInitialize,
PipelineOutputDuringInitialize,
RegisterAccountControlPostInit,
RegisterTradingControlPostInit,
SetBenchmarkOutsideInitialize,
SetCommissionPostInit,
SetSlippagePostInit,
UnsupportedCommissionModel,
UnsupportedDatetimeFormat,
UnsupportedOrderParameters,
UnsupportedSlippageModel,
CannotOrderDelistedAsset,
UnsupportedCancelPolicy,
SetCancelPolicyPostInit,
OrderInBeforeTradingStart
)
from zipline.finance.trading import TradingEnvironment
from zipline.finance.blotter import Blotter
from zipline.finance.commission import PerShare, CommissionModel
from zipline.finance.controls import (
LongOnly,
MaxOrderCount,
MaxOrderSize,
MaxPositionSize,
MaxLeverage,
RestrictedListOrder
)
from zipline.finance.execution import (
LimitOrder,
MarketOrder,
StopLimitOrder,
StopOrder,
)
from zipline.finance.performance import PerformanceTracker
from zipline.finance.asset_restrictions import Restrictions
from zipline.finance.slippage import (
VolumeShareSlippage,
SlippageModel
)
from zipline.finance.cancel_policy import NeverCancel, CancelPolicy
from zipline.finance.asset_restrictions import (
NoRestrictions,
StaticRestrictions,
SecurityListRestrictions,
)
from zipline.assets import Asset, Future
from zipline.gens.tradesimulation import AlgorithmSimulator
from zipline.pipeline import Pipeline
from zipline.pipeline.engine import (
ExplodingPipelineEngine,
SimplePipelineEngine,
)
from zipline.utils.api_support import (
api_method,
require_initialized,
require_not_initialized,
ZiplineAPI,
disallowed_in_before_trading_start)
from zipline.utils.input_validation import (
coerce_string,
ensure_upper_case,
error_keywords,
expect_types,
optional,
)
from zipline.utils.calendars.trading_calendar import days_at_time
from zipline.utils.cache import CachedObject, Expired
from zipline.utils.calendars import get_calendar
from zipline.utils.compat import exc_clear
import zipline.utils.events
from zipline.utils.events import (
EventManager,
make_eventrule,
date_rules,
time_rules,
AfterOpen,
BeforeClose
)
from zipline.utils.factory import create_simulation_parameters
from zipline.utils.math_utils import (
tolerant_equals,
round_if_near_integer
)
from zipline.utils.pandas_utils import clear_dataframe_indexer_caches
from zipline.utils.preprocess import preprocess
from zipline.utils.security_list import SecurityList
import zipline.protocol
from zipline.sources.requests_csv import PandasRequestsCSV
from zipline.gens.sim_engine import MinuteSimulationClock
from zipline.sources.benchmark_source import BenchmarkSource
from zipline.zipline_warnings import ZiplineDeprecationWarning
log = logbook.Logger("ZiplineLog")
class TradingAlgorithm(object):
"""A class that represents a trading strategy and parameters to execute
the strategy.
Parameters
----------
*args, **kwargs
Forwarded to ``initialize`` unless listed below.
initialize : callable[context -> None], optional
Function that is called at the start of the simulation to
setup the initial context.
handle_data : callable[(context, data) -> None], optional
Function called on every bar. This is where most logic should be
implemented.
before_trading_start : callable[(context, data) -> None], optional
Function that is called before any bars have been processed each
day.
analyze : callable[(context, DataFrame) -> None], optional
Function that is called at the end of the backtest. This is passed
the context and the performance results for the backtest.
script : str, optional
Algoscript that contains the definitions for the four algorithm
lifecycle functions and any supporting code.
namespace : dict, optional
The namespace to execute the algoscript in. By default this is an
empty namespace that will include only python built ins.
algo_filename : str, optional
The filename for the algoscript. This will be used in exception
tracebacks. default: '<string>'.
data_frequency : {'daily', 'minute'}, optional
The duration of the bars.
instant_fill : bool, optional
Whether to fill orders immediately or on next bar. default: False
equities_metadata : dict or DataFrame or file-like object, optional
If dict is provided, it must have the following structure:
* keys are the identifiers
* values are dicts containing the metadata, with the metadata
field name as the key
If pandas.DataFrame is provided, it must have the
following structure:
* column names must be the metadata fields
* index must be the different asset identifiers
* array contents should be the metadata value
If an object with a ``read`` method is provided, ``read`` must
return rows containing at least one of 'sid' or 'symbol' along
with the other metadata fields.
futures_metadata : dict or DataFrame or file-like object, optional
The same layout as ``equities_metadata`` except that it is used
for futures information.
identifiers : list, optional
Any asset identifiers that are not provided in the
equities_metadata, but will be traded by this TradingAlgorithm.
get_pipeline_loader : callable[BoundColumn -> PipelineLoader], optional
The function that maps pipeline columns to their loaders.
create_event_context : callable[BarData -> context manager], optional
A function used to create a context mananger that wraps the
execution of all events that are scheduled for a bar.
This function will be passed the data for the bar and should
return the actual context manager that will be entered.
history_container_class : type, optional
The type of history container to use. default: HistoryContainer
platform : str, optional
The platform the simulation is running on. This can be queried for
in the simulation with ``get_environment``. This allows algorithms
to conditionally execute code based on platform it is running on.
default: 'zipline'
"""
def __init__(self, *args, **kwargs):
"""Initialize sids and other state variables.
:Arguments:
:Optional:
initialize : function
Function that is called with a single
argument at the begninning of the simulation.
handle_data : function
Function that is called with 2 arguments
(context and data) on every bar.
script : str
Algoscript that contains initialize and
handle_data function definition.
data_frequency : {'daily', 'minute'}
The duration of the bars.
capital_base : float <default: 1.0e5>
How much capital to start with.
asset_finder : An AssetFinder object
A new AssetFinder object to be used in this TradingEnvironment
equities_metadata : can be either:
- dict
- pandas.DataFrame
- object with 'read' property
If dict is provided, it must have the following structure:
* keys are the identifiers
* values are dicts containing the metadata, with the metadata
field name as the key
If pandas.DataFrame is provided, it must have the
following structure:
* column names must be the metadata fields
* index must be the different asset identifiers
* array contents should be the metadata value
If an object with a 'read' property is provided, 'read' must
return rows containing at least one of 'sid' or 'symbol' along
with the other metadata fields.
identifiers : List
Any asset identifiers that are not provided in the
equities_metadata, but will be traded by this TradingAlgorithm
"""
self.sources = []
# List of trading controls to be used to validate orders.
self.trading_controls = []
# List of account controls to be checked on each bar.
self.account_controls = []
self._recorded_vars = {}
self.namespace = kwargs.pop('namespace', {})
self._platform = kwargs.pop('platform', 'zipline')
self.logger = None
self.data_portal = kwargs.pop('data_portal', None)
# If an env has been provided, pop it
self.trading_environment = kwargs.pop('env', None)
if self.trading_environment is None:
self.trading_environment = TradingEnvironment()
# Update the TradingEnvironment with the provided asset metadata
if 'equities_metadata' in kwargs or 'futures_metadata' in kwargs:
warnings.warn(
'passing metadata to TradingAlgorithm is deprecated; please'
' write this data into the asset db before passing it to the'
' trading environment',
DeprecationWarning,
stacklevel=1,
)
self.trading_environment.write_data(
equities=kwargs.pop('equities_metadata', None),
futures=kwargs.pop('futures_metadata', None),
)
# If a schedule has been provided, pop it. Otherwise, use NYSE.
self.trading_calendar = kwargs.pop(
'trading_calendar',
get_calendar("NYSE")
)
self.sim_params = kwargs.pop('sim_params', None)
if self.sim_params is None:
self.sim_params = create_simulation_parameters(
start=kwargs.pop('start', None),
end=kwargs.pop('end', None),
trading_calendar=self.trading_calendar,
)
self.perf_tracker = None
# Pull in the environment's new AssetFinder for quick reference
self.asset_finder = self.trading_environment.asset_finder
# Initialize Pipeline API data.
self.init_engine(kwargs.pop('get_pipeline_loader', None))
self._pipelines = {}
# Create an always-expired cache so that we compute the first time data
# is requested.
self._pipeline_cache = CachedObject(None, pd.Timestamp(0, tz='UTC'))
self.blotter = kwargs.pop('blotter', None)
self.cancel_policy = kwargs.pop('cancel_policy', NeverCancel())
if not self.blotter:
self.blotter = Blotter(
data_frequency=self.data_frequency,
asset_finder=self.asset_finder,
slippage_func=VolumeShareSlippage(),
commission=PerShare(),
# Default to NeverCancel in zipline
cancel_policy=self.cancel_policy
)
# The symbol lookup date specifies the date to use when resolving
# symbols to sids, and can be set using set_symbol_lookup_date()
self._symbol_lookup_date = None
self.portfolio_needs_update = True
self.account_needs_update = True
self.performance_needs_update = True
self._portfolio = None
self._account = None
# If string is passed in, execute and get reference to
# functions.
self.algoscript = kwargs.pop('script', None)
self._initialize = None
self._before_trading_start = None
self._analyze = None
self._in_before_trading_start = False
self.event_manager = EventManager(
create_context=kwargs.pop('create_event_context', None),
)
self._handle_data = None
def noop(*args, **kwargs):
pass
if self.algoscript is not None:
api_methods = {
'initialize',
'handle_data',
'before_trading_start',
'analyze',
}
unexpected_api_methods = viewkeys(kwargs) & api_methods
if unexpected_api_methods:
raise ValueError(
"TradingAlgorithm received a script and the following API"
" methods as functions:\n{funcs}".format(
funcs=unexpected_api_methods,
)
)
filename = kwargs.pop('algo_filename', None)
if filename is None:
filename = '<string>'
code = compile(self.algoscript, filename, 'exec')
exec_(code, self.namespace)
self._initialize = self.namespace.get('initialize', noop)
self._handle_data = self.namespace.get('handle_data', noop)
self._before_trading_start = self.namespace.get(
'before_trading_start',
)
# Optional analyze function, gets called after run
self._analyze = self.namespace.get('analyze')
else:
self._initialize = kwargs.pop('initialize', noop)
self._handle_data = kwargs.pop('handle_data', noop)
self._before_trading_start = kwargs.pop(
'before_trading_start',
None,
)
self._analyze = kwargs.pop('analyze', None)
self.event_manager.add_event(
zipline.utils.events.Event(
zipline.utils.events.Always(),
# We pass handle_data.__func__ to get the unbound method.
# We will explicitly pass the algorithm to bind it again.
self.handle_data.__func__,
),
prepend=True,
)
# Alternative way of setting data_frequency for backwards
# compatibility.
if 'data_frequency' in kwargs:
self.data_frequency = kwargs.pop('data_frequency')
# Prepare the algo for initialization
self.initialized = False
self.initialize_args = args
self.initialize_kwargs = kwargs
self.benchmark_sid = kwargs.pop('benchmark_sid', None)
# A dictionary of capital changes, keyed by timestamp, indicating the
# target/delta of the capital changes, along with values
self.capital_changes = kwargs.pop('capital_changes', {})
# A dictionary of the actual capital change deltas, keyed by timestamp
self.capital_change_deltas = {}
self.restrictions = NoRestrictions()
def init_engine(self, get_loader):
"""
Construct and store a PipelineEngine from loader.
If get_loader is None, constructs an ExplodingPipelineEngine
"""
if get_loader is not None:
self.engine = SimplePipelineEngine(
get_loader,
self.trading_calendar.all_sessions,
self.asset_finder,
)
else:
self.engine = ExplodingPipelineEngine()
def initialize(self, *args, **kwargs):
"""
Call self._initialize with `self` made available to Zipline API
functions.
"""
with ZiplineAPI(self):
self._initialize(self, *args, **kwargs)
def before_trading_start(self, data):
if self._before_trading_start is None:
return
self._in_before_trading_start = True
with handle_non_market_minutes(data) if \
self.data_frequency == "minute" else ExitStack():
self._before_trading_start(self, data)
self._in_before_trading_start = False
def handle_data(self, data):
if self._handle_data:
self._handle_data(self, data)
# Unlike trading controls which remain constant unless placing an
# order, account controls can change each bar. Thus, must check
# every bar no matter if the algorithm places an order or not.
self.validate_account_controls()
def analyze(self, perf):
if self._analyze is None:
return
with ZiplineAPI(self):
self._analyze(self, perf)
def __repr__(self):
"""
N.B. this does not yet represent a string that can be used
to instantiate an exact copy of an algorithm.
However, it is getting close, and provides some value as something
that can be inspected interactively.
"""
return """
{class_name}(
capital_base={capital_base}
sim_params={sim_params},
initialized={initialized},
slippage={slippage},
commission={commission},
blotter={blotter},
recorded_vars={recorded_vars})
""".strip().format(class_name=self.__class__.__name__,
capital_base=self.sim_params.capital_base,
sim_params=repr(self.sim_params),
initialized=self.initialized,
slippage=repr(self.blotter.slippage_func),
commission=repr(self.blotter.commission),
blotter=repr(self.blotter),
recorded_vars=repr(self.recorded_vars))
def _create_clock(self):
"""
If the clock property is not set, then create one based on frequency.
"""
trading_o_and_c = self.trading_calendar.schedule.ix[
self.sim_params.sessions]
market_closes = trading_o_and_c['market_close']
minutely_emission = False
if self.sim_params.data_frequency == 'minute':
market_opens = trading_o_and_c['market_open']
minutely_emission = self.sim_params.emission_rate == "minute"
else:
# in daily mode, we want to have one bar per session, timestamped
# as the last minute of the session.
market_opens = market_closes
# The calendar's execution times are the minutes over which we actually
# want to run the clock. Typically the execution times simply adhere to
# the market open and close times. In the case of the futures calendar,
# for example, we only want to simulate over a subset of the full 24
# hour calendar, so the execution times dictate a market open time of
# 6:31am US/Eastern and a close of 5:00pm US/Eastern.
execution_opens = \
self.trading_calendar.execution_time_from_open(market_opens)
execution_closes = \
self.trading_calendar.execution_time_from_close(market_closes)
# FIXME generalize these values
before_trading_start_minutes = days_at_time(
self.sim_params.sessions,
time(8, 45),
"US/Eastern"
)
return MinuteSimulationClock(
self.sim_params.sessions,
execution_opens,
execution_closes,
before_trading_start_minutes,
minute_emission=minutely_emission,
)
def _create_benchmark_source(self):
return BenchmarkSource(
benchmark_sid=self.benchmark_sid,
env=self.trading_environment,
trading_calendar=self.trading_calendar,
sessions=self.sim_params.sessions,
data_portal=self.data_portal,
emission_rate=self.sim_params.emission_rate,
)
def _create_generator(self, sim_params):
if sim_params is not None:
self.sim_params = sim_params
if self.perf_tracker is None:
# HACK: When running with the `run` method, we set perf_tracker to
# None so that it will be overwritten here.
self.perf_tracker = PerformanceTracker(
sim_params=self.sim_params,
trading_calendar=self.trading_calendar,
env=self.trading_environment,
)
# Set the dt initially to the period start by forcing it to change.
self.on_dt_changed(self.sim_params.start_session)
if not self.initialized:
self.initialize(*self.initialize_args, **self.initialize_kwargs)
self.initialized = True
self.trading_client = AlgorithmSimulator(
self,
sim_params,
self.data_portal,
self._create_clock(),
self._create_benchmark_source(),
self.restrictions,
universe_func=self._calculate_universe
)
return self.trading_client.transform()
def _calculate_universe(self):
# this exists to provide backwards compatibility for older,
# deprecated APIs, particularly around the iterability of
# BarData (ie, 'for sid in data`).
# our universe is all the assets passed into `run`.
return self._assets_from_source
def get_generator(self):
"""
Override this method to add new logic to the construction
of the generator. Overrides can use the _create_generator
method to get a standard construction generator.
"""
return self._create_generator(self.sim_params)
def run(self, data=None, overwrite_sim_params=True):
"""Run the algorithm.
:Arguments:
source : DataPortal
:Returns:
daily_stats : pandas.DataFrame
Daily performance metrics such as returns, alpha etc.
"""
self._assets_from_source = []
if isinstance(data, DataPortal):
self.data_portal = data
# define the universe as all the assets in the assetfinder
# This is not great, because multiple runs can accumulate assets
# in the assetfinder, but it's better than spending time adding
# functionality in the dataportal to report all the assets it
# knows about.
self._assets_from_source = \
self.trading_environment.asset_finder.retrieve_all(
self.trading_environment.asset_finder.sids
)
else:
if isinstance(data, pd.DataFrame):
# If a DataFrame is passed. Promote it to a Panel.
# The reader will fake volume values.
data = pd.Panel({'close': data.copy()})
data = data.swapaxes(0, 2)
if isinstance(data, pd.Panel):
# Guard against tz-naive index.
if data.major_axis.tz is None:
data.major_axis = data.major_axis.tz_localize('UTC')
# For compatibility with existing examples allow start/end
# to be inferred.
if overwrite_sim_params:
self.sim_params = self.sim_params.create_new(
self.trading_calendar.minute_to_session_label(
data.major_axis[0]
),
self.trading_calendar.minute_to_session_label(
data.major_axis[-1]
),
)
# Assume data is daily if timestamp times are
# standardized, otherwise assume minute bars.
times = data.major_axis.time
if np.all(times == times[0]):
self.sim_params.data_frequency = 'daily'
else:
self.sim_params.data_frequency = 'minute'
copy_panel = data.rename(
# These were the old names for the close/open columns. We
# need to make a copy anyway, so swap these for backwards
# compat while we're here.
minor_axis={'close_price': 'close', 'open_price': 'open'},
copy=True,
)
copy_panel.items = self._write_and_map_id_index_to_sids(
copy_panel.items, copy_panel.major_axis[0],
)
self._assets_from_source = (
self.asset_finder.retrieve_all(
copy_panel.items
)
)
if self.sim_params.data_frequency == 'daily':
equity_reader_arg = 'equity_daily_reader'
elif self.sim_params.data_frequency == 'minute':
equity_reader_arg = 'equity_minute_reader'
equity_reader = PanelBarReader(
self.trading_calendar,
copy_panel,
self.sim_params.data_frequency,
)
self.data_portal = DataPortal(
self.asset_finder,
self.trading_calendar,
first_trading_day=equity_reader.first_trading_day,
**{equity_reader_arg: equity_reader}
)
# Force a reset of the performance tracker, in case
# this is a repeat run of the algorithm.
self.perf_tracker = None
# Create zipline and loop through simulated_trading.
# Each iteration returns a perf dictionary
try:
perfs = []
for perf in self.get_generator():
perfs.append(perf)
# convert perf dict to pandas dataframe
daily_stats = self._create_daily_stats(perfs)
self.analyze(daily_stats)
finally:
self.data_portal = None
return daily_stats
def _write_and_map_id_index_to_sids(self, identifiers, as_of_date):
# Build new Assets for identifiers that can't be resolved as
# sids/Assets
def is_unknown(asset_or_sid):
sid = op.index(asset_or_sid)
return self.asset_finder.retrieve_asset(
sid=sid,
default_none=True
) is None
new_assets = set()
new_sids = set()
new_symbols = set()
for identifier in identifiers:
if isinstance(identifier, Asset) and is_unknown(identifier):
new_assets.add(identifier)
elif isinstance(identifier, Integral) and is_unknown(identifier):
new_sids.add(identifier)
elif isinstance(identifier, (string_types)):
new_symbols.add(identifier)
else:
try:
new_sids.add(op.index(identifier))
except TypeError:
raise TypeError(
"Can't convert %s to an asset." % identifier
)
new_assets = tuple(new_assets)
new_sids = tuple(new_sids)
new_symbols = tuple(new_symbols)
number_of_kinds_of_new_things = (
sum((bool(new_assets), bool(new_sids), bool(new_symbols)))
)
# Nothing to insert, bail early.
if not number_of_kinds_of_new_things:
return self.asset_finder.map_identifier_index_to_sids(
identifiers, as_of_date,
)
elif number_of_kinds_of_new_things == 1:
warnings.warn(
'writing unknown identifiers into the assets db of the trading'
' environment is deprecated; please write this information'
' to the assets db before constructing the environment',
DeprecationWarning,
stacklevel=2,
)
else:
raise ValueError(
"Mixed types in DataFrame or Panel index.\n"
"Asset Count: %d, Sid Count: %d, Symbol Count: %d.\n"
"Choose one type and stick with it." % (
len(new_assets),
len(new_sids),
len(new_symbols),
)
)
def map_getattr(iterable, attr):
return [getattr(i, attr) for i in iterable]
if new_assets:
frame_to_write = pd.DataFrame(
data=dict(
symbol=map_getattr(new_assets, 'symbol'),
start_date=map_getattr(new_assets, 'start_date'),
end_date=map_getattr(new_assets, 'end_date'),
exchange=map_getattr(new_assets, 'exchange'),
),
index=map_getattr(new_assets, 'sid'),
)
elif new_sids:
frame_to_write = make_simple_equity_info(
new_sids,
start_date=self.sim_params.start_session,
end_date=self.sim_params.end_session,
symbols=map(str, new_sids),
)
elif new_symbols:
existing_sids = self.asset_finder.sids
first_sid = max(existing_sids) + 1 if existing_sids else 0
fake_sids = range(first_sid, first_sid + len(new_symbols))
frame_to_write = make_simple_equity_info(
sids=fake_sids,
start_date=as_of_date,
end_date=self.sim_params.end_session,
symbols=new_symbols,
)
else:
raise AssertionError("This should never happen.")
self.trading_environment.write_data(equities=frame_to_write)
# We need to clear out any cache misses that were stored while trying
# to do lookups. The real fix for this problem is to not construct an
# AssetFinder until we `run()` when we actually have all the data we
# need to so.
self.asset_finder._reset_caches()
return self.asset_finder.map_identifier_index_to_sids(
identifiers, as_of_date,
)
def _create_daily_stats(self, perfs):
# create daily and cumulative stats dataframe
daily_perfs = []
# TODO: the loop here could overwrite expected properties
# of daily_perf. Could potentially raise or log a
# warning.
for perf in perfs:
if 'daily_perf' in perf:
perf['daily_perf'].update(
perf['daily_perf'].pop('recorded_vars')
)
perf['daily_perf'].update(perf['cumulative_risk_metrics'])
daily_perfs.append(perf['daily_perf'])
else:
self.risk_report = perf
daily_dts = pd.DatetimeIndex(
[p['period_close'] for p in daily_perfs], tz='UTC'
)
daily_stats = pd.DataFrame(daily_perfs, index=daily_dts)
return daily_stats
def calculate_capital_changes(self, dt, emission_rate, is_interday,
portfolio_value_adjustment=0.0):
"""
If there is a capital change for a given dt, this means the the change
occurs before `handle_data` on the given dt. In the case of the
change being a target value, the change will be computed on the
portfolio value according to prices at the given dt
`portfolio_value_adjustment`, if specified, will be removed from the
portfolio_value of the cumulative performance when calculating deltas
from target capital changes.
"""
try:
capital_change = self.capital_changes[dt]
except KeyError:
return
if emission_rate == 'daily':
# If we are running daily emission, prices won't
# necessarily be synced at the end of every minute, and we
# need the up-to-date prices for capital change
# calculations. We want to sync the prices as of the
# last market minute, and this is okay from a data portal
# perspective as we have technically not "advanced" to the
# current dt yet.
self.perf_tracker.position_tracker.sync_last_sale_prices(
self.trading_calendar.previous_minute(
dt
),
False,
self.data_portal
)
self.perf_tracker.prepare_capital_change(is_interday)
if capital_change['type'] == 'target':
target = capital_change['value']
capital_change_amount = target - \
(self.updated_portfolio().portfolio_value -
portfolio_value_adjustment)
self.portfolio_needs_update = True
log.info('Processing capital change to target %s at %s. Capital '
'change delta is %s' % (target, dt,
capital_change_amount))
elif capital_change['type'] == 'delta':
target = None
capital_change_amount = capital_change['value']
log.info('Processing capital change of delta %s at %s'
% (capital_change_amount, dt))
else:
log.error("Capital change %s does not indicate a valid type "
"('target' or 'delta')" % capital_change)
return
self.capital_change_deltas.update({dt: capital_change_amount})
self.perf_tracker.process_capital_change(capital_change_amount,
is_interday)
yield {
'capital_change':
{'date': dt,
'type': 'cash',
'target': target,
'delta': capital_change_amount}
}
@api_method
def get_environment(self, field='platform'):
"""Query the execution environment.
Parameters
----------
field : {'platform', 'arena', 'data_frequency',
'start', 'end', 'capital_base', 'platform', '*'}
The field to query. The options have the following meanings:
arena : str
The arena from the simulation parameters. This will normally
be ``'backtest'`` but some systems may use this distinguish
live trading from backtesting.
data_frequency : {'daily', 'minute'}
data_frequency tells the algorithm if it is running with
daily data or minute data.
start : datetime
The start date for the simulation.
end : datetime
The end date for the simulation.
capital_base : float
The starting capital for the simulation.
platform : str
The platform that the code is running on. By default this
will be the string 'zipline'. This can allow algorithms to
know if they are running on the Quantopian platform instead.
* : dict[str -> any]
Returns all of the fields in a dictionary.
Returns
-------
val : any
The value for the field queried. See above for more information.
Raises
------
ValueError
Raised when ``field`` is not a valid option.
"""
env = {
'arena': self.sim_params.arena,
'data_frequency': self.sim_params.data_frequency,
'start': self.sim_params.first_open,
'end': self.sim_params.last_close,
'capital_base': self.sim_params.capital_base,
'platform': self._platform
}
if field == '*':
return env
else:
try:
return env[field]
except KeyError:
raise ValueError(
'%r is not a valid field for get_environment' % field,
)
@api_method
def fetch_csv(self,
url,
pre_func=None,
post_func=None,
date_column='date',
date_format=None,
timezone=pytz.utc.zone,
symbol=None,
mask=True,
symbol_column=None,
special_params_checker=None,
**kwargs):
"""Fetch a csv from a remote url and register the data so that it is
queryable from the ``data`` object.
Parameters
----------
url : str
The url of the csv file to load.
pre_func : callable[pd.DataFrame -> pd.DataFrame], optional
A callback to allow preprocessing the raw data returned from
fetch_csv before dates are paresed or symbols are mapped.
post_func : callable[pd.DataFrame -> pd.DataFrame], optional
A callback to allow postprocessing of the data after dates and
symbols have been mapped.
date_column : str, optional