From 4203c5441747deddc5b61d067576e4fda361e18e Mon Sep 17 00:00:00 2001 From: Jean Bredeche Date: Thu, 7 Apr 2016 09:35:09 -0400 Subject: [PATCH] ENH: make handle_data optional --- tests/test_algorithm.py | 8 ++++++-- zipline/algorithm.py | 9 +++++---- zipline/test_algorithms.py | 5 +++++ 3 files changed, 16 insertions(+), 6 deletions(-) diff --git a/tests/test_algorithm.py b/tests/test_algorithm.py index ad834933..92f52ea3 100644 --- a/tests/test_algorithm.py +++ b/tests/test_algorithm.py @@ -106,8 +106,8 @@ from zipline.test_algorithms import ( call_with_kwargs, call_without_kwargs, call_with_bad_kwargs_current, - call_with_bad_kwargs_history -) + call_with_bad_kwargs_history, + no_handle_data) from zipline.testing import ( make_jagged_equity_info, to_utc, @@ -1491,6 +1491,10 @@ class TestAlgoScript(TestCase): algo = TradingAlgorithm(script=noop_algo) algo.run(self.data_portal) + def test_no_handle_data(self): + algo = TradingAlgorithm(script=no_handle_data) + algo.run(self.data_portal) + def test_api_calls(self): algo = TradingAlgorithm(initialize=initialize_api, handle_data=handle_data_api, diff --git a/zipline/algorithm.py b/zipline/algorithm.py index 8e204710..90f9801e 100644 --- a/zipline/algorithm.py +++ b/zipline/algorithm.py @@ -318,6 +318,8 @@ class TradingAlgorithm(object): create_context=kwargs.pop('create_event_context', None), ) + self._handle_data = None + if self.algoscript is not None: filename = kwargs.pop('algo_filename', None) if filename is None: @@ -325,9 +327,7 @@ class TradingAlgorithm(object): code = compile(self.algoscript, filename, 'exec') exec_(code, self.namespace) self._initialize = self.namespace.get('initialize') - if 'handle_data' not in self.namespace: - raise ValueError('You must define a handle_data function.') - else: + if 'handle_data' in self.namespace: self._handle_data = self.namespace['handle_data'] self._before_trading_start = \ @@ -407,7 +407,8 @@ class TradingAlgorithm(object): self._in_before_trading_start = False def handle_data(self, data): - self._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 diff --git a/zipline/test_algorithms.py b/zipline/test_algorithms.py index 35d89668..32932cd9 100644 --- a/zipline/test_algorithms.py +++ b/zipline/test_algorithms.py @@ -784,6 +784,11 @@ def handle_data(context, data): pass """ +no_handle_data = """ +def initialize(context): + pass +""" + api_algo = """ from zipline.api import (order, set_slippage,