| Total Complexity | 153 |
| Total Lines | 1210 |
| Duplicated Lines | 0 % |
Complex classes like zipline.TradingAlgorithm often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
| 1 | # |
||
| 115 | class TradingAlgorithm(object): |
||
| 116 | """ |
||
| 117 | Base class for trading algorithms. Inherit and overload |
||
| 118 | initialize() and handle_data(data). |
||
| 119 | |||
| 120 | A new algorithm could look like this: |
||
| 121 | ``` |
||
| 122 | from zipline.api import order, symbol |
||
| 123 | |||
| 124 | def initialize(context): |
||
| 125 | context.sid = symbol('AAPL') |
||
| 126 | context.amount = 100 |
||
| 127 | |||
| 128 | def handle_data(context, data): |
||
| 129 | sid = context.sid |
||
| 130 | amount = context.amount |
||
| 131 | order(sid, amount) |
||
| 132 | ``` |
||
| 133 | To then to run this algorithm pass these functions to |
||
| 134 | TradingAlgorithm: |
||
| 135 | |||
| 136 | my_algo = TradingAlgorithm(initialize, handle_data) |
||
| 137 | stats = my_algo.run(data) |
||
| 138 | |||
| 139 | """ |
||
| 140 | |||
| 141 | def __init__(self, *args, **kwargs): |
||
| 142 | """Initialize sids and other state variables. |
||
| 143 | |||
| 144 | :Arguments: |
||
| 145 | :Optional: |
||
| 146 | initialize : function |
||
| 147 | Function that is called with a single |
||
| 148 | argument at the begninning of the simulation. |
||
| 149 | handle_data : function |
||
| 150 | Function that is called with 2 arguments |
||
| 151 | (context and data) on every bar. |
||
| 152 | script : str |
||
| 153 | Algoscript that contains initialize and |
||
| 154 | handle_data function definition. |
||
| 155 | data_frequency : {'daily', 'minute'} |
||
| 156 | The duration of the bars. |
||
| 157 | capital_base : float <default: 1.0e5> |
||
| 158 | How much capital to start with. |
||
| 159 | asset_finder : An AssetFinder object |
||
| 160 | A new AssetFinder object to be used in this TradingEnvironment |
||
| 161 | equities_metadata : can be either: |
||
| 162 | - dict |
||
| 163 | - pandas.DataFrame |
||
| 164 | - object with 'read' property |
||
| 165 | If dict is provided, it must have the following structure: |
||
| 166 | * keys are the identifiers |
||
| 167 | * values are dicts containing the metadata, with the metadata |
||
| 168 | field name as the key |
||
| 169 | If pandas.DataFrame is provided, it must have the |
||
| 170 | following structure: |
||
| 171 | * column names must be the metadata fields |
||
| 172 | * index must be the different asset identifiers |
||
| 173 | * array contents should be the metadata value |
||
| 174 | If an object with a 'read' property is provided, 'read' must |
||
| 175 | return rows containing at least one of 'sid' or 'symbol' along |
||
| 176 | with the other metadata fields. |
||
| 177 | identifiers : List |
||
| 178 | Any asset identifiers that are not provided in the |
||
| 179 | equities_metadata, but will be traded by this TradingAlgorithm |
||
| 180 | """ |
||
| 181 | self.sources = [] |
||
| 182 | |||
| 183 | # List of trading controls to be used to validate orders. |
||
| 184 | self.trading_controls = [] |
||
| 185 | |||
| 186 | # List of account controls to be checked on each bar. |
||
| 187 | self.account_controls = [] |
||
| 188 | |||
| 189 | self._recorded_vars = {} |
||
| 190 | self.namespace = kwargs.pop('namespace', {}) |
||
| 191 | |||
| 192 | self._platform = kwargs.pop('platform', 'zipline') |
||
| 193 | |||
| 194 | self.logger = None |
||
| 195 | |||
| 196 | self.data_portal = None |
||
| 197 | |||
| 198 | # If an env has been provided, pop it |
||
| 199 | self.trading_environment = kwargs.pop('env', None) |
||
| 200 | |||
| 201 | if self.trading_environment is None: |
||
| 202 | self.trading_environment = TradingEnvironment() |
||
| 203 | |||
| 204 | # Update the TradingEnvironment with the provided asset metadata |
||
| 205 | self.trading_environment.write_data( |
||
| 206 | equities_data=kwargs.pop('equities_metadata', {}), |
||
| 207 | equities_identifiers=kwargs.pop('identifiers', []), |
||
| 208 | futures_data=kwargs.pop('futures_metadata', {}), |
||
| 209 | ) |
||
| 210 | |||
| 211 | # set the capital base |
||
| 212 | self.capital_base = kwargs.pop('capital_base', DEFAULT_CAPITAL_BASE) |
||
| 213 | self.sim_params = kwargs.pop('sim_params', None) |
||
| 214 | if self.sim_params is None: |
||
| 215 | self.sim_params = create_simulation_parameters( |
||
| 216 | capital_base=self.capital_base, |
||
| 217 | start=kwargs.pop('start', None), |
||
| 218 | end=kwargs.pop('end', None), |
||
| 219 | env=self.trading_environment, |
||
| 220 | ) |
||
| 221 | else: |
||
| 222 | self.sim_params.update_internal_from_env(self.trading_environment) |
||
| 223 | |||
| 224 | self.perf_tracker = None |
||
| 225 | # Pull in the environment's new AssetFinder for quick reference |
||
| 226 | self.asset_finder = self.trading_environment.asset_finder |
||
| 227 | |||
| 228 | # Initialize Pipeline API data. |
||
| 229 | self.init_engine(kwargs.pop('get_pipeline_loader', None)) |
||
| 230 | self._pipelines = {} |
||
| 231 | # Create an always-expired cache so that we compute the first time data |
||
| 232 | # is requested. |
||
| 233 | self._pipeline_cache = CachedObject(None, pd.Timestamp(0, tz='UTC')) |
||
| 234 | |||
| 235 | self.blotter = kwargs.pop('blotter', None) |
||
| 236 | if not self.blotter: |
||
| 237 | self.blotter = Blotter( |
||
| 238 | slippage_func=VolumeShareSlippage(), |
||
| 239 | commission=PerShare(), |
||
| 240 | data_frequency=self.data_frequency, |
||
| 241 | ) |
||
| 242 | |||
| 243 | # The symbol lookup date specifies the date to use when resolving |
||
| 244 | # symbols to sids, and can be set using set_symbol_lookup_date() |
||
| 245 | self._symbol_lookup_date = None |
||
| 246 | |||
| 247 | self._portfolio = None |
||
| 248 | self._account = None |
||
| 249 | |||
| 250 | # If string is passed in, execute and get reference to |
||
| 251 | # functions. |
||
| 252 | self.algoscript = kwargs.pop('script', None) |
||
| 253 | |||
| 254 | self._initialize = None |
||
| 255 | self._before_trading_start = None |
||
| 256 | self._analyze = None |
||
| 257 | |||
| 258 | self.event_manager = EventManager( |
||
| 259 | create_context=kwargs.pop('create_event_context', None), |
||
| 260 | ) |
||
| 261 | |||
| 262 | if self.algoscript is not None: |
||
| 263 | filename = kwargs.pop('algo_filename', None) |
||
| 264 | if filename is None: |
||
| 265 | filename = '<string>' |
||
| 266 | code = compile(self.algoscript, filename, 'exec') |
||
| 267 | exec_(code, self.namespace) |
||
| 268 | self._initialize = self.namespace.get('initialize') |
||
| 269 | if 'handle_data' not in self.namespace: |
||
| 270 | raise ValueError('You must define a handle_data function.') |
||
| 271 | else: |
||
| 272 | self._handle_data = self.namespace['handle_data'] |
||
| 273 | |||
| 274 | self._before_trading_start = \ |
||
| 275 | self.namespace.get('before_trading_start') |
||
| 276 | # Optional analyze function, gets called after run |
||
| 277 | self._analyze = self.namespace.get('analyze') |
||
| 278 | |||
| 279 | elif kwargs.get('initialize') and kwargs.get('handle_data'): |
||
| 280 | if self.algoscript is not None: |
||
| 281 | raise ValueError('You can not set script and \ |
||
| 282 | initialize/handle_data.') |
||
| 283 | self._initialize = kwargs.pop('initialize') |
||
| 284 | self._handle_data = kwargs.pop('handle_data') |
||
| 285 | self._before_trading_start = kwargs.pop('before_trading_start', |
||
| 286 | None) |
||
| 287 | self._analyze = kwargs.pop('analyze', None) |
||
| 288 | |||
| 289 | self.event_manager.add_event( |
||
| 290 | zipline.utils.events.Event( |
||
| 291 | zipline.utils.events.Always(), |
||
| 292 | # We pass handle_data.__func__ to get the unbound method. |
||
| 293 | # We will explicitly pass the algorithm to bind it again. |
||
| 294 | self.handle_data.__func__, |
||
| 295 | ), |
||
| 296 | prepend=True, |
||
| 297 | ) |
||
| 298 | |||
| 299 | # If method not defined, NOOP |
||
| 300 | if self._initialize is None: |
||
| 301 | self._initialize = lambda x: None |
||
| 302 | |||
| 303 | # Alternative way of setting data_frequency for backwards |
||
| 304 | # compatibility. |
||
| 305 | if 'data_frequency' in kwargs: |
||
| 306 | self.data_frequency = kwargs.pop('data_frequency') |
||
| 307 | |||
| 308 | # Prepare the algo for initialization |
||
| 309 | self.initialized = False |
||
| 310 | self.initialize_args = args |
||
| 311 | self.initialize_kwargs = kwargs |
||
| 312 | |||
| 313 | self.benchmark_sid = kwargs.pop('benchmark_sid', None) |
||
| 314 | |||
| 315 | def init_engine(self, get_loader): |
||
| 316 | """ |
||
| 317 | Construct and store a PipelineEngine from loader. |
||
| 318 | |||
| 319 | If get_loader is None, constructs a NoOpPipelineEngine. |
||
| 320 | """ |
||
| 321 | if get_loader is not None: |
||
| 322 | self.engine = SimplePipelineEngine( |
||
| 323 | get_loader, |
||
| 324 | self.trading_environment.trading_days, |
||
| 325 | self.asset_finder, |
||
| 326 | ) |
||
| 327 | else: |
||
| 328 | self.engine = NoOpPipelineEngine() |
||
| 329 | |||
| 330 | def initialize(self, *args, **kwargs): |
||
| 331 | """ |
||
| 332 | Call self._initialize with `self` made available to Zipline API |
||
| 333 | functions. |
||
| 334 | """ |
||
| 335 | with ZiplineAPI(self): |
||
| 336 | self._initialize(self, *args, **kwargs) |
||
| 337 | |||
| 338 | def before_trading_start(self, data): |
||
| 339 | if self._before_trading_start is None: |
||
| 340 | return |
||
| 341 | |||
| 342 | self._before_trading_start(self, data) |
||
| 343 | |||
| 344 | def handle_data(self, data): |
||
| 345 | self._handle_data(self, data) |
||
| 346 | |||
| 347 | # Unlike trading controls which remain constant unless placing an |
||
| 348 | # order, account controls can change each bar. Thus, must check |
||
| 349 | # every bar no matter if the algorithm places an order or not. |
||
| 350 | self.validate_account_controls() |
||
| 351 | |||
| 352 | def analyze(self, perf): |
||
| 353 | if self._analyze is None: |
||
| 354 | return |
||
| 355 | |||
| 356 | with ZiplineAPI(self): |
||
| 357 | self._analyze(self, perf) |
||
| 358 | |||
| 359 | def __repr__(self): |
||
| 360 | """ |
||
| 361 | N.B. this does not yet represent a string that can be used |
||
| 362 | to instantiate an exact copy of an algorithm. |
||
| 363 | |||
| 364 | However, it is getting close, and provides some value as something |
||
| 365 | that can be inspected interactively. |
||
| 366 | """ |
||
| 367 | return """ |
||
| 368 | {class_name}( |
||
| 369 | capital_base={capital_base} |
||
| 370 | sim_params={sim_params}, |
||
| 371 | initialized={initialized}, |
||
| 372 | slippage={slippage}, |
||
| 373 | commission={commission}, |
||
| 374 | blotter={blotter}, |
||
| 375 | recorded_vars={recorded_vars}) |
||
| 376 | """.strip().format(class_name=self.__class__.__name__, |
||
| 377 | capital_base=self.capital_base, |
||
| 378 | sim_params=repr(self.sim_params), |
||
| 379 | initialized=self.initialized, |
||
| 380 | slippage=repr(self.blotter.slippage_func), |
||
| 381 | commission=repr(self.blotter.commission), |
||
| 382 | blotter=repr(self.blotter), |
||
| 383 | recorded_vars=repr(self.recorded_vars)) |
||
| 384 | |||
| 385 | def _create_clock(self): |
||
| 386 | """ |
||
| 387 | If the clock property is not set, then create one based on frequency. |
||
| 388 | """ |
||
| 389 | if self.sim_params.data_frequency == 'minute': |
||
| 390 | env = self.trading_environment |
||
| 391 | trading_o_and_c = env.open_and_closes.ix[ |
||
| 392 | self.sim_params.trading_days] |
||
| 393 | market_opens = trading_o_and_c['market_open'].values.astype( |
||
| 394 | 'datetime64[ns]').astype(np.int64) |
||
| 395 | market_closes = trading_o_and_c['market_close'].values.astype( |
||
| 396 | 'datetime64[ns]').astype(np.int64) |
||
| 397 | |||
| 398 | minutely_emission = self.sim_params.emission_rate == "minute" |
||
| 399 | |||
| 400 | clock = MinuteSimulationClock( |
||
| 401 | self.sim_params.trading_days, |
||
| 402 | market_opens, |
||
| 403 | market_closes, |
||
| 404 | env.trading_days, |
||
| 405 | minutely_emission |
||
| 406 | ) |
||
| 407 | self.data_portal.setup_offset_cache( |
||
| 408 | clock.minutes_by_day, |
||
| 409 | clock.minutes_to_day) |
||
| 410 | return clock |
||
| 411 | else: |
||
| 412 | return DailySimulationClock(self.sim_params.trading_days) |
||
| 413 | |||
| 414 | def _create_benchmark_source(self): |
||
| 415 | return BenchmarkSource( |
||
| 416 | self.benchmark_sid, |
||
| 417 | self.trading_environment, |
||
| 418 | self.sim_params.trading_days, |
||
| 419 | self.data_portal, |
||
| 420 | emission_rate=self.sim_params.emission_rate, |
||
| 421 | ) |
||
| 422 | |||
| 423 | def _create_generator(self, sim_params): |
||
| 424 | if sim_params is not None: |
||
| 425 | self.sim_params = sim_params |
||
| 426 | |||
| 427 | if self.perf_tracker is None: |
||
| 428 | # HACK: When running with the `run` method, we set perf_tracker to |
||
| 429 | # None so that it will be overwritten here. |
||
| 430 | self.perf_tracker = PerformanceTracker( |
||
| 431 | sim_params=self.sim_params, |
||
| 432 | env=self.trading_environment, |
||
| 433 | data_portal=self.data_portal |
||
| 434 | ) |
||
| 435 | |||
| 436 | # Set the dt initially to the period start by forcing it to change. |
||
| 437 | self.on_dt_changed(self.sim_params.period_start) |
||
| 438 | |||
| 439 | if not self.initialized: |
||
| 440 | self.initialize(*self.initialize_args, **self.initialize_kwargs) |
||
| 441 | self.initialized = True |
||
| 442 | |||
| 443 | self.trading_client = AlgorithmSimulator( |
||
| 444 | self, |
||
| 445 | sim_params, |
||
| 446 | self.data_portal, |
||
| 447 | self._create_clock(), |
||
| 448 | self._create_benchmark_source() |
||
| 449 | ) |
||
| 450 | |||
| 451 | return self.trading_client.transform() |
||
| 452 | |||
| 453 | def get_generator(self): |
||
| 454 | """ |
||
| 455 | Override this method to add new logic to the construction |
||
| 456 | of the generator. Overrides can use the _create_generator |
||
| 457 | method to get a standard construction generator. |
||
| 458 | """ |
||
| 459 | return self._create_generator(self.sim_params) |
||
| 460 | |||
| 461 | def run(self, data_portal=None): |
||
| 462 | """Run the algorithm. |
||
| 463 | |||
| 464 | :Arguments: |
||
| 465 | source : DataPortal |
||
| 466 | |||
| 467 | :Returns: |
||
| 468 | daily_stats : pandas.DataFrame |
||
| 469 | Daily performance metrics such as returns, alpha etc. |
||
| 470 | |||
| 471 | """ |
||
| 472 | self.data_portal = data_portal |
||
| 473 | |||
| 474 | # Force a reset of the performance tracker, in case |
||
| 475 | # this is a repeat run of the algorithm. |
||
| 476 | self.perf_tracker = None |
||
| 477 | |||
| 478 | # Create zipline and loop through simulated_trading. |
||
| 479 | # Each iteration returns a perf dictionary |
||
| 480 | perfs = [] |
||
| 481 | for perf in self.get_generator(): |
||
| 482 | perfs.append(perf) |
||
| 483 | |||
| 484 | # convert perf dict to pandas dataframe |
||
| 485 | daily_stats = self._create_daily_stats(perfs) |
||
| 486 | |||
| 487 | self.analyze(daily_stats) |
||
| 488 | |||
| 489 | return daily_stats |
||
| 490 | |||
| 491 | def _write_and_map_id_index_to_sids(self, identifiers, as_of_date): |
||
| 492 | # Build new Assets for identifiers that can't be resolved as |
||
| 493 | # sids/Assets |
||
| 494 | identifiers_to_build = [] |
||
| 495 | for identifier in identifiers: |
||
| 496 | asset = None |
||
| 497 | |||
| 498 | if isinstance(identifier, Asset): |
||
| 499 | asset = self.asset_finder.retrieve_asset(sid=identifier.sid, |
||
| 500 | default_none=True) |
||
| 501 | elif isinstance(identifier, Integral): |
||
| 502 | asset = self.asset_finder.retrieve_asset(sid=identifier, |
||
| 503 | default_none=True) |
||
| 504 | if asset is None: |
||
| 505 | identifiers_to_build.append(identifier) |
||
| 506 | |||
| 507 | self.trading_environment.write_data( |
||
| 508 | equities_identifiers=identifiers_to_build) |
||
| 509 | |||
| 510 | # We need to clear out any cache misses that were stored while trying |
||
| 511 | # to do lookups. The real fix for this problem is to not construct an |
||
| 512 | # AssetFinder until we `run()` when we actually have all the data we |
||
| 513 | # need to so. |
||
| 514 | self.asset_finder._reset_caches() |
||
| 515 | |||
| 516 | return self.asset_finder.map_identifier_index_to_sids( |
||
| 517 | identifiers, as_of_date, |
||
| 518 | ) |
||
| 519 | |||
| 520 | def _create_daily_stats(self, perfs): |
||
| 521 | # create daily and cumulative stats dataframe |
||
| 522 | daily_perfs = [] |
||
| 523 | # TODO: the loop here could overwrite expected properties |
||
| 524 | # of daily_perf. Could potentially raise or log a |
||
| 525 | # warning. |
||
| 526 | for perf in perfs: |
||
| 527 | if 'daily_perf' in perf: |
||
| 528 | |||
| 529 | perf['daily_perf'].update( |
||
| 530 | perf['daily_perf'].pop('recorded_vars') |
||
| 531 | ) |
||
| 532 | perf['daily_perf'].update(perf['cumulative_risk_metrics']) |
||
| 533 | daily_perfs.append(perf['daily_perf']) |
||
| 534 | else: |
||
| 535 | self.risk_report = perf |
||
| 536 | |||
| 537 | daily_dts = [np.datetime64(perf['period_close'], utc=True) |
||
| 538 | for perf in daily_perfs] |
||
| 539 | daily_stats = pd.DataFrame(daily_perfs, index=daily_dts) |
||
| 540 | |||
| 541 | return daily_stats |
||
| 542 | |||
| 543 | @api_method |
||
| 544 | def get_environment(self, field='platform'): |
||
| 545 | env = { |
||
| 546 | 'arena': self.sim_params.arena, |
||
| 547 | 'data_frequency': self.sim_params.data_frequency, |
||
| 548 | 'start': self.sim_params.first_open, |
||
| 549 | 'end': self.sim_params.last_close, |
||
| 550 | 'capital_base': self.sim_params.capital_base, |
||
| 551 | 'platform': self._platform |
||
| 552 | } |
||
| 553 | if field == '*': |
||
| 554 | return env |
||
| 555 | else: |
||
| 556 | return env[field] |
||
| 557 | |||
| 558 | @api_method |
||
| 559 | def fetch_csv(self, url, |
||
| 560 | pre_func=None, |
||
| 561 | post_func=None, |
||
| 562 | date_column='date', |
||
| 563 | date_format=None, |
||
| 564 | timezone=pytz.utc.zone, |
||
| 565 | symbol=None, |
||
| 566 | mask=True, |
||
| 567 | symbol_column=None, |
||
| 568 | special_params_checker=None, |
||
| 569 | **kwargs): |
||
| 570 | |||
| 571 | # Show all the logs every time fetcher is used. |
||
| 572 | csv_data_source = PandasRequestsCSV( |
||
| 573 | url, |
||
| 574 | pre_func, |
||
| 575 | post_func, |
||
| 576 | self.trading_environment, |
||
| 577 | self.sim_params.period_start, |
||
| 578 | self.sim_params.period_end, |
||
| 579 | date_column, |
||
| 580 | date_format, |
||
| 581 | timezone, |
||
| 582 | symbol, |
||
| 583 | mask, |
||
| 584 | symbol_column, |
||
| 585 | data_frequency=self.data_frequency, |
||
| 586 | special_params_checker=special_params_checker, |
||
| 587 | **kwargs |
||
| 588 | ) |
||
| 589 | |||
| 590 | # ingest this into dataportal |
||
| 591 | self.data_portal.handle_extra_source(csv_data_source.df) |
||
| 592 | |||
| 593 | return csv_data_source |
||
| 594 | |||
| 595 | def add_event(self, rule=None, callback=None): |
||
| 596 | """ |
||
| 597 | Adds an event to the algorithm's EventManager. |
||
| 598 | """ |
||
| 599 | self.event_manager.add_event( |
||
| 600 | zipline.utils.events.Event(rule, callback), |
||
| 601 | ) |
||
| 602 | |||
| 603 | @api_method |
||
| 604 | def schedule_function(self, |
||
| 605 | func, |
||
| 606 | date_rule=None, |
||
| 607 | time_rule=None, |
||
| 608 | half_days=True): |
||
| 609 | """ |
||
| 610 | Schedules a function to be called with some timed rules. |
||
| 611 | """ |
||
| 612 | date_rule = date_rule or DateRuleFactory.every_day() |
||
| 613 | time_rule = ((time_rule or TimeRuleFactory.market_open()) |
||
| 614 | if self.sim_params.data_frequency == 'minute' else |
||
| 615 | # If we are in daily mode the time_rule is ignored. |
||
| 616 | zipline.utils.events.Always()) |
||
| 617 | |||
| 618 | self.add_event( |
||
| 619 | make_eventrule(date_rule, time_rule, half_days), |
||
| 620 | func, |
||
| 621 | ) |
||
| 622 | |||
| 623 | @api_method |
||
| 624 | def record(self, *args, **kwargs): |
||
| 625 | """ |
||
| 626 | Track and record local variable (i.e. attributes) each day. |
||
| 627 | """ |
||
| 628 | # Make 2 objects both referencing the same iterator |
||
| 629 | args = [iter(args)] * 2 |
||
| 630 | |||
| 631 | # Zip generates list entries by calling `next` on each iterator it |
||
| 632 | # receives. In this case the two iterators are the same object, so the |
||
| 633 | # call to next on args[0] will also advance args[1], resulting in zip |
||
| 634 | # returning (a,b) (c,d) (e,f) rather than (a,a) (b,b) (c,c) etc. |
||
| 635 | positionals = zip(*args) |
||
| 636 | for name, value in chain(positionals, iteritems(kwargs)): |
||
| 637 | self._recorded_vars[name] = value |
||
| 638 | |||
| 639 | @api_method |
||
| 640 | def set_benchmark(self, benchmark_sid): |
||
| 641 | if self.initialized: |
||
| 642 | raise SetBenchmarkOutsideInitialize() |
||
| 643 | |||
| 644 | self.benchmark_sid = benchmark_sid |
||
| 645 | |||
| 646 | @api_method |
||
| 647 | @preprocess(symbol_str=ensure_upper_case) |
||
| 648 | def symbol(self, symbol_str): |
||
| 649 | """ |
||
| 650 | Default symbol lookup for any source that directly maps the |
||
| 651 | symbol to the Asset (e.g. yahoo finance). |
||
| 652 | """ |
||
| 653 | # If the user has not set the symbol lookup date, |
||
| 654 | # use the period_end as the date for sybmol->sid resolution. |
||
| 655 | _lookup_date = self._symbol_lookup_date if self._symbol_lookup_date is not None \ |
||
| 656 | else self.sim_params.period_end |
||
| 657 | |||
| 658 | return self.asset_finder.lookup_symbol( |
||
| 659 | symbol_str, |
||
| 660 | as_of_date=_lookup_date, |
||
| 661 | ) |
||
| 662 | |||
| 663 | @api_method |
||
| 664 | def symbols(self, *args): |
||
| 665 | """ |
||
| 666 | Default symbols lookup for any source that directly maps the |
||
| 667 | symbol to the Asset (e.g. yahoo finance). |
||
| 668 | """ |
||
| 669 | return [self.symbol(identifier) for identifier in args] |
||
| 670 | |||
| 671 | @api_method |
||
| 672 | def sid(self, a_sid): |
||
| 673 | """ |
||
| 674 | Default sid lookup for any source that directly maps the integer sid |
||
| 675 | to the Asset. |
||
| 676 | """ |
||
| 677 | return self.asset_finder.retrieve_asset(a_sid) |
||
| 678 | |||
| 679 | @api_method |
||
| 680 | @preprocess(symbol=ensure_upper_case) |
||
| 681 | def future_symbol(self, symbol): |
||
| 682 | """ Lookup a futures contract with a given symbol. |
||
| 683 | |||
| 684 | Parameters |
||
| 685 | ---------- |
||
| 686 | symbol : str |
||
| 687 | The symbol of the desired contract. |
||
| 688 | |||
| 689 | Returns |
||
| 690 | ------- |
||
| 691 | Future |
||
| 692 | A Future object. |
||
| 693 | |||
| 694 | Raises |
||
| 695 | ------ |
||
| 696 | SymbolNotFound |
||
| 697 | Raised when no contract named 'symbol' is found. |
||
| 698 | |||
| 699 | """ |
||
| 700 | return self.asset_finder.lookup_future_symbol(symbol) |
||
| 701 | |||
| 702 | @api_method |
||
| 703 | @preprocess(root_symbol=ensure_upper_case) |
||
| 704 | def future_chain(self, root_symbol, as_of_date=None): |
||
| 705 | """ Look up a future chain with the specified parameters. |
||
| 706 | |||
| 707 | Parameters |
||
| 708 | ---------- |
||
| 709 | root_symbol : str |
||
| 710 | The root symbol of a future chain. |
||
| 711 | as_of_date : datetime.datetime or pandas.Timestamp or str, optional |
||
| 712 | Date at which the chain determination is rooted. I.e. the |
||
| 713 | existing contract whose notice date is first after this date is |
||
| 714 | the primary contract, etc. |
||
| 715 | |||
| 716 | Returns |
||
| 717 | ------- |
||
| 718 | FutureChain |
||
| 719 | The future chain matching the specified parameters. |
||
| 720 | |||
| 721 | Raises |
||
| 722 | ------ |
||
| 723 | RootSymbolNotFound |
||
| 724 | If a future chain could not be found for the given root symbol. |
||
| 725 | """ |
||
| 726 | if as_of_date: |
||
| 727 | try: |
||
| 728 | as_of_date = pd.Timestamp(as_of_date, tz='UTC') |
||
| 729 | except ValueError: |
||
| 730 | raise UnsupportedDatetimeFormat(input=as_of_date, |
||
| 731 | method='future_chain') |
||
| 732 | return FutureChain( |
||
| 733 | asset_finder=self.asset_finder, |
||
| 734 | get_datetime=self.get_datetime, |
||
| 735 | root_symbol=root_symbol, |
||
| 736 | as_of_date=as_of_date |
||
| 737 | ) |
||
| 738 | |||
| 739 | def _calculate_order_value_amount(self, asset, value): |
||
| 740 | """ |
||
| 741 | Calculates how many shares/contracts to order based on the type of |
||
| 742 | asset being ordered. |
||
| 743 | """ |
||
| 744 | last_price = self.trading_client.current_data[asset].price |
||
| 745 | |||
| 746 | if tolerant_equals(last_price, 0): |
||
| 747 | zero_message = "Price of 0 for {psid}; can't infer value".format( |
||
| 748 | psid=asset |
||
| 749 | ) |
||
| 750 | if self.logger: |
||
| 751 | self.logger.debug(zero_message) |
||
| 752 | # Don't place any order |
||
| 753 | return 0 |
||
| 754 | |||
| 755 | if isinstance(asset, Future): |
||
| 756 | value_multiplier = asset.contract_multiplier |
||
| 757 | else: |
||
| 758 | value_multiplier = 1 |
||
| 759 | |||
| 760 | return value / (last_price * value_multiplier) |
||
| 761 | |||
| 762 | @api_method |
||
| 763 | def order(self, sid, amount, |
||
| 764 | limit_price=None, |
||
| 765 | stop_price=None, |
||
| 766 | style=None): |
||
| 767 | """ |
||
| 768 | Place an order using the specified parameters. |
||
| 769 | """ |
||
| 770 | # Truncate to the integer share count that's either within .0001 of |
||
| 771 | # amount or closer to zero. |
||
| 772 | # E.g. 3.9999 -> 4.0; 5.5 -> 5.0; -5.5 -> -5.0 |
||
| 773 | amount = int(round_if_near_integer(amount)) |
||
| 774 | |||
| 775 | # Raises a ZiplineError if invalid parameters are detected. |
||
| 776 | self.validate_order_params(sid, |
||
| 777 | amount, |
||
| 778 | limit_price, |
||
| 779 | stop_price, |
||
| 780 | style) |
||
| 781 | |||
| 782 | # Convert deprecated limit_price and stop_price parameters to use |
||
| 783 | # ExecutionStyle objects. |
||
| 784 | style = self.__convert_order_params_for_blotter(limit_price, |
||
| 785 | stop_price, |
||
| 786 | style) |
||
| 787 | return self.blotter.order(sid, amount, style) |
||
| 788 | |||
| 789 | def validate_order_params(self, |
||
| 790 | asset, |
||
| 791 | amount, |
||
| 792 | limit_price, |
||
| 793 | stop_price, |
||
| 794 | style): |
||
| 795 | """ |
||
| 796 | Helper method for validating parameters to the order API function. |
||
| 797 | |||
| 798 | Raises an UnsupportedOrderParameters if invalid arguments are found. |
||
| 799 | """ |
||
| 800 | |||
| 801 | if not self.initialized: |
||
| 802 | raise OrderDuringInitialize( |
||
| 803 | msg="order() can only be called from within handle_data()" |
||
| 804 | ) |
||
| 805 | |||
| 806 | if style: |
||
| 807 | if limit_price: |
||
| 808 | raise UnsupportedOrderParameters( |
||
| 809 | msg="Passing both limit_price and style is not supported." |
||
| 810 | ) |
||
| 811 | |||
| 812 | if stop_price: |
||
| 813 | raise UnsupportedOrderParameters( |
||
| 814 | msg="Passing both stop_price and style is not supported." |
||
| 815 | ) |
||
| 816 | |||
| 817 | if not isinstance(asset, Asset): |
||
| 818 | raise UnsupportedOrderParameters( |
||
| 819 | msg="Passing non-Asset argument to 'order()' is not supported." |
||
| 820 | " Use 'sid()' or 'symbol()' methods to look up an Asset." |
||
| 821 | ) |
||
| 822 | |||
| 823 | for control in self.trading_controls: |
||
| 824 | control.validate(asset, |
||
| 825 | amount, |
||
| 826 | self.portfolio, |
||
| 827 | self.get_datetime(), |
||
| 828 | self.trading_client.current_data) |
||
| 829 | |||
| 830 | @staticmethod |
||
| 831 | def __convert_order_params_for_blotter(limit_price, stop_price, style): |
||
| 832 | """ |
||
| 833 | Helper method for converting deprecated limit_price and stop_price |
||
| 834 | arguments into ExecutionStyle instances. |
||
| 835 | |||
| 836 | This function assumes that either style == None or (limit_price, |
||
| 837 | stop_price) == (None, None). |
||
| 838 | """ |
||
| 839 | # TODO_SS: DeprecationWarning for usage of limit_price and stop_price. |
||
| 840 | if style: |
||
| 841 | assert (limit_price, stop_price) == (None, None) |
||
| 842 | return style |
||
| 843 | if limit_price and stop_price: |
||
| 844 | return StopLimitOrder(limit_price, stop_price) |
||
| 845 | if limit_price: |
||
| 846 | return LimitOrder(limit_price) |
||
| 847 | if stop_price: |
||
| 848 | return StopOrder(stop_price) |
||
| 849 | else: |
||
| 850 | return MarketOrder() |
||
| 851 | |||
| 852 | @api_method |
||
| 853 | def order_value(self, sid, value, |
||
| 854 | limit_price=None, stop_price=None, style=None): |
||
| 855 | """ |
||
| 856 | Place an order by desired value rather than desired number of shares. |
||
| 857 | If the requested sid exists, the requested value is |
||
| 858 | divided by its price to imply the number of shares to transact. |
||
| 859 | If the Asset being ordered is a Future, the 'value' calculated |
||
| 860 | is actually the exposure, as Futures have no 'value'. |
||
| 861 | |||
| 862 | value > 0 :: Buy/Cover |
||
| 863 | value < 0 :: Sell/Short |
||
| 864 | Market order: order(sid, value) |
||
| 865 | Limit order: order(sid, value, limit_price) |
||
| 866 | Stop order: order(sid, value, None, stop_price) |
||
| 867 | StopLimit order: order(sid, value, limit_price, stop_price) |
||
| 868 | """ |
||
| 869 | amount = self._calculate_order_value_amount(sid, value) |
||
| 870 | return self.order(sid, amount, |
||
| 871 | limit_price=limit_price, |
||
| 872 | stop_price=stop_price, |
||
| 873 | style=style) |
||
| 874 | |||
| 875 | @property |
||
| 876 | def recorded_vars(self): |
||
| 877 | return copy(self._recorded_vars) |
||
| 878 | |||
| 879 | @property |
||
| 880 | def portfolio(self): |
||
| 881 | return self.updated_portfolio() |
||
| 882 | |||
| 883 | def updated_portfolio(self): |
||
| 884 | if self._portfolio is None and self.perf_tracker is not None: |
||
| 885 | self._portfolio = \ |
||
| 886 | self.perf_tracker.get_portfolio(self.datetime) |
||
| 887 | return self._portfolio |
||
| 888 | |||
| 889 | @property |
||
| 890 | def account(self): |
||
| 891 | return self.updated_account() |
||
| 892 | |||
| 893 | def updated_account(self): |
||
| 894 | if self._account is None and self.perf_tracker is not None: |
||
| 895 | self._account = \ |
||
| 896 | self.perf_tracker.get_account(self.datetime) |
||
| 897 | return self._account |
||
| 898 | |||
| 899 | def set_logger(self, logger): |
||
| 900 | self.logger = logger |
||
| 901 | |||
| 902 | def on_dt_changed(self, dt): |
||
| 903 | """ |
||
| 904 | Callback triggered by the simulation loop whenever the current dt |
||
| 905 | changes. |
||
| 906 | |||
| 907 | Any logic that should happen exactly once at the start of each datetime |
||
| 908 | group should happen here. |
||
| 909 | """ |
||
| 910 | assert isinstance(dt, datetime), \ |
||
| 911 | "Attempt to set algorithm's current time with non-datetime" |
||
| 912 | assert dt.tzinfo == pytz.utc, \ |
||
| 913 | "Algorithm expects a utc datetime" |
||
| 914 | |||
| 915 | self.datetime = dt |
||
| 916 | self.perf_tracker.set_date(dt) |
||
| 917 | self.blotter.set_date(dt) |
||
| 918 | |||
| 919 | self._portfolio = None |
||
| 920 | self._account = None |
||
| 921 | |||
| 922 | @api_method |
||
| 923 | def get_datetime(self, tz=None): |
||
| 924 | """ |
||
| 925 | Returns the simulation datetime. |
||
| 926 | """ |
||
| 927 | dt = self.datetime |
||
| 928 | assert dt.tzinfo == pytz.utc, "Algorithm should have a utc datetime" |
||
| 929 | |||
| 930 | if tz is not None: |
||
| 931 | # Convert to the given timezone passed as a string or tzinfo. |
||
| 932 | if isinstance(tz, string_types): |
||
| 933 | tz = pytz.timezone(tz) |
||
| 934 | dt = dt.astimezone(tz) |
||
| 935 | |||
| 936 | return dt # datetime.datetime objects are immutable. |
||
| 937 | |||
| 938 | def update_dividends(self, dividend_frame): |
||
| 939 | """ |
||
| 940 | Set DataFrame used to process dividends. DataFrame columns should |
||
| 941 | contain at least the entries in zp.DIVIDEND_FIELDS. |
||
| 942 | """ |
||
| 943 | self.perf_tracker.update_dividends(dividend_frame) |
||
| 944 | |||
| 945 | @api_method |
||
| 946 | def set_slippage(self, slippage): |
||
| 947 | if not isinstance(slippage, SlippageModel): |
||
| 948 | raise UnsupportedSlippageModel() |
||
| 949 | if self.initialized: |
||
| 950 | raise OverrideSlippagePostInit() |
||
| 951 | self.blotter.slippage_func = slippage |
||
| 952 | |||
| 953 | @api_method |
||
| 954 | def set_commission(self, commission): |
||
| 955 | if not isinstance(commission, (PerShare, PerTrade, PerDollar)): |
||
| 956 | raise UnsupportedCommissionModel() |
||
| 957 | |||
| 958 | if self.initialized: |
||
| 959 | raise OverrideCommissionPostInit() |
||
| 960 | self.blotter.commission = commission |
||
| 961 | |||
| 962 | @api_method |
||
| 963 | def set_symbol_lookup_date(self, dt): |
||
| 964 | """ |
||
| 965 | Set the date for which symbols will be resolved to their sids |
||
| 966 | (symbols may map to different firms or underlying assets at |
||
| 967 | different times) |
||
| 968 | """ |
||
| 969 | try: |
||
| 970 | self._symbol_lookup_date = pd.Timestamp(dt, tz='UTC') |
||
| 971 | except ValueError: |
||
| 972 | raise UnsupportedDatetimeFormat(input=dt, |
||
| 973 | method='set_symbol_lookup_date') |
||
| 974 | |||
| 975 | # Remain backwards compatibility |
||
| 976 | @property |
||
| 977 | def data_frequency(self): |
||
| 978 | return self.sim_params.data_frequency |
||
| 979 | |||
| 980 | @data_frequency.setter |
||
| 981 | def data_frequency(self, value): |
||
| 982 | assert value in ('daily', 'minute') |
||
| 983 | self.sim_params.data_frequency = value |
||
| 984 | |||
| 985 | @api_method |
||
| 986 | def order_percent(self, sid, percent, |
||
| 987 | limit_price=None, stop_price=None, style=None): |
||
| 988 | """ |
||
| 989 | Place an order in the specified asset corresponding to the given |
||
| 990 | percent of the current portfolio value. |
||
| 991 | |||
| 992 | Note that percent must expressed as a decimal (0.50 means 50\%). |
||
| 993 | """ |
||
| 994 | value = self.portfolio.portfolio_value * percent |
||
| 995 | return self.order_value(sid, value, |
||
| 996 | limit_price=limit_price, |
||
| 997 | stop_price=stop_price, |
||
| 998 | style=style) |
||
| 999 | |||
| 1000 | @api_method |
||
| 1001 | def order_target(self, sid, target, |
||
| 1002 | limit_price=None, stop_price=None, style=None): |
||
| 1003 | """ |
||
| 1004 | Place an order to adjust a position to a target number of shares. If |
||
| 1005 | the position doesn't already exist, this is equivalent to placing a new |
||
| 1006 | order. If the position does exist, this is equivalent to placing an |
||
| 1007 | order for the difference between the target number of shares and the |
||
| 1008 | current number of shares. |
||
| 1009 | """ |
||
| 1010 | if sid in self.portfolio.positions: |
||
| 1011 | current_position = self.portfolio.positions[sid].amount |
||
| 1012 | req_shares = target - current_position |
||
| 1013 | return self.order(sid, req_shares, |
||
| 1014 | limit_price=limit_price, |
||
| 1015 | stop_price=stop_price, |
||
| 1016 | style=style) |
||
| 1017 | else: |
||
| 1018 | return self.order(sid, target, |
||
| 1019 | limit_price=limit_price, |
||
| 1020 | stop_price=stop_price, |
||
| 1021 | style=style) |
||
| 1022 | |||
| 1023 | @api_method |
||
| 1024 | def order_target_value(self, sid, target, |
||
| 1025 | limit_price=None, stop_price=None, style=None): |
||
| 1026 | """ |
||
| 1027 | Place an order to adjust a position to a target value. If |
||
| 1028 | the position doesn't already exist, this is equivalent to placing a new |
||
| 1029 | order. If the position does exist, this is equivalent to placing an |
||
| 1030 | order for the difference between the target value and the |
||
| 1031 | current value. |
||
| 1032 | If the Asset being ordered is a Future, the 'target value' calculated |
||
| 1033 | is actually the target exposure, as Futures have no 'value'. |
||
| 1034 | """ |
||
| 1035 | target_amount = self._calculate_order_value_amount(sid, target) |
||
| 1036 | return self.order_target(sid, target_amount, |
||
| 1037 | limit_price=limit_price, |
||
| 1038 | stop_price=stop_price, |
||
| 1039 | style=style) |
||
| 1040 | |||
| 1041 | @api_method |
||
| 1042 | def order_target_percent(self, sid, target, |
||
| 1043 | limit_price=None, stop_price=None, style=None): |
||
| 1044 | """ |
||
| 1045 | Place an order to adjust a position to a target percent of the |
||
| 1046 | current portfolio value. If the position doesn't already exist, this is |
||
| 1047 | equivalent to placing a new order. If the position does exist, this is |
||
| 1048 | equivalent to placing an order for the difference between the target |
||
| 1049 | percent and the current percent. |
||
| 1050 | |||
| 1051 | Note that target must expressed as a decimal (0.50 means 50\%). |
||
| 1052 | """ |
||
| 1053 | target_value = self.portfolio.portfolio_value * target |
||
| 1054 | return self.order_target_value(sid, target_value, |
||
| 1055 | limit_price=limit_price, |
||
| 1056 | stop_price=stop_price, |
||
| 1057 | style=style) |
||
| 1058 | |||
| 1059 | @api_method |
||
| 1060 | def get_open_orders(self, sid=None): |
||
| 1061 | if sid is None: |
||
| 1062 | return { |
||
| 1063 | key: [order.to_api_obj() for order in orders] |
||
| 1064 | for key, orders in iteritems(self.blotter.open_orders) |
||
| 1065 | if orders |
||
| 1066 | } |
||
| 1067 | if sid in self.blotter.open_orders: |
||
| 1068 | orders = self.blotter.open_orders[sid] |
||
| 1069 | return [order.to_api_obj() for order in orders] |
||
| 1070 | return [] |
||
| 1071 | |||
| 1072 | @api_method |
||
| 1073 | def get_order(self, order_id): |
||
| 1074 | if order_id in self.blotter.orders: |
||
| 1075 | return self.blotter.orders[order_id].to_api_obj() |
||
| 1076 | |||
| 1077 | @api_method |
||
| 1078 | def cancel_order(self, order_param): |
||
| 1079 | order_id = order_param |
||
| 1080 | if isinstance(order_param, zipline.protocol.Order): |
||
| 1081 | order_id = order_param.id |
||
| 1082 | |||
| 1083 | self.blotter.cancel(order_id) |
||
| 1084 | |||
| 1085 | @api_method |
||
| 1086 | @require_initialized(HistoryInInitialize()) |
||
| 1087 | def history(self, sids, bar_count, frequency, field, ffill=True): |
||
| 1088 | if self.data_portal is None: |
||
| 1089 | raise Exception("no data portal!") |
||
| 1090 | |||
| 1091 | return self.data_portal.get_history_window( |
||
| 1092 | sids, |
||
| 1093 | self.datetime, |
||
| 1094 | bar_count, |
||
| 1095 | frequency, |
||
| 1096 | field, |
||
| 1097 | ffill, |
||
| 1098 | ) |
||
| 1099 | |||
| 1100 | #################### |
||
| 1101 | # Account Controls # |
||
| 1102 | #################### |
||
| 1103 | |||
| 1104 | def register_account_control(self, control): |
||
| 1105 | """ |
||
| 1106 | Register a new AccountControl to be checked on each bar. |
||
| 1107 | """ |
||
| 1108 | if self.initialized: |
||
| 1109 | raise RegisterAccountControlPostInit() |
||
| 1110 | self.account_controls.append(control) |
||
| 1111 | |||
| 1112 | def validate_account_controls(self): |
||
| 1113 | for control in self.account_controls: |
||
| 1114 | control.validate(self.portfolio, |
||
| 1115 | self.account, |
||
| 1116 | self.get_datetime(), |
||
| 1117 | self.trading_client.current_data) |
||
| 1118 | |||
| 1119 | @api_method |
||
| 1120 | def set_max_leverage(self, max_leverage=None): |
||
| 1121 | """ |
||
| 1122 | Set a limit on the maximum leverage of the algorithm. |
||
| 1123 | """ |
||
| 1124 | control = MaxLeverage(max_leverage) |
||
| 1125 | self.register_account_control(control) |
||
| 1126 | |||
| 1127 | #################### |
||
| 1128 | # Trading Controls # |
||
| 1129 | #################### |
||
| 1130 | |||
| 1131 | def register_trading_control(self, control): |
||
| 1132 | """ |
||
| 1133 | Register a new TradingControl to be checked prior to order calls. |
||
| 1134 | """ |
||
| 1135 | if self.initialized: |
||
| 1136 | raise RegisterTradingControlPostInit() |
||
| 1137 | self.trading_controls.append(control) |
||
| 1138 | |||
| 1139 | @api_method |
||
| 1140 | def set_max_position_size(self, |
||
| 1141 | sid=None, |
||
| 1142 | max_shares=None, |
||
| 1143 | max_notional=None): |
||
| 1144 | """ |
||
| 1145 | Set a limit on the number of shares and/or dollar value held for the |
||
| 1146 | given sid. Limits are treated as absolute values and are enforced at |
||
| 1147 | the time that the algo attempts to place an order for sid. This means |
||
| 1148 | that it's possible to end up with more than the max number of shares |
||
| 1149 | due to splits/dividends, and more than the max notional due to price |
||
| 1150 | improvement. |
||
| 1151 | |||
| 1152 | If an algorithm attempts to place an order that would result in |
||
| 1153 | increasing the absolute value of shares/dollar value exceeding one of |
||
| 1154 | these limits, raise a TradingControlException. |
||
| 1155 | """ |
||
| 1156 | control = MaxPositionSize(asset=sid, |
||
| 1157 | max_shares=max_shares, |
||
| 1158 | max_notional=max_notional) |
||
| 1159 | self.register_trading_control(control) |
||
| 1160 | |||
| 1161 | @api_method |
||
| 1162 | def set_max_order_size(self, sid=None, max_shares=None, max_notional=None): |
||
| 1163 | """ |
||
| 1164 | Set a limit on the number of shares and/or dollar value of any single |
||
| 1165 | order placed for sid. Limits are treated as absolute values and are |
||
| 1166 | enforced at the time that the algo attempts to place an order for sid. |
||
| 1167 | |||
| 1168 | If an algorithm attempts to place an order that would result in |
||
| 1169 | exceeding one of these limits, raise a TradingControlException. |
||
| 1170 | """ |
||
| 1171 | control = MaxOrderSize(asset=sid, |
||
| 1172 | max_shares=max_shares, |
||
| 1173 | max_notional=max_notional) |
||
| 1174 | self.register_trading_control(control) |
||
| 1175 | |||
| 1176 | @api_method |
||
| 1177 | def set_max_order_count(self, max_count): |
||
| 1178 | """ |
||
| 1179 | Set a limit on the number of orders that can be placed within the given |
||
| 1180 | time interval. |
||
| 1181 | """ |
||
| 1182 | control = MaxOrderCount(max_count) |
||
| 1183 | self.register_trading_control(control) |
||
| 1184 | |||
| 1185 | @api_method |
||
| 1186 | def set_do_not_order_list(self, restricted_list): |
||
| 1187 | """ |
||
| 1188 | Set a restriction on which sids can be ordered. |
||
| 1189 | """ |
||
| 1190 | control = RestrictedListOrder(restricted_list) |
||
| 1191 | self.register_trading_control(control) |
||
| 1192 | |||
| 1193 | @api_method |
||
| 1194 | def set_long_only(self): |
||
| 1195 | """ |
||
| 1196 | Set a rule specifying that this algorithm cannot take short positions. |
||
| 1197 | """ |
||
| 1198 | self.register_trading_control(LongOnly()) |
||
| 1199 | |||
| 1200 | ############## |
||
| 1201 | # Pipeline API |
||
| 1202 | ############## |
||
| 1203 | @api_method |
||
| 1204 | @require_not_initialized(AttachPipelineAfterInitialize()) |
||
| 1205 | def attach_pipeline(self, pipeline, name, chunksize=None): |
||
| 1206 | """ |
||
| 1207 | Register a pipeline to be computed at the start of each day. |
||
| 1208 | """ |
||
| 1209 | if self._pipelines: |
||
| 1210 | raise NotImplementedError("Multiple pipelines are not supported.") |
||
| 1211 | if chunksize is None: |
||
| 1212 | # Make the first chunk smaller to get more immediate results: |
||
| 1213 | # (one week, then every half year) |
||
| 1214 | chunks = iter(chain([5], repeat(126))) |
||
| 1215 | else: |
||
| 1216 | chunks = iter(repeat(int(chunksize))) |
||
| 1217 | self._pipelines[name] = pipeline, chunks |
||
| 1218 | |||
| 1219 | # Return the pipeline to allow expressions like |
||
| 1220 | # p = attach_pipeline(Pipeline(), 'name') |
||
| 1221 | return pipeline |
||
| 1222 | |||
| 1223 | @api_method |
||
| 1224 | @require_initialized(PipelineOutputDuringInitialize()) |
||
| 1225 | def pipeline_output(self, name): |
||
| 1226 | """ |
||
| 1227 | Get the results of pipeline with name `name`. |
||
| 1228 | |||
| 1229 | Parameters |
||
| 1230 | ---------- |
||
| 1231 | name : str |
||
| 1232 | Name of the pipeline for which results are requested. |
||
| 1233 | |||
| 1234 | Returns |
||
| 1235 | ------- |
||
| 1236 | results : pd.DataFrame |
||
| 1237 | DataFrame containing the results of the requested pipeline for |
||
| 1238 | the current simulation date. |
||
| 1239 | |||
| 1240 | Raises |
||
| 1241 | ------ |
||
| 1242 | NoSuchPipeline |
||
| 1243 | Raised when no pipeline with the name `name` has been registered. |
||
| 1244 | |||
| 1245 | See Also |
||
| 1246 | -------- |
||
| 1247 | :meth:`zipline.pipeline.engine.PipelineEngine.run_pipeline` |
||
| 1248 | """ |
||
| 1249 | # NOTE: We don't currently support multiple pipelines, but we plan to |
||
| 1250 | # in the future. |
||
| 1251 | try: |
||
| 1252 | p, chunks = self._pipelines[name] |
||
| 1253 | except KeyError: |
||
| 1254 | raise NoSuchPipeline( |
||
| 1255 | name=name, |
||
| 1256 | valid=list(self._pipelines.keys()), |
||
| 1257 | ) |
||
| 1258 | return self._pipeline_output(p, chunks) |
||
| 1259 | |||
| 1260 | def _pipeline_output(self, pipeline, chunks): |
||
| 1261 | """ |
||
| 1262 | Internal implementation of `pipeline_output`. |
||
| 1263 | """ |
||
| 1264 | today = normalize_date(self.get_datetime()) |
||
| 1265 | try: |
||
| 1266 | data = self._pipeline_cache.unwrap(today) |
||
| 1267 | except Expired: |
||
| 1268 | data, valid_until = self._run_pipeline( |
||
| 1269 | pipeline, today, next(chunks), |
||
| 1270 | ) |
||
| 1271 | self._pipeline_cache = CachedObject(data, valid_until) |
||
| 1272 | |||
| 1273 | # Now that we have a cached result, try to return the data for today. |
||
| 1274 | try: |
||
| 1275 | return data.loc[today] |
||
| 1276 | except KeyError: |
||
| 1277 | # This happens if no assets passed the pipeline screen on a given |
||
| 1278 | # day. |
||
| 1279 | return pd.DataFrame(index=[], columns=data.columns) |
||
| 1280 | |||
| 1281 | def _run_pipeline(self, pipeline, start_date, chunksize): |
||
| 1282 | """ |
||
| 1283 | Compute `pipeline`, providing values for at least `start_date`. |
||
| 1284 | |||
| 1285 | Produces a DataFrame containing data for days between `start_date` and |
||
| 1286 | `end_date`, where `end_date` is defined by: |
||
| 1287 | |||
| 1288 | `end_date = min(start_date + chunksize trading days, |
||
| 1289 | simulation_end)` |
||
| 1290 | |||
| 1291 | Returns |
||
| 1292 | ------- |
||
| 1293 | (data, valid_until) : tuple (pd.DataFrame, pd.Timestamp) |
||
| 1294 | |||
| 1295 | See Also |
||
| 1296 | -------- |
||
| 1297 | PipelineEngine.run_pipeline |
||
| 1298 | """ |
||
| 1299 | days = self.trading_environment.trading_days |
||
| 1300 | |||
| 1301 | # Load data starting from the previous trading day... |
||
| 1302 | start_date_loc = days.get_loc(start_date) |
||
| 1303 | |||
| 1304 | # ...continuing until either the day before the simulation end, or |
||
| 1305 | # until chunksize days of data have been loaded. |
||
| 1306 | sim_end = self.sim_params.last_close.normalize() |
||
| 1307 | end_loc = min(start_date_loc + chunksize, days.get_loc(sim_end)) |
||
| 1308 | end_date = days[end_loc] |
||
| 1309 | |||
| 1310 | return \ |
||
| 1311 | self.engine.run_pipeline(pipeline, start_date, end_date), end_date |
||
| 1312 | |||
| 1313 | ################## |
||
| 1314 | # End Pipeline API |
||
| 1315 | ################## |
||
| 1316 | |||
| 1317 | @classmethod |
||
| 1318 | def all_api_methods(cls): |
||
| 1319 | """ |
||
| 1320 | Return a list of all the TradingAlgorithm API methods. |
||
| 1321 | """ |
||
| 1322 | return [ |
||
| 1323 | fn for fn in itervalues(vars(cls)) |
||
| 1324 | if getattr(fn, 'is_api_method', False) |
||
| 1325 | ] |
||
| 1326 |