diff --git a/tests/test_algorithm.py b/tests/test_algorithm.py index a2688b28..c74a346d 100644 --- a/tests/test_algorithm.py +++ b/tests/test_algorithm.py @@ -155,6 +155,7 @@ from zipline.test_algorithms import ( call_with_good_kwargs_get_open_orders, call_with_no_kwargs_get_open_orders, empty_positions, + set_benchmark_algo, no_handle_data, ) from zipline.utils.api_support import ZiplineAPI, set_algo_instance @@ -1819,6 +1820,28 @@ def handle_data(context, data): self.assertTrue(all(num_positions == 0)) self.assertTrue(all(amounts == 0)) + @parameterized.expand([ + ('noop_algo', noop_algo), + ('with_benchmark_set', set_benchmark_algo)] + ) + def test_zero_trading_days(self, name, algocode): + """ + Test that when we run a simulation with no trading days (e.g. beginning + and ending the same weekend), we don't crash on calculating the + benchmark + """ + sim_params = factory.create_simulation_parameters( + start=pd.Timestamp('2006-01-14', tz='UTC'), + end=pd.Timestamp('2006-01-15', tz='UTC') + ) + + algo = TradingAlgorithm( + script=algocode, + sim_params=sim_params, + env=self.env + ) + algo.run(self.data_portal) + class TestGetDatetime(WithLogger, WithSimParams, diff --git a/zipline/sources/benchmark_source.py b/zipline/sources/benchmark_source.py index ab4b2c63..d3a33c58 100644 --- a/zipline/sources/benchmark_source.py +++ b/zipline/sources/benchmark_source.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. +import pandas as pd + from zipline.errors import ( InvalidBenchmarkAsset, BenchmarkAssetNotAvailableTooEarly, @@ -29,7 +31,9 @@ class BenchmarkSource(object): self.emission_rate = emission_rate self.data_portal = data_portal - if self.benchmark_sid: + if len(trading_days) == 0: + self._precalculated_series = pd.Series() + elif self.benchmark_sid: self.benchmark_asset = self.env.asset_finder.retrieve_asset( self.benchmark_sid) diff --git a/zipline/test_algorithms.py b/zipline/test_algorithms.py index 39c4151b..7ac81a06 100644 --- a/zipline/test_algorithms.py +++ b/zipline/test_algorithms.py @@ -1140,3 +1140,14 @@ def test_history(context,data): record(amounts=context.portfolio.positions[context.sid].amount) record(num_positions=len(context.portfolio.positions)) """ + +set_benchmark_algo = """ +from zipline.api import symbol, set_benchmark + +def initialize(context): + set_benchmark(symbol('TEST')) + context.sid = symbol('TEST') + +def handle_data(context, data): + pass +"""