From d67e5d7a4bee9030c94b17b9cd3f2d5724b5e820 Mon Sep 17 00:00:00 2001 From: fawce Date: Sat, 16 Feb 2013 21:51:21 -0500 Subject: [PATCH] factory had a bug in the creation of trade history that traversed daylight savings time changes. added a fix and a test. --- tests/test_perf_tracking.py | 11 +++++++++++ zipline/utils/factory.py | 16 ++++++++++++---- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/tests/test_perf_tracking.py b/tests/test_perf_tracking.py index b9187130..62d5734a 100644 --- a/tests/test_perf_tracking.py +++ b/tests/test_perf_tracking.py @@ -28,6 +28,7 @@ from zipline.utils.protocol_utils import ndict from zipline.gens.composites import date_sorted_sources from zipline.finance.trading import SimulationParameters +import zipline.finance.trading as trading from zipline.utils.factory import create_random_simulation_parameters onesec = datetime.timedelta(seconds=1) @@ -44,6 +45,16 @@ class TestDividendPerformance(unittest.TestCase): self.sim_params.capital_base = 10e3 + def test_market_hours_calculations(self): + with trading.TradingEnvironment(): + # DST in US/Eastern began on Sunday March 14, 2010 + before = datetime.datetime(2010, 3, 12, 14, 30, tzinfo=pytz.utc) + after = factory.get_next_trading_dt( + before, + datetime.timedelta(days=1) + ) + self.assertEqual(after.hour, 13) + def test_long_position_receives_dividend(self): #post some trades in the market events = factory.create_trade_history( diff --git a/zipline/utils/factory.py b/zipline/utils/factory.py index 34c8b064..4f9d99d7 100644 --- a/zipline/utils/factory.py +++ b/zipline/utils/factory.py @@ -20,6 +20,7 @@ Factory functions to prepare useful data for tests. import pytz import random from collections import OrderedDict +from delorean import Delorean import pandas as pd from pandas.io.data import DataReader @@ -54,6 +55,7 @@ def create_simulation_parameters(year=2006, start=None, end=None, def create_random_simulation_parameters(): + trading.environment = trading.TradingEnvironment() treasury_curves = trading.environment.treasury_curves for n in range(100): @@ -84,13 +86,19 @@ check treasury and benchmark data in findb, and re-run the test.""" def get_next_trading_dt(current, interval): - next = current + naive = current.replace(tzinfo=None) + delo = Delorean(naive, "UTC") + ex_tz = trading.environment.exchange_tz + next_dt = delo.shift(ex_tz).datetime + while True: - next = next + interval - if trading.environment.is_market_hours(next): + next_dt = next_dt + interval + next_delo = Delorean(next_dt.replace(tzinfo=None), ex_tz) + next_utc = next_delo.shift("UTC").datetime + if trading.environment.is_market_hours(next_utc): break - return next + return next_utc def create_trade_history(sid, prices, amounts, interval, sim_params,