diff --git a/tests/risk/test_risk.py b/tests/risk/test_risk.py index 0526ac11..b850ec64 100644 --- a/tests/risk/test_risk.py +++ b/tests/risk/test_risk.py @@ -91,7 +91,7 @@ class TestRisk(unittest.TestCase): def test_drawdown(self): returns = factory.create_returns_from_list( [1.0, -0.5, 0.8, .17, 1.0, -0.1, -0.45], self.sim_params) - #200, 100, 180, 210.6, 421.2, 379.8, 208.494 + # 200, 100, 180, 210.6, 421.2, 379.8, 208.494 metrics = risk.RiskMetricsPeriod(returns[0].date, returns[-1].date, returns) @@ -398,7 +398,7 @@ class TestRisk(unittest.TestCase): # Month 4 seems to be the problem. Variance is disabled # just to avoid distraction - it is much closer than covariance # and can probably pass with 6 significant digits instead of 7. - #re-enable variance, alpha, and beta tests once this is resolved + # re-enable variance, alpha, and beta tests once this is resolved def test_algorithm_covariance_06(self): answer_key_month_periods = ANSWER_KEY.get_values( AnswerKey.ALGORITHM_PERIOD_COVARIANCE['Monthly'], @@ -624,7 +624,7 @@ class TestRisk(unittest.TestCase): minute=0, tzinfo=pytz.utc) - #1992 and 1996 were leap years + # 1992 and 1996 were leap years total_days = 365 * 5 + 2 end = start + datetime.timedelta(days=total_days) sim_params90s = SimulationParameters( @@ -682,10 +682,10 @@ class TestRisk(unittest.TestCase): ) def assert_last_day(self, period_end): - #30 days has september, april, june and november + # 30 days has september, april, june and november if period_end.month in [9, 4, 6, 11]: self.assertEqual(period_end.day, 30) - #all the rest have 31, except for february + # all the rest have 31, except for february elif(period_end.month != 2): self.assertEqual(period_end.day, 31) else: diff --git a/tests/test_finance.py b/tests/test_finance.py index 6ee06847..075df882 100644 --- a/tests/test_finance.py +++ b/tests/test_finance.py @@ -79,7 +79,7 @@ class FinanceTestCase(TestCase): @timed(DEFAULT_TIMEOUT) def test_trading_environment(self): - #holidays taken from: http://www.nyse.com/press/1191407641943.html + # holidays taken from: http://www.nyse.com/press/1191407641943.html new_years = datetime(2008, 1, 1, tzinfo=pytz.utc) mlk_day = datetime(2008, 1, 21, tzinfo=pytz.utc) presidents = datetime(2008, 2, 18, tzinfo=pytz.utc) @@ -145,7 +145,7 @@ class FinanceTestCase(TestCase): expected_trading_days = ( datetime(2007, 12, 31, tzinfo=pytz.utc), # Skip new years - #holidays taken from: http://www.nyse.com/press/1191407641943.html + # holidays taken from: http://www.nyse.com/press/1191407641943.html datetime(2008, 1, 2, tzinfo=pytz.utc), datetime(2008, 1, 3, tzinfo=pytz.utc), datetime(2008, 1, 4, tzinfo=pytz.utc), @@ -161,7 +161,7 @@ class FinanceTestCase(TestCase): @timed(EXTENDED_TIMEOUT) def test_full_zipline(self): - #provide enough trades to ensure all orders are filled. + # provide enough trades to ensure all orders are filled. self.zipline_test_config['order_count'] = 100 # making a small order amount, so that each order is filled # in a single transaction, and txn_count == order_count. diff --git a/tests/test_perf_tracking.py b/tests/test_perf_tracking.py index 192f16eb..b1033ba0 100644 --- a/tests/test_perf_tracking.py +++ b/tests/test_perf_tracking.py @@ -168,7 +168,7 @@ class TestDividendPerformance(unittest.TestCase): def test_long_position_receives_dividend(self): with trading.TradingEnvironment(): - #post some trades in the market + # post some trades in the market events = factory.create_trade_history( 1, [10, 10, 10, 10, 10], @@ -213,7 +213,7 @@ class TestDividendPerformance(unittest.TestCase): self.assertEqual(cash_pos, [9000, 9000, 10000, 10000, 10000]) def test_post_ex_long_position_receives_no_dividend(self): - #post some trades in the market + # post some trades in the market events = factory.create_trade_history( 1, [10, 10, 10, 10, 10], @@ -248,7 +248,7 @@ class TestDividendPerformance(unittest.TestCase): self.assertEqual(cumulative_cash_flows, [0, 0, -1000, -1000, -1000]) def test_selling_before_dividend_payment_still_gets_paid(self): - #post some trades in the market + # post some trades in the market events = factory.create_trade_history( 1, [10, 10, 10, 10, 10], @@ -285,7 +285,7 @@ class TestDividendPerformance(unittest.TestCase): self.assertEqual(cumulative_cash_flows, [-1000, -1000, 0, 1000, 1000]) def test_buy_and_sell_before_ex(self): - #post some trades in the market + # post some trades in the market events = factory.create_trade_history( 1, [10, 10, 10, 10, 10, 10], @@ -322,7 +322,7 @@ class TestDividendPerformance(unittest.TestCase): self.assertEqual(cumulative_cash_flows, [0, -1000, 0, 0, 0, 0]) def test_ending_before_pay_date(self): - #post some trades in the market + # post some trades in the market events = factory.create_trade_history( 1, [10, 10, 10, 10, 10], @@ -364,7 +364,7 @@ class TestDividendPerformance(unittest.TestCase): ) def test_short_position_pays_dividend(self): - #post some trades in the market + # post some trades in the market events = factory.create_trade_history( 1, [10, 10, 10, 10, 10], @@ -401,7 +401,7 @@ class TestDividendPerformance(unittest.TestCase): self.assertEqual(cumulative_cash_flows, [0, 1000, 1000, 0, 0]) def test_no_position_receives_no_dividend(self): - #post some trades in the market + # post some trades in the market events = factory.create_trade_history( 1, [10, 10, 10, 10, 10], @@ -464,7 +464,7 @@ class TestPositionPerformance(unittest.TestCase): verify that the performance period calculates properly for a single buy transaction """ - #post some trades in the market + # post some trades in the market trades = factory.create_trade_history( 1, [10, 10, 10, 11], @@ -602,7 +602,7 @@ single short-sale transaction""" # reflects the new price trades_2 = trades[-2:] - #simulate a rollover to a new period + # simulate a rollover to a new period pp.rollover() for trade in trades_2: @@ -659,7 +659,7 @@ single short-sale transaction""" "drop of 2 on -100 shares should be 200" ) - #now run a performance period encompassing the entire trade sample. + # now run a performance period encompassing the entire trade sample. ppTotal = perf.PerformancePeriod(1000.0) for trade in trades_1: @@ -876,7 +876,7 @@ shares in position" "should have a cost basis of 11.33" ) - #print "second period pnl is {pnl}".format(pnl=pp2.pnl) + # print "second period pnl is {pnl}".format(pnl=pp2.pnl) self.assertEqual(pp.pnl, -800, "this period goes from +400 to -400") pp3 = perf.PerformancePeriod(1000.0) @@ -1065,8 +1065,8 @@ class TestPerformanceTracker(unittest.TestCase): def trades_with_txns(self, events, no_txn_dt): for event in events: - #create a transaction for all but - #first trade in each sid, to simulate None transaction + # create a transaction for all but + # first trade in each sid, to simulate None transaction if event.dt != no_txn_dt: order = Order(**{ 'sid': event.sid, diff --git a/zipline/data/benchmarks.py b/zipline/data/benchmarks.py index 86663937..6f32a667 100644 --- a/zipline/data/benchmarks.py +++ b/zipline/data/benchmarks.py @@ -123,7 +123,7 @@ def get_benchmark_returns(symbol, start_date=None, end_date=None): curr_open = data_points[i]['open'] returns = (data_points[i]['close'] - curr_open) / curr_open else: - prev_close = data_points[i-1]['close'] + prev_close = data_points[i - 1]['close'] returns = (data_point['close'] - prev_close) / prev_close daily_return = DailyReturn(date=data_point['date'], returns=returns) benchmark_returns.append(daily_return) diff --git a/zipline/examples/olmar.py b/zipline/examples/olmar.py index 9d05579c..23e9611f 100644 --- a/zipline/examples/olmar.py +++ b/zipline/examples/olmar.py @@ -72,15 +72,15 @@ class OLMAR(TradingAlgorithm): # Expected return with current portfolio exp_return = np.dot(self.b_t, x_tilde) weight = self.eps - exp_return - variability = (np.linalg.norm(mark_rel_dev))**2 + variability = (np.linalg.norm(mark_rel_dev)) ** 2 # test for divide-by-zero case if variability == 0.0: step_size = 0 else: - step_size = max(0, weight/variability) + step_size = max(0, weight / variability) - b = self.b_t + step_size*mark_rel_dev + b = self.b_t + step_size * mark_rel_dev b_norm = simplex_projection(b) np.testing.assert_almost_equal(b_norm.sum(), 1) @@ -90,7 +90,7 @@ class OLMAR(TradingAlgorithm): self.b_t = b_norm def rebalance_portfolio(self, data, desired_port): - #rebalance portfolio + # rebalance portfolio desired_amount = np.zeros_like(desired_port) current_amount = np.zeros_like(desired_port) prices = np.zeros_like(desired_port) @@ -145,8 +145,8 @@ def simplex_projection(v, b=1): u = np.sort(v)[::-1] sv = np.cumsum(u) - rho = np.where(u > (sv - b) / np.arange(1, p+1))[0][-1] - theta = np.max([0, (sv[rho] - b) / (rho+1)]) + rho = np.where(u > (sv - b) / np.arange(1, p + 1))[0][-1] + theta = np.max([0, (sv[rho] - b) / (rho + 1)]) w = (v - theta) w[w < 0] = 0 return w diff --git a/zipline/finance/performance.py b/zipline/finance/performance.py index 669ef091..c4b0a112 100644 --- a/zipline/finance/performance.py +++ b/zipline/finance/performance.py @@ -288,7 +288,7 @@ class PerformanceTracker(object): self.event_count += 1 if event.type == zp.DATASOURCE_TYPE.TRADE: - #update last sale + # update last sale for perf_period in self.perf_periods: perf_period.update_last_sale(event) @@ -334,7 +334,7 @@ class PerformanceTracker(object): self.all_benchmark_returns[midnight] = event.returns - #calculate performance as of last trade + # calculate performance as of last trade for perf_period in self.perf_periods: perf_period.calculate_performance() @@ -402,7 +402,7 @@ class PerformanceTracker(object): ) self.returns.append(todays_return_obj) - #update risk metrics for cumulative performance + # update risk metrics for cumulative performance self.cumulative_risk_metrics.update( todays_return_obj.date, todays_return_obj.returns, @@ -421,7 +421,7 @@ class PerformanceTracker(object): if self.market_close >= self.last_close: return daily_update - #move the market day markers forward + # move the market day markers forward self.market_open, self.market_close = \ trading.environment.next_open_and_close(self.market_open) @@ -560,7 +560,7 @@ class Position(object): if(self.sid != txn.sid): raise NameError('updating position with txn for a different sid') - #we're covering a short or closing a position + # we're covering a short or closing a position if(self.amount + txn.amount == 0): self.cost_basis = 0.0 self.amount = 0 diff --git a/zipline/finance/risk/cumulative.py b/zipline/finance/risk/cumulative.py index 5637ca31..fc9b8cb2 100644 --- a/zipline/finance/risk/cumulative.py +++ b/zipline/finance/risk/cumulative.py @@ -323,8 +323,8 @@ algorithm_returns ({algo_count}) in range {start} : {end} on {dt}" http://en.wikipedia.org/wiki/Beta_(finance) """ - #it doesn't make much sense to calculate beta for less than two days, - #so return none. + # it doesn't make much sense to calculate beta for less than two days, + # so return none. if len(self.algorithm_returns) < 2: return 0.0, 0.0, 0.0, 0.0, [] diff --git a/zipline/finance/risk/period.py b/zipline/finance/risk/period.py index f25af543..dfcb28bf 100644 --- a/zipline/finance/risk/period.py +++ b/zipline/finance/risk/period.py @@ -217,8 +217,8 @@ class RiskMetricsPeriod(object): http://en.wikipedia.org/wiki/Beta_(finance) """ - #it doesn't make much sense to calculate beta for less than two days, - #so return none. + # it doesn't make much sense to calculate beta for less than two days, + # so return none. if len(self.algorithm_returns) < 2: return 0.0, 0.0, 0.0, 0.0, [] @@ -254,7 +254,7 @@ class RiskMetricsPeriod(object): for r in self.algorithm_returns: try: cur_return += math.log(1.0 + r) - #this is a guard for a single day returning -100% + # this is a guard for a single day returning -100% except ValueError: log.debug("{cur} return, zeroing the returns".format( cur=cur_return)) diff --git a/zipline/finance/risk/report.py b/zipline/finance/risk/report.py index e0a1ea07..bd7a7a0d 100644 --- a/zipline/finance/risk/report.py +++ b/zipline/finance/risk/report.py @@ -129,8 +129,8 @@ class RiskReport(object): if len(self.algorithm_returns) == 0: return ends - #ensure that we have an end at the end of a calendar month, in case - #the return series ends mid-month... + # ensure that we have an end at the end of a calendar month, in case + # the return series ends mid-month... the_end = end.replace(day=1) + relativedelta(months=1) - one_day while True: cur_end = cur_start + relativedelta(months=months_per) - one_day diff --git a/zipline/test_algorithms.py b/zipline/test_algorithms.py index e55c9ca6..a87924d1 100644 --- a/zipline/test_algorithms.py +++ b/zipline/test_algorithms.py @@ -97,7 +97,7 @@ class TestAlgorithm(TradingAlgorithm): self.sid_filter = [self.sid] def handle_data(self, data): - #place an order for 100 shares of sid + # place an order for 100 shares of sid if self.incr < self.count: self.order(self.sid, self.amount) self.incr += 1 @@ -116,7 +116,7 @@ class HeavyBuyAlgorithm(TradingAlgorithm): self.incr = 0 def handle_data(self, data): - #place an order for 100 shares of sid + # place an order for 100 shares of sid self.order(self.sid, self.amount) self.incr += 1 diff --git a/zipline/transforms/ta.py b/zipline/transforms/ta.py index 3b813c73..0c83df94 100644 --- a/zipline/transforms/ta.py +++ b/zipline/transforms/ta.py @@ -190,7 +190,7 @@ def make_transform(talib_fn, name): self.talib_fn.info['name']) TALibTransform.__name__ = name - #return class + # return class return TALibTransform diff --git a/zipline/utils/data.py b/zipline/utils/data.py index b12fd367..67a3c4ae 100644 --- a/zipline/utils/data.py +++ b/zipline/utils/data.py @@ -82,7 +82,7 @@ class RollingPanel(object): self._roll_data() if set(frame.columns).difference(set(self.minor_axis)) or \ - set(frame.index).difference(set(self.items)): + set(frame.index).difference(set(self.items)): self._update_buffer(frame) self.buffer.loc[:, self.pos, :] = frame.ix[self.items].T diff --git a/zipline/utils/factory.py b/zipline/utils/factory.py index 065b4d41..c513bce7 100644 --- a/zipline/utils/factory.py +++ b/zipline/utils/factory.py @@ -223,7 +223,7 @@ def create_returns_from_list(returns, sim_params): current = sim_params.first_open test_range = [] - #sometimes the range starts with a non-trading day. + # sometimes the range starts with a non-trading day. if not trading.environment.is_trading_day(current): current = trading.environment.next_trading_day(current) @@ -292,7 +292,7 @@ def create_trade_source(sids, trade_count, # TODO: do we need to set the trading environment's end to same dt as # the last trade in the history? - #sim_params.period_end = trade_history[-1].dt + # sim_params.period_end = trade_history[-1].dt return source