mirror of
https://github.com/wassname/catalyst.git
synced 2026-07-13 17:42:42 +08:00
STY: autopep8 codebase.
This commit is contained in:
@@ -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:
|
||||
|
||||
@@ -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.
|
||||
|
||||
+13
-13
@@ -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,
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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, []
|
||||
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -190,7 +190,7 @@ def make_transform(talib_fn, name):
|
||||
self.talib_fn.info['name'])
|
||||
|
||||
TALibTransform.__name__ = name
|
||||
#return class
|
||||
# return class
|
||||
return TALibTransform
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
Reference in New Issue
Block a user