Permalink
Browse files

[ENH] Initial effort in py3k support

  • Loading branch information...
1 parent 7099543 commit 15f34cf707b913ef6be7d5e6ccede4195e52e0e3 @WeatherGod WeatherGod committed Nov 4, 2012
View
@@ -1,5 +1,5 @@
"la init"
-
+from __future__ import print_function
# Classes
from la.deflarry import larry
@@ -22,7 +22,7 @@
test = Tester().test
del Tester
except (ImportError, ValueError):
- print "No la unit testing available."
+ print("No la unit testing available.")
try:
# Namespace cleaning
View
@@ -1,4 +1,4 @@
-
+from __future__ import print_function
import datetime
import numpy as np
import la
@@ -110,10 +110,10 @@ def quotes(tickers, date1=None, date2=None, adjust=True, verbose=False):
lar = None
items = ['open', 'close', 'high', 'low', 'volume', 'adjclose']
if verbose:
- print "Load data"
+ print("Load data")
for ticker in tickers:
if verbose:
- print "\t" + ticker
+ print("\t" + ticker)
data, dates = quotes_historical_yahoo(ticker, date1, date2)
data = np.array(data).T
qlar = la.larry(data, [items, dates])
View

Large diffs are not rendered by default.

Oops, something went wrong.
@@ -95,7 +95,7 @@ def quotes_historical_yahoo(ticker, date1, date2):
data, dates = parse_yahoo_historical(fh)
if len(data) == 0:
return None
- except IOError, exc:
+ except IOError as exc:
warnings.warn('urlopen() failure\n' + exc.strerror[1])
return None
return data, dates
View
@@ -1,7 +1,7 @@
"""
pretty table code was copied from http://code.activestate.com/recipes/267662/
"""
-
+from __future__ import print_function
import cStringIO, operator
def indent(rows, hasHeader=False, headerChar='-', delim=' | ', justify='left',
@@ -35,14 +35,13 @@ def rowWrapper(row):
# select the appropriate justify method
justify = {'center':str.center, 'right':str.rjust, 'left':str.ljust}[justify.lower()]
output=cStringIO.StringIO()
- if separateRows: print >> output, rowSeparator
+ if separateRows: print(rowSeparator, file=output)
for physicalRows in logicalRows:
for row in physicalRows:
- print >> output, \
- prefix \
+ print(prefix \
+ delim.join([justify(str(item),width) for (item,width) in zip(row,maxWidths)]) \
- + postfix
- if separateRows or hasHeader: print >> output, rowSeparator; hasHeader=False
+ + postfix, file=output)
+ if separateRows or hasHeader: print(rowSeparator, file=output); hasHeader=False
return output.getvalue()
# written by Mike Brown
@@ -84,15 +83,15 @@ def wrap_always(text, width):
Aristidis,Papageorgopoulos,28,Senior Reseacher'''
rows = [row.strip().split(',') for row in data.splitlines()]
- print 'Without wrapping function\n'
- print indent([labels]+rows, hasHeader=True)
+ print('Without wrapping function\n')
+ print(indent([labels]+rows, hasHeader=True))
# test indent with different wrapping functions
width = 10
for wrapper in (wrap_always,wrap_onspace,wrap_onspace_strict):
- print 'Wrapping function: %s(x,width=%d)\n' % (wrapper.__name__,width)
- print indent([labels]+rows, hasHeader=True, separateRows=True,
+ print('Wrapping function: %s(x,width=%d)\n' % (wrapper.__name__,width))
+ print(indent([labels]+rows, hasHeader=True, separateRows=True,
prefix='| ', postfix=' |',
- wrapfunc=lambda x: wrapper(x,width))
+ wrapfunc=lambda x: wrapper(x,width)))
# output:
#
View
@@ -15,7 +15,7 @@ def geometric_mean(x, axis=-1, check_for_greater_than_zero=True):
"""
if (x <= 0).any() and check_for_greater_than_zero:
msg = 'All elements of x (except NaNs) must be greater than zero.'
- raise ValueError, msg
+ raise ValueError(msg)
x = x.copy()
m = np.isnan(x)
np.putmask(x, m, 1.0)
@@ -84,7 +84,7 @@ def correlation(arr1, arr2, axis=None):
mask = np.logical_or(np.isnan(arr1), np.isnan(arr2))
if mask.any():
# arr1 and/or arr2 contain NaNs, so use slower NaN functions if needed
- if axis == None:
+ if axis is None:
x1 = arr1.flatten()
x2 = arr2.flatten()
idx = ~mask.flatten()
@@ -111,7 +111,7 @@ def correlation(arr1, arr2, axis=None):
den = np.sqrt(bn.nansum(x1**2, axis) * bn.nansum(x2**2, axis))
else:
# Neither arr1 or arr2 contains nans, so use faster non-nan functions
- if axis == None:
+ if axis is None:
x1 = arr1.flatten()
x2 = arr2.flatten()
x1 = x1 - x1.mean()
@@ -153,7 +153,7 @@ def covMissing(R):
normalization = np.dot(mask, mask.T)
if np.any(normalization < 2):
- raise ValueError, 'covMissing: not enough observations'
+ raise ValueError('covMissing: not enough observations')
C = np.dot(R, R.T) / normalization
View
@@ -52,7 +52,7 @@ def move_nanmedian(arr, window, axis=-1, method='loop'):
y = move_func_loop(bn.nanmedian, arr, window, axis=axis)
else:
msg = "`method` must be 'strides' or 'loop'."
- raise ValueError, msg
+ raise ValueError(msg)
return y
# RANKING -------------------------------------------------------------------
@@ -119,7 +119,7 @@ def move_nanranking(arr, window, axis=-1, method='strides'):
y = move_func_loop(lastrank, arr, window, axis=axis)
else:
msg = "`method` must be 'strides' or 'loop'."
- raise ValueError, msg
+ raise ValueError(msg)
return y
# GENERAL --------------------------------------------------------------------
@@ -171,17 +171,17 @@ def move_func(func, arr, window, axis=-1, method='loop', **kwargs):
y = move_func_loop(func, arr, window, axis=axis, **kwargs)
else:
msg = "`method` must be 'strides' or 'loop'."
- raise ValueError, msg
+ raise ValueError(msg)
return y
def move_func_loop(func, arr, window, axis=-1, **kwargs):
"Generic moving window function implemented with a python loop."
- if axis == None:
- raise ValueError, "An `axis` value of None is not supported."
+ if axis is None:
+ raise ValueError("An `axis` value of None is not supported.")
if window < 1:
- raise ValueError, "`window` must be at least 1."
+ raise ValueError("`window` must be at least 1.")
if window > arr.shape[axis]:
- raise ValueError, "`window` is too long."
+ raise ValueError("`window` is too long.")
y = nans(arr.shape)
idx1 = [slice(None)] * arr.ndim
idx2 = list(idx1)
@@ -193,19 +193,19 @@ def move_func_loop(func, arr, window, axis=-1, **kwargs):
def move_func_strides(func, arr, window, axis=-1, **kwargs):
"Generic moving window function implemented with strides."
- if axis == None:
- raise ValueError, "An `axis` value of None is not supported."
+ if axis is None:
+ raise ValueError("An `axis` value of None is not supported.")
if window < 1:
- raise ValueError, "`window` must be at least 1."
+ raise ValueError("`window` must be at least 1.")
if window > arr.shape[axis]:
- raise ValueError, "`window` is too long."
+ raise ValueError("`window` is too long.")
ndim = arr.ndim
as_strided = np.lib.stride_tricks.as_strided
idx = range(ndim)
axis = idx[axis]
arrshape0 = tuple(arr.shape)
if axis >= ndim:
- raise IndexError, "`axis` is out of range."
+ raise IndexError("`axis` is out of range.")
if ndim == 1:
strides = arr.strides
shape = (arr.size - window + 1, window)
@@ -233,7 +233,7 @@ def move_func_strides(func, arr, window, axis=-1, **kwargs):
if axis > 0:
y = y.swapaxes(0, axis)
else:
- raise ValueError, "Only 1d, 2d, and 3d input arrays are supported."
+ raise ValueError("Only 1d, 2d, and 3d input arrays are supported.")
ynan = nans(arrshape0)
index = [slice(None)] * ndim
index[axis] = slice(window - 1, None)
@@ -288,11 +288,11 @@ def movingsum(arr, window, skip=0, axis=-1, norm=False):
# Check input
if window < 1:
- raise ValueError, 'window must be at least 1'
+ raise ValueError('window must be at least 1')
if window > arr.shape[axis]:
- raise ValueError, 'Window is too big.'
+ raise ValueError('Window is too big.')
if skip > arr.shape[axis]:
- raise IndexError, 'Your skip is too large.'
+ raise IndexError('Your skip is too large.')
# Set missing values to 0
m = ismissing(arr)
@@ -347,9 +347,9 @@ def movingrank(x, window, axis=-1):
If a window is all NaNs except last, this is returned as NaN
"""
if window > x.shape[axis]:
- raise ValueError, 'Window is too big.'
+ raise ValueError('Window is too big.')
if window < 2:
- raise ValueError, 'Window is too small.'
+ raise ValueError('Window is too small.')
nt = x.shape[axis]
mr = np.nan * np.zeros(x.shape)
for i in xrange(window-1, nt):
View
@@ -107,7 +107,7 @@ def lastrank(x, axis=-1, decay=0.0):
r = (g + g + e - w.flat[-1]) / 2.0
r = r / (n - w.flat[-1])
elif decay < 0:
- raise ValueError, 'decay must be greater than or equal to zero.'
+ raise ValueError('decay must be greater than or equal to zero.')
else:
# Special case the most common case, decay = 0, for speed
g = (x[indlast] > x).sum(axis)
@@ -270,7 +270,7 @@ def quantile(x, q, axis=0):
"""
if q < 1:
- raise ValueError, 'q must be one or greater.'
+ raise ValueError('q must be one or greater.')
elif q == 1:
y = np.zeros(x.shape)
np.putmask(y, np.isnan(x), np.nan)
@@ -279,13 +279,13 @@ def quantile(x, q, axis=0):
if q > x.size:
msg = 'q must be less than or equal to the number of elements '
msg += 'in x.'
- raise ValueError, msg
+ raise ValueError(msg)
y = np.apply_along_axis(_quantileraw1d, 0, x.flat, q)
y = y.reshape(x.shape)
else:
if q > x.shape[axis]:
msg = 'q must be less than or equal to the number of rows in x.'
- raise ValueError, msg
+ raise ValueError(msg)
y = np.apply_along_axis(_quantileraw1d, axis, x, q)
y = y - 1.0
y = 1.0 * y / (q - 1.0)
View
@@ -171,7 +171,7 @@ def flattenlabel(label, order='C'):
"""
if order not in ('C', 'F'):
- raise ValueError, "order must be 'C' or 'F'"
+ raise ValueError("order must be 'C' or 'F'")
label = list(label)
if order == 'C':
label = label[::-1]
Oops, something went wrong.

0 comments on commit 15f34cf

Please sign in to comment.