def test_doc_differentiates(self): a = sentinel('sentinel-name', 'original-doc') with self.assertRaises(ValueError) as e: sentinel(a.__name__, 'new-doc') msg = str(e.exception) self.assertIn(a.__name__, msg) self.assertIn(a.__doc__, msg)
def test_doc_differentiates(self): # the following assignment must be exactly one source line above # the assignment of ``a``. line = sys._getframe().f_lineno a = sentinel("sentinel-name", "original-doc") with self.assertRaises(ValueError) as e: sentinel(a.__name__, "new-doc") msg = str(e.exception) self.assertIn(a.__name__, msg) self.assertIn(a.__doc__, msg) # strip the 'c' in case ``__file__`` is a .pyc and we are running this # test twice in the same process... self.assertIn("%s:%s" % (__file__.rstrip("c"), line + 1), msg)
def test_doc_differentiates(self): # the following assignment must be exactly one source line above # the assignment of ``a``. line = sys._getframe().f_lineno a = sentinel('sentinel-name', 'original-doc') with self.assertRaises(ValueError) as e: sentinel(a.__name__, 'new-doc') msg = str(e.exception) self.assertIn(a.__name__, msg) self.assertIn(a.__doc__, msg) # strip the 'c' in case ``__file__`` is a .pyc and we are running this # test twice in the same process... self.assertIn('%s:%s' % (__file__.rstrip('c'), line + 1), msg)
class TestingSlippage(SlippageModel): """ Slippage model that fills a constant number of shares per tick, for testing purposes. Parameters ---------- filled_per_tick : int or TestingSlippage.ALL The number of shares to fill on each call to process_order. If TestingSlippage.ALL is passed, the entire order is filled. See also -------- zipline.finance.slippage.SlippageModel """ ALL = sentinel('ALL') allowed_asset_types = (Equity, ) def __init__(self, filled_per_tick): super(TestingSlippage, self).__init__() self.filled_per_tick = filled_per_tick def process_order(self, data, order): price = data.current(order.asset, "close") if self.filled_per_tick is self.ALL: volume = order.amount else: volume = self.filled_per_tick return (price, volume)
class tmp_assets_db(object): """Create a temporary assets sqlite database. This is meant to be used as a context manager. Parameters ---------- url : string The URL for the database connection. **frames The frames to pass to the AssetDBWriter. By default this maps equities: ('A', 'B', 'C') -> map(ord, 'ABC') See Also -------- empty_assets_db tmp_asset_finder """ _default_equities = sentinel('_default_equities') def __init__(self, url='sqlite:///:memory:', equities=_default_equities, **frames): self._url = url self._eng = None if equities is self._default_equities: equities = make_simple_equity_info( list(map(ord, 'ABC')), pd.Timestamp(0), pd.Timestamp('2015'), ) frames['equities'] = equities self._frames = frames self._eng = None # set in enter and exit def __enter__(self): self._eng = eng = create_engine(self._url) AssetDBWriter(eng).write(**self._frames) return eng def __exit__(self, *excinfo): assert self._eng is not None, '_eng was not set in __enter__' self._eng.dispose() self._eng = None
class calendars(object): US_EQUITIES = sentinel('US_EQUITIES') US_FUTURES = sentinel('US_FUTURES')
TermInputsNotSpecified, TermOutputsEmpty, UnsupportedDType, WindowLengthNotSpecified, ) from zipline.lib.adjusted_array import can_represent_dtype from zipline.utils.memoize import lazyval from zipline.utils.numpy_utils import ( bool_dtype, default_missing_value_for_dtype, ) from zipline.utils.sentinel import sentinel NotSpecified = sentinel( 'NotSpecified', 'Singleton sentinel value used for Term defaults.', ) NotSpecifiedType = type(NotSpecified) class Term(with_metaclass(ABCMeta, object)): """ Base class for terms in a Pipeline API compute graph. """ # These are NotSpecified because a subclass is required to provide them. dtype = NotSpecified domain = NotSpecified missing_value = NotSpecified # Subclasses aren't required to provide `params`. The default behavior is
def test_pickle_roundtrip(self): a = sentinel("a") self.assertIs(loads(dumps(a)), a)
def test_memo(self): assert sentinel("a") is sentinel("a")
def test_name(self): self.assertEqual(sentinel("a").__name__, "a")
datetime64ns_dtype, default_fillvalue_for_dtype, float64_dtype, int64_dtype, uint8_dtype, ) from zipline.utils.memoize import lazyval from zipline.utils.sentinel import sentinel # These class names are all the same because of our bootleg templating system. from ._float64window import AdjustedArrayWindow as Float64Window from ._int64window import AdjustedArrayWindow as Int64Window from ._uint8window import AdjustedArrayWindow as UInt8Window Infer = sentinel( 'Infer', "Sentinel used to say 'infer missing_value from data type.'" ) NOMASK = None SUPPORTED_NUMERIC_DTYPES = frozenset( map(dtype, [float32, float64, int32, int64, uint32]) ) CONCRETE_WINDOW_TYPES = { float64_dtype: Float64Window, int64_dtype: Int64Window, uint8_dtype: UInt8Window, } def _normalize_array(data): """ Coerce buffer data for an AdjustedArray into a standard scalar
def test_name(self): assert sentinel("a").__name__ == "a"
def test_name(self): self.assertEqual(sentinel('a').__name__, 'a')
def test_new(self): with pytest.raises(TypeError): type(sentinel("a"))()
def test_pickle_roundtrip(self): a = sentinel("a") assert loads(dumps(a)) is a
def test_repr(self): assert repr(sentinel("a")) == "sentinel('a')"
def test_deepcopy(self): a = sentinel("a") assert deepcopy(a) is a
def test_copy(self): a = sentinel("a") assert copy(a) is a
from zipline.utils.sentinel import sentinel NotSpecified = sentinel( "NotSpecified", "Singleton sentinel value used for Term defaults.", ) NotSpecifiedType = type(NotSpecified)
def test_doc(self): self.assertEqual(sentinel('a', 'b').__doc__, 'b')
True Notes ----- This function will force ``seq`` to completion. """ ret = tuple(zip(*_gen_unzip(map(tuple, seq), elem_len))) if ret: return ret if elem_len is None: raise ValueError("cannot unzip empty sequence without 'elem_len'") return ((),) * elem_len _no_default = sentinel('_no_default') def getattrs(value, attrs, default=_no_default): """ Perform a chained application of ``getattr`` on ``value`` with the values in ``attrs``. If ``default`` is supplied, return it if any of the attribute lookups fail. Parameters ---------- value : object Root of the lookup chain. attrs : iterable[str] Sequence of attributes to look up.
from interface import Interface from zipline.utils.sentinel import sentinel DEFAULT_FX_RATE = sentinel('DEFAULT_FX_RATE') class FXRateReader(Interface): def get_rates(self, rate, quote, bases, dts): """ Get rates to convert ``bases`` into ``quote``. Parameters ---------- rate : str Rate type to load. Readers intended for use with the Pipeline API should support at least ``zipline.data.fx.DEFAULT_FX_RATE``, which will be used by default for Pipeline API terms that don't specify a specific rate. quote : str Currency code of the currency into to convert. bases : np.array[object] Array of codes of the currencies from which to convert. A single currency may appear multiple times. dts : pd.DatetimeIndex Datetimes for which to load rates. Must be sorted in ascending order. Returns ------- rates : np.array
True Notes ----- This function will force ``seq`` to completion. """ ret = tuple(zip(*_gen_unzip(map(tuple, seq), elem_len))) if ret: return ret if elem_len is None: raise ValueError("cannot unzip empty sequence without 'elem_len'") return ((), ) * elem_len _no_default = sentinel('_no_default') def getattrs(value, attrs, default=_no_default): """ Perform a chained application of ``getattr`` on ``value`` with the values in ``attrs``. If ``default`` is supplied, return it if any of the attribute lookups fail. Parameters ---------- value : object Root of the lookup chain. attrs : iterable[str] Sequence of attributes to look up.
def test_copy(self): a = sentinel("a") self.assertIs(copy(a), a)
NotDType, TermInputsNotSpecified, TermOutputsEmpty, UnsupportedDType, WindowLengthNotSpecified, ) from zipline.lib.adjusted_array import can_represent_dtype from zipline.utils.memoize import lazyval from zipline.utils.numpy_utils import ( bool_dtype, default_missing_value_for_dtype, ) from zipline.utils.sentinel import sentinel NotSpecified = sentinel( 'NotSpecified', 'Singleton sentinel value used for Term defaults.', ) NotSpecifiedType = type(NotSpecified) class Term(with_metaclass(ABCMeta, object)): """ Base class for terms in a Pipeline API compute graph. """ # These are NotSpecified because a subclass is required to provide them. dtype = NotSpecified domain = NotSpecified missing_value = NotSpecified # Subclasses aren't required to provide `params`. The default behavior is
def test_repr(self): self.assertEqual( repr(sentinel("a")), "sentinel('a')", )
def test_doc(self): self.assertEqual(sentinel("a", "b").__doc__, "b")
def test_doc(self): assert sentinel("a", "b").__doc__ == "b"
def test_memo(self): self.assertIs(sentinel("a"), sentinel("a"))
def test_memo(self): self.assertIs(sentinel('a'), sentinel('a'))
def test_deepcopy(self): a = sentinel("a") self.assertIs(deepcopy(a), a)
def test_copy(self): a = sentinel('a') self.assertIs(copy(a), a)
def test_new(self): with self.assertRaises(TypeError): type(sentinel("a"))()
def test_deepcopy(self): a = sentinel('a') self.assertIs(deepcopy(a), a)
def test_weakreferencable(self): ref(sentinel("a"))
def test_repr(self): self.assertEqual( repr(sentinel('a')), "sentinel('a')", )
def test_new(self): with self.assertRaises(TypeError): type(sentinel('a'))()
def test_pickle_roundtrip(self): a = sentinel('a') self.assertIs(loads(dumps(a)), a)
""" def __init__(self, left, right): (mismatches,) = np.where(left != right) assert len(mismatches), "Not actually a mismatch!" super(CategoryMismatch, self).__init__( "LabelArray categories don't match:\n" "Mismatched Indices: {mismatches}\n" "Left: {left}\n" "Right: {right}".format( mismatches=mismatches, left=left[mismatches], right=right[mismatches], ) ) _NotPassed = sentinel('_NotPassed') class LabelArray(ndarray): """ An ndarray subclass for working with arrays of strings. Factorizes the input array into integers, but overloads equality on strings to check against the factor label. Parameters ---------- values : array-like Array of values that can be passed to np.asarray with dtype=object. missing_value : str Scalar value to treat as 'missing' for operations on ``self``.
def test_weakreferencable(self): ref(sentinel('a'))
""" def __init__(self, left, right): (mismatches, ) = np.where(left != right) assert len(mismatches), "Not actually a mismatch!" super(CategoryMismatch, self).__init__("LabelArray categories don't match:\n" "Mismatched Indices: {mismatches}\n" "Left: {left}\n" "Right: {right}".format( mismatches=mismatches, left=left[mismatches], right=right[mismatches], )) _NotPassed = sentinel('_NotPassed') class LabelArray(ndarray): """ An ndarray subclass for working with arrays of strings. Factorizes the input array into integers, but overloads equality on strings to check against the factor label. Parameters ---------- values : array-like Array of values that can be passed to np.asarray with dtype=object. missing_value : str Scalar value to treat as 'missing' for operations on ``self``.
ordered_dict[key] = new_first_element # add the items back in their original order ordered_dict.update(items) else: move_to_end = OrderedDict.move_to_end PeriodStats = namedtuple( 'PeriodStats', 'net_liquidation gross_leverage net_leverage', ) not_overridden = sentinel( 'not_overridden', 'Mark that an account field has not been overridden', ) class Ledger(object): """The ledger tracks all orders and transactions as well as the current state of the portfolio and positions. Attributes ---------- portfolio : zipline.protocol.Portfolio The updated portfolio being managed. account : zipline.protocol.Account The updated account being managed. position_tracker : PositionTracker The current set of positions.