code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def _build_date(date, kwargs): """ Builds the date argument for event rules. """ if date is None: if not kwargs: raise ValueError('Must pass a date or kwargs') else: return datetime.date(**kwargs) elif kwargs: raise ValueError('Cannot pass kwargs and ...
Builds the date argument for event rules.
_build_date
python
quantopian/zipline
zipline/utils/events.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/events.py
Apache-2.0
def _build_time(time, kwargs): """ Builds the time argument for event rules. """ tz = kwargs.pop('tz', 'UTC') if time: if kwargs: raise ValueError('Cannot pass kwargs and a time') else: return ensure_utc(time, tz) elif not kwargs: raise ValueError(...
Builds the time argument for event rules.
_build_time
python
quantopian/zipline
zipline/utils/events.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/events.py
Apache-2.0
def lossless_float_to_int(funcname, func, argname, arg): """ A preprocessor that coerces integral floats to ints. Receipt of non-integral floats raises a TypeError. """ if not isinstance(arg, float): return arg arg_as_int = int(arg) if arg == arg_as_int: warnings.warn( ...
A preprocessor that coerces integral floats to ints. Receipt of non-integral floats raises a TypeError.
lossless_float_to_int
python
quantopian/zipline
zipline/utils/events.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/events.py
Apache-2.0
def add_event(self, event, prepend=False): """ Adds an event to the manager. """ if prepend: self._events.insert(0, event) else: self._events.append(event)
Adds an event to the manager.
add_event
python
quantopian/zipline
zipline/utils/events.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/events.py
Apache-2.0
def should_trigger(self, dt): """ Composes the two rules with a lazy composer. """ return self.composer( self.first.should_trigger, self.second.should_trigger, dt )
Composes the two rules with a lazy composer.
should_trigger
python
quantopian/zipline
zipline/utils/events.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/events.py
Apache-2.0
def calculate_dates(self, dt): """ Given a date, find that day's open and period end (open + offset). """ period_start, period_close = self.cal.open_and_close_for_session( self.cal.minute_to_session_label(dt), ) # Align the market open and close times here wi...
Given a date, find that day's open and period end (open + offset).
calculate_dates
python
quantopian/zipline
zipline/utils/events.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/events.py
Apache-2.0
def calculate_dates(self, dt): """ Given a dt, find that day's close and period start (close - offset). """ period_end = self.cal.open_and_close_for_session( self.cal.minute_to_session_label(dt), )[1] # Align the market close time here with the execution time...
Given a dt, find that day's close and period start (close - offset).
calculate_dates
python
quantopian/zipline
zipline/utils/events.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/events.py
Apache-2.0
def make_eventrule(date_rule, time_rule, cal, half_days=True): """ Constructs an event rule from the factory api. """ _check_if_not_called(date_rule) _check_if_not_called(time_rule) if half_days: inner_rule = date_rule & time_rule else: inner_rule = date_rule & time_rule & N...
Constructs an event rule from the factory api.
make_eventrule
python
quantopian/zipline
zipline/utils/events.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/events.py
Apache-2.0
def create_daily_trade_source(sids, sim_params, asset_finder, trading_calendar): """ creates trade_count trades for each sid in sids list. first trade will be on sim_params.start_session, and daily thereafter for e...
creates trade_count trades for each sid in sids list. first trade will be on sim_params.start_session, and daily thereafter for each sid. Thus, two sids should result in two trades per day.
create_daily_trade_source
python
quantopian/zipline
zipline/utils/factory.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/factory.py
Apache-2.0
def bases_mro(bases): """ Yield classes in the order that methods should be looked up from the base classes of an object. """ for base in bases: for class_ in base.__mro__: yield class_
Yield classes in the order that methods should be looked up from the base classes of an object.
bases_mro
python
quantopian/zipline
zipline/utils/final.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/final.py
Apache-2.0
def is_final(name, mro): """ Checks if `name` is a `final` object in the given `mro`. We need to check the mro because we need to directly go into the __dict__ of the classes. Because `final` objects are descriptor, we need to grab them _BEFORE_ the `__call__` is invoked. """ return any(isin...
Checks if `name` is a `final` object in the given `mro`. We need to check the mro because we need to directly go into the __dict__ of the classes. Because `final` objects are descriptor, we need to grab them _BEFORE_ the `__call__` is invoked.
is_final
python
quantopian/zipline
zipline/utils/final.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/final.py
Apache-2.0
def __setattr__(self, name, value): """This stops the `final` attributes from being reassigned on the class object. """ if is_final(name, self.__mro__): raise _type_error super(FinalMeta, self).__setattr__(name, value)
This stops the `final` attributes from being reassigned on the class object.
__setattr__
python
quantopian/zipline
zipline/utils/final.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/final.py
Apache-2.0
def s(word, seq, suffix='s'): """Adds a suffix to ``word`` if some sequence has anything other than exactly one element. Parameters ---------- word : str The string to add the suffix to. seq : sequence The sequence to check the length of. suffix : str, optional. The ...
Adds a suffix to ``word`` if some sequence has anything other than exactly one element. Parameters ---------- word : str The string to add the suffix to. seq : sequence The sequence to check the length of. suffix : str, optional. The suffix to add to ``word`` Return...
s
python
quantopian/zipline
zipline/utils/formatting.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/formatting.py
Apache-2.0
def plural(singular, plural, seq): """Selects a singular or plural word based on the length of a sequence. Parameters ---------- singlular : str The string to use when ``len(seq) == 1``. plural : str The string to use when ``len(seq) != 1``. seq : sequence The sequence t...
Selects a singular or plural word based on the length of a sequence. Parameters ---------- singlular : str The string to use when ``len(seq) == 1``. plural : str The string to use when ``len(seq) != 1``. seq : sequence The sequence to check the length of. Returns --...
plural
python
quantopian/zipline
zipline/utils/formatting.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/formatting.py
Apache-2.0
def bulleted_list(items, indent=0, bullet_type='-'): """Format a bulleted list of values. Parameters ---------- items : sequence The items to make a list. indent : int, optional The number of spaces to add before each bullet. bullet_type : str, optional The bullet type t...
Format a bulleted list of values. Parameters ---------- items : sequence The items to make a list. indent : int, optional The number of spaces to add before each bullet. bullet_type : str, optional The bullet type to use. Returns ------- formatted_list : str ...
bulleted_list
python
quantopian/zipline
zipline/utils/formatting.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/formatting.py
Apache-2.0
def mapall(funcs, seq): """ Parameters ---------- funcs : iterable[function] Sequence of functions to map over `seq`. seq : iterable Sequence over which to map funcs. Yields ------ elem : object Concatenated result of mapping each ``func`` over ``seq``. Exam...
Parameters ---------- funcs : iterable[function] Sequence of functions to map over `seq`. seq : iterable Sequence over which to map funcs. Yields ------ elem : object Concatenated result of mapping each ``func`` over ``seq``. Examples -------- >>> list(...
mapall
python
quantopian/zipline
zipline/utils/functional.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/functional.py
Apache-2.0
def same(*values): """ Check if all values in a sequence are equal. Returns True on empty sequences. Examples -------- >>> same(1, 1, 1, 1) True >>> same(1, 2, 1) False >>> same() True """ if not values: return True first, rest = values[0], values[1:] ...
Check if all values in a sequence are equal. Returns True on empty sequences. Examples -------- >>> same(1, 1, 1, 1) True >>> same(1, 2, 1) False >>> same() True
same
python
quantopian/zipline
zipline/utils/functional.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/functional.py
Apache-2.0
def dzip_exact(*dicts): """ Parameters ---------- *dicts : iterable[dict] A sequence of dicts all sharing the same keys. Returns ------- zipped : dict A dict whose keys are the union of all keys in *dicts, and whose values are tuples of length len(dicts) containing t...
Parameters ---------- *dicts : iterable[dict] A sequence of dicts all sharing the same keys. Returns ------- zipped : dict A dict whose keys are the union of all keys in *dicts, and whose values are tuples of length len(dicts) containing the result of looking up ...
dzip_exact
python
quantopian/zipline
zipline/utils/functional.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/functional.py
Apache-2.0
def _gen_unzip(it, elem_len): """Helper for unzip which checks the lengths of each element in it. Parameters ---------- it : iterable[tuple] An iterable of tuples. ``unzip`` should map ensure that these are already tuples. elem_len : int or None The expected element length. I...
Helper for unzip which checks the lengths of each element in it. Parameters ---------- it : iterable[tuple] An iterable of tuples. ``unzip`` should map ensure that these are already tuples. elem_len : int or None The expected element length. If this is None it is infered from the...
_gen_unzip
python
quantopian/zipline
zipline/utils/functional.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/functional.py
Apache-2.0
def unzip(seq, elem_len=None): """Unzip a length n sequence of length m sequences into m seperate length n sequences. Parameters ---------- seq : iterable[iterable] The sequence to unzip. elem_len : int, optional The expected length of each element of ``seq``. If not provided thi...
Unzip a length n sequence of length m sequences into m seperate length n sequences. Parameters ---------- seq : iterable[iterable] The sequence to unzip. elem_len : int, optional The expected length of each element of ``seq``. If not provided this will be infered from the len...
unzip
python
quantopian/zipline
zipline/utils/functional.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/functional.py
Apache-2.0
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. ...
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 t...
getattrs
python
quantopian/zipline
zipline/utils/functional.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/functional.py
Apache-2.0
def set_attribute(name, value): """ Decorator factory for setting attributes on a function. Doesn't change the behavior of the wrapped function. Examples -------- >>> @set_attribute('__name__', 'foo') ... def bar(): ... return 3 ... >>> bar() 3 >>> bar.__name__ ...
Decorator factory for setting attributes on a function. Doesn't change the behavior of the wrapped function. Examples -------- >>> @set_attribute('__name__', 'foo') ... def bar(): ... return 3 ... >>> bar() 3 >>> bar.__name__ 'foo'
set_attribute
python
quantopian/zipline
zipline/utils/functional.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/functional.py
Apache-2.0
def foldr(f, seq, default=_no_default): """Fold a function over a sequence with right associativity. Parameters ---------- f : callable[any, any] The function to reduce the sequence with. The first argument will be the element of the sequence; the second argument will be the acc...
Fold a function over a sequence with right associativity. Parameters ---------- f : callable[any, any] The function to reduce the sequence with. The first argument will be the element of the sequence; the second argument will be the accumulator. seq : iterable[any] The s...
foldr
python
quantopian/zipline
zipline/utils/functional.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/functional.py
Apache-2.0
def invert(d): """ Invert a dictionary into a dictionary of sets. >>> invert({'a': 1, 'b': 2, 'c': 1}) # doctest: +SKIP {1: {'a', 'c'}, 2: {'b'}} """ out = {} for k, v in iteritems(d): try: out[v].add(k) except KeyError: out[v] = {k} return out
Invert a dictionary into a dictionary of sets. >>> invert({'a': 1, 'b': 2, 'c': 1}) # doctest: +SKIP {1: {'a', 'c'}, 2: {'b'}}
invert
python
quantopian/zipline
zipline/utils/functional.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/functional.py
Apache-2.0
def _qualified_name(obj): """ Return the fully-qualified name (ignoring inner classes) of a type. """ # If the obj has an explicitly-set __qualname__, use it. try: return getattr(obj, '__qualname__') except AttributeError: pass # If not, b...
Return the fully-qualified name (ignoring inner classes) of a type.
_qualified_name
python
quantopian/zipline
zipline/utils/input_validation.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/input_validation.py
Apache-2.0
def verify_indices_all_unique(obj): """ Check that all axes of a pandas object are unique. Parameters ---------- obj : pd.Series / pd.DataFrame / pd.Panel The object to validate. Returns ------- obj : pd.Series / pd.DataFrame / pd.Panel The validated object, unchanged. ...
Check that all axes of a pandas object are unique. Parameters ---------- obj : pd.Series / pd.DataFrame / pd.Panel The object to validate. Returns ------- obj : pd.Series / pd.DataFrame / pd.Panel The validated object, unchanged. Raises ------ ValueError ...
verify_indices_all_unique
python
quantopian/zipline
zipline/utils/input_validation.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/input_validation.py
Apache-2.0
def optionally(preprocessor): """Modify a preprocessor to explicitly allow `None`. Parameters ---------- preprocessor : callable[callable, str, any -> any] A preprocessor to delegate to when `arg is not None`. Returns ------- optional_preprocessor : callable[callable, str, any -> a...
Modify a preprocessor to explicitly allow `None`. Parameters ---------- preprocessor : callable[callable, str, any -> any] A preprocessor to delegate to when `arg is not None`. Returns ------- optional_preprocessor : callable[callable, str, any -> any] A preprocessor that deleg...
optionally
python
quantopian/zipline
zipline/utils/input_validation.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/input_validation.py
Apache-2.0
def ensure_dtype(func, argname, arg): """ Argument preprocessor that converts the input into a numpy dtype. Examples -------- >>> import numpy as np >>> from zipline.utils.preprocess import preprocess >>> @preprocess(dtype=ensure_dtype) ... def foo(dtype): ... return dtype ....
Argument preprocessor that converts the input into a numpy dtype. Examples -------- >>> import numpy as np >>> from zipline.utils.preprocess import preprocess >>> @preprocess(dtype=ensure_dtype) ... def foo(dtype): ... return dtype ... >>> foo(float) dtype('float64') ...
ensure_dtype
python
quantopian/zipline
zipline/utils/input_validation.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/input_validation.py
Apache-2.0
def ensure_timezone(func, argname, arg): """Argument preprocessor that converts the input into a tzinfo object. Examples -------- >>> from zipline.utils.preprocess import preprocess >>> @preprocess(tz=ensure_timezone) ... def foo(tz): ... return tz >>> foo('utc') <UTC> """ ...
Argument preprocessor that converts the input into a tzinfo object. Examples -------- >>> from zipline.utils.preprocess import preprocess >>> @preprocess(tz=ensure_timezone) ... def foo(tz): ... return tz >>> foo('utc') <UTC>
ensure_timezone
python
quantopian/zipline
zipline/utils/input_validation.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/input_validation.py
Apache-2.0
def ensure_timestamp(func, argname, arg): """Argument preprocessor that converts the input into a pandas Timestamp object. Examples -------- >>> from zipline.utils.preprocess import preprocess >>> @preprocess(ts=ensure_timestamp) ... def foo(ts): ... return ts >>> foo('2014-01-0...
Argument preprocessor that converts the input into a pandas Timestamp object. Examples -------- >>> from zipline.utils.preprocess import preprocess >>> @preprocess(ts=ensure_timestamp) ... def foo(ts): ... return ts >>> foo('2014-01-01') Timestamp('2014-01-01 00:00:00')
ensure_timestamp
python
quantopian/zipline
zipline/utils/input_validation.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/input_validation.py
Apache-2.0
def expect_dtypes(__funcname=_qualified_name, **named): """ Preprocessing decorator that verifies inputs have expected numpy dtypes. Examples -------- >>> from numpy import dtype, arange, int8, float64 >>> @expect_dtypes(x=dtype(int8)) ... def foo(x, y): ... return x, y ... >...
Preprocessing decorator that verifies inputs have expected numpy dtypes. Examples -------- >>> from numpy import dtype, arange, int8, float64 >>> @expect_dtypes(x=dtype(int8)) ... def foo(x, y): ... return x, y ... >>> foo(arange(3, dtype=int8), 'foo') (array([0, 1, 2], dtyp...
expect_dtypes
python
quantopian/zipline
zipline/utils/input_validation.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/input_validation.py
Apache-2.0
def _expect_dtype(dtypes): """ Factory for dtype-checking functions that work with the @preprocess decorator. """ def error_message(func, argname, value): # If the bad value has a dtype, but it's wrong, show the dtype # name. Otherwise just show the value...
Factory for dtype-checking functions that work with the @preprocess decorator.
_expect_dtype
python
quantopian/zipline
zipline/utils/input_validation.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/input_validation.py
Apache-2.0
def expect_kinds(**named): """ Preprocessing decorator that verifies inputs have expected dtype kinds. Examples -------- >>> from numpy import int64, int32, float32 >>> @expect_kinds(x='i') ... def foo(x): ... return x ... >>> foo(int64(2)) 2 >>> foo(int32(2)) 2 ...
Preprocessing decorator that verifies inputs have expected dtype kinds. Examples -------- >>> from numpy import int64, int32, float32 >>> @expect_kinds(x='i') ... def foo(x): ... return x ... >>> foo(int64(2)) 2 >>> foo(int32(2)) 2 >>> foo(float32(2)) # doctest:...
expect_kinds
python
quantopian/zipline
zipline/utils/input_validation.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/input_validation.py
Apache-2.0
def _expect_kind(kinds): """ Factory for kind-checking functions that work the @preprocess decorator. """ def error_message(func, argname, value): # If the bad value has a dtype, but it's wrong, show the dtype # kind. Otherwise just show the value. ...
Factory for kind-checking functions that work the @preprocess decorator.
_expect_kind
python
quantopian/zipline
zipline/utils/input_validation.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/input_validation.py
Apache-2.0
def expect_types(__funcname=_qualified_name, **named): """ Preprocessing decorator that verifies inputs have expected types. Examples -------- >>> @expect_types(x=int, y=str) ... def foo(x, y): ... return x, y ... >>> foo(2, '3') (2, '3') >>> foo(2.0, '3') # doctest: +NO...
Preprocessing decorator that verifies inputs have expected types. Examples -------- >>> @expect_types(x=int, y=str) ... def foo(x, y): ... return x, y ... >>> foo(2, '3') (2, '3') >>> foo(2.0, '3') # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS Traceback (most recent call l...
expect_types
python
quantopian/zipline
zipline/utils/input_validation.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/input_validation.py
Apache-2.0
def make_check(exc_type, template, pred, actual, funcname): """ Factory for making preprocessing functions that check a predicate on the input value. Parameters ---------- exc_type : Exception The exception type to raise if the predicate fails. template : str A template stri...
Factory for making preprocessing functions that check a predicate on the input value. Parameters ---------- exc_type : Exception The exception type to raise if the predicate fails. template : str A template string to use to create error messages. Should have %-style nam...
make_check
python
quantopian/zipline
zipline/utils/input_validation.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/input_validation.py
Apache-2.0
def expect_element(__funcname=_qualified_name, **named): """ Preprocessing decorator that verifies inputs are elements of some expected collection. Examples -------- >>> @expect_element(x=('a', 'b')) ... def foo(x): ... return x.upper() ... >>> foo('a') 'A' >>> foo('b...
Preprocessing decorator that verifies inputs are elements of some expected collection. Examples -------- >>> @expect_element(x=('a', 'b')) ... def foo(x): ... return x.upper() ... >>> foo('a') 'A' >>> foo('b') 'B' >>> foo('c') # doctest: +NORMALIZE_WHITESPACE +E...
expect_element
python
quantopian/zipline
zipline/utils/input_validation.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/input_validation.py
Apache-2.0
def expect_bounded(__funcname=_qualified_name, **named): """ Preprocessing decorator verifying that inputs fall INCLUSIVELY between bounds. Bounds should be passed as a pair of ``(min_value, max_value)``. ``None`` may be passed as ``min_value`` or ``max_value`` to signify that the input is onl...
Preprocessing decorator verifying that inputs fall INCLUSIVELY between bounds. Bounds should be passed as a pair of ``(min_value, max_value)``. ``None`` may be passed as ``min_value`` or ``max_value`` to signify that the input is only bounded above or below. Examples -------- >>> @ex...
expect_bounded
python
quantopian/zipline
zipline/utils/input_validation.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/input_validation.py
Apache-2.0
def expect_strictly_bounded(__funcname=_qualified_name, **named): """ Preprocessing decorator verifying that inputs fall EXCLUSIVELY between bounds. Bounds should be passed as a pair of ``(min_value, max_value)``. ``None`` may be passed as ``min_value`` or ``max_value`` to signify that the inp...
Preprocessing decorator verifying that inputs fall EXCLUSIVELY between bounds. Bounds should be passed as a pair of ``(min_value, max_value)``. ``None`` may be passed as ``min_value`` or ``max_value`` to signify that the input is only bounded above or below. Examples -------- >>> @ex...
expect_strictly_bounded
python
quantopian/zipline
zipline/utils/input_validation.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/input_validation.py
Apache-2.0
def expect_dimensions(__funcname=_qualified_name, **dimensions): """ Preprocessing decorator that verifies inputs are numpy arrays with a specific dimensionality. Examples -------- >>> from numpy import array >>> @expect_dimensions(x=1, y=2) ... def foo(x, y): ... return x[0] + y...
Preprocessing decorator that verifies inputs are numpy arrays with a specific dimensionality. Examples -------- >>> from numpy import array >>> @expect_dimensions(x=1, y=2) ... def foo(x, y): ... return x[0] + y[0, 0] ... >>> foo(array([1, 1]), array([[1, 1], [2, 2]])) 2...
expect_dimensions
python
quantopian/zipline
zipline/utils/input_validation.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/input_validation.py
Apache-2.0
def coerce(from_, to, **to_kwargs): """ A preprocessing decorator that coerces inputs of a given type by passing them to a callable. Parameters ---------- from : type or tuple or types Inputs types on which to call ``to``. to : function Coercion function to call on inputs. ...
A preprocessing decorator that coerces inputs of a given type by passing them to a callable. Parameters ---------- from : type or tuple or types Inputs types on which to call ``to``. to : function Coercion function to call on inputs. **to_kwargs Additional keywords ...
coerce
python
quantopian/zipline
zipline/utils/input_validation.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/input_validation.py
Apache-2.0
def coerce_types(**kwargs): """ Preprocessing decorator that applies type coercions. Parameters ---------- **kwargs : dict[str -> (type, callable)] Keyword arguments mapping function parameter names to pairs of (from_type, to_type). Examples -------- >>> @coerce_types...
Preprocessing decorator that applies type coercions. Parameters ---------- **kwargs : dict[str -> (type, callable)] Keyword arguments mapping function parameter names to pairs of (from_type, to_type). Examples -------- >>> @coerce_types(x=(float, int), y=(int, str)) ...
coerce_types
python
quantopian/zipline
zipline/utils/input_validation.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/input_validation.py
Apache-2.0
def validate_keys(dict_, expected, funcname): """Validate that a dictionary has an expected set of keys. """ expected = set(expected) received = set(dict_) missing = expected - received if missing: raise ValueError( "Missing keys in {}:\n" "Expected Keys: {}\n" ...
Validate that a dictionary has an expected set of keys.
validate_keys
python
quantopian/zipline
zipline/utils/input_validation.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/input_validation.py
Apache-2.0
def tolerant_equals(a, b, atol=10e-7, rtol=10e-7, equal_nan=False): """Check if a and b are equal with some tolerance. Parameters ---------- a, b : float The floats to check for equality. atol : float, optional The absolute tolerance. rtol : float, optional The relative ...
Check if a and b are equal with some tolerance. Parameters ---------- a, b : float The floats to check for equality. atol : float, optional The absolute tolerance. rtol : float, optional The relative tolerance. equal_nan : bool, optional Should NaN compare equal?...
tolerant_equals
python
quantopian/zipline
zipline/utils/math_utils.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/math_utils.py
Apache-2.0
def round_if_near_integer(a, epsilon=1e-4): """ Round a to the nearest integer if that integer is within an epsilon of a. """ if abs(a - round(a)) <= epsilon: return round(a) else: return a
Round a to the nearest integer if that integer is within an epsilon of a.
round_if_near_integer
python
quantopian/zipline
zipline/utils/math_utils.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/math_utils.py
Apache-2.0
def _weak_lru_cache(maxsize=100): """ Users should only access the lru_cache through its public API: cache_info, cache_clear The internals of the lru_cache are encapsulated for thread safety and to allow the implementation to change. """ def decorating_function( user_function, tu...
Users should only access the lru_cache through its public API: cache_info, cache_clear The internals of the lru_cache are encapsulated for thread safety and to allow the implementation to change.
_weak_lru_cache
python
quantopian/zipline
zipline/utils/memoize.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/memoize.py
Apache-2.0
def cache_clear(): """Clear the cache and cache statistics""" with lock: cache.clear() hits[0] = misses[0] = 0
Clear the cache and cache statistics
cache_clear
python
quantopian/zipline
zipline/utils/memoize.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/memoize.py
Apache-2.0
def weak_lru_cache(maxsize=100): """Weak least-recently-used cache decorator. If *maxsize* is set to None, the LRU features are disabled and the cache can grow without bound. Arguments to the cached function must be hashable. Any that are weak- referenceable will be stored by weak reference. Once...
Weak least-recently-used cache decorator. If *maxsize* is set to None, the LRU features are disabled and the cache can grow without bound. Arguments to the cached function must be hashable. Any that are weak- referenceable will be stored by weak reference. Once any of the args have been garbage c...
weak_lru_cache
python
quantopian/zipline
zipline/utils/memoize.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/memoize.py
Apache-2.0
def compose_types(a, *cs): """Compose multiple classes together. Parameters ---------- *mcls : tuple[type] The classes that you would like to compose Returns ------- cls : type A type that subclasses all of the types in ``mcls``. Notes ----- A common use case f...
Compose multiple classes together. Parameters ---------- *mcls : tuple[type] The classes that you would like to compose Returns ------- cls : type A type that subclasses all of the types in ``mcls``. Notes ----- A common use case for this is to build composed metac...
compose_types
python
quantopian/zipline
zipline/utils/metautils.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/metautils.py
Apache-2.0
def make_kind_check(python_types, numpy_kind): """ Make a function that checks whether a scalar or array is of a given kind (e.g. float, int, datetime, timedelta). """ def check(value): if hasattr(value, 'dtype'): return value.dtype.kind == numpy_kind return isinstance(va...
Make a function that checks whether a scalar or array is of a given kind (e.g. float, int, datetime, timedelta).
make_kind_check
python
quantopian/zipline
zipline/utils/numpy_utils.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/numpy_utils.py
Apache-2.0
def coerce_to_dtype(dtype, value): """ Make a value with the specified numpy dtype. Only datetime64[ns] and datetime64[D] are supported for datetime dtypes. """ name = dtype.name if name.startswith('datetime64'): if name == 'datetime64[D]': return make_datetime64D(value) ...
Make a value with the specified numpy dtype. Only datetime64[ns] and datetime64[D] are supported for datetime dtypes.
coerce_to_dtype
python
quantopian/zipline
zipline/utils/numpy_utils.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/numpy_utils.py
Apache-2.0
def default_missing_value_for_dtype(dtype): """ Get the default fill value for `dtype`. """ try: return _FILLVALUE_DEFAULTS[dtype] except KeyError: raise NoDefaultMissingValue( "No default value registered for dtype %s." % dtype )
Get the default fill value for `dtype`.
default_missing_value_for_dtype
python
quantopian/zipline
zipline/utils/numpy_utils.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/numpy_utils.py
Apache-2.0
def rolling_window(array, length): """ Restride an array of shape (X_0, ... X_N) into an array of shape (length, X_0 - length + 1, ... X_N) where each slice at index i along the first axis is equivalent to result[i] = array[length * i:length * (i + 1)] Parameters --...
Restride an array of shape (X_0, ... X_N) into an array of shape (length, X_0 - length + 1, ... X_N) where each slice at index i along the first axis is equivalent to result[i] = array[length * i:length * (i + 1)] Parameters ---------- array : np.ndarray Th...
rolling_window
python
quantopian/zipline
zipline/utils/numpy_utils.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/numpy_utils.py
Apache-2.0
def isnat(obj): """ Check if a value is np.NaT. """ if obj.dtype.kind not in ('m', 'M'): raise ValueError("%s is not a numpy datetime or timedelta") return obj.view(int64_dtype) == iNaT
Check if a value is np.NaT.
isnat
python
quantopian/zipline
zipline/utils/numpy_utils.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/numpy_utils.py
Apache-2.0
def is_missing(data, missing_value): """ Generic is_missing function that handles NaN and NaT. """ if is_float(data) and isnan(missing_value): return isnan(data) elif is_datetime(data) and isnat(missing_value): return isnat(data) elif is_object(data) and missing_value is None: ...
Generic is_missing function that handles NaN and NaT.
is_missing
python
quantopian/zipline
zipline/utils/numpy_utils.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/numpy_utils.py
Apache-2.0
def same(x, y): """ Check if two scalar values are "the same". Returns True if `x == y`, or if x and y are both NaN or both NaT. """ if is_float(x) and isnan(x) and is_float(y) and isnan(y): return True elif is_datetime(x) and isnat(x) and is_datetime(y) and isnat(y): return Tru...
Check if two scalar values are "the same". Returns True if `x == y`, or if x and y are both NaN or both NaT.
same
python
quantopian/zipline
zipline/utils/numpy_utils.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/numpy_utils.py
Apache-2.0
def busday_count_mask_NaT(begindates, enddates, out=None): """ Simple of numpy.busday_count that returns `float` arrays rather than int arrays, and handles `NaT`s by returning `NaN`s where the inputs were `NaT`. Doesn't support custom weekdays or calendars, but probably should in the future. S...
Simple of numpy.busday_count that returns `float` arrays rather than int arrays, and handles `NaT`s by returning `NaN`s where the inputs were `NaT`. Doesn't support custom weekdays or calendars, but probably should in the future. See Also -------- np.busday_count
busday_count_mask_NaT
python
quantopian/zipline
zipline/utils/numpy_utils.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/numpy_utils.py
Apache-2.0
def ignore_nanwarnings(): """ Helper for building a WarningContext that ignores warnings from numpy's nanfunctions. """ return WarningContext( ( ('ignore',), {'category': RuntimeWarning, 'module': 'numpy.lib.nanfunctions'}, ) )
Helper for building a WarningContext that ignores warnings from numpy's nanfunctions.
ignore_nanwarnings
python
quantopian/zipline
zipline/utils/numpy_utils.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/numpy_utils.py
Apache-2.0
def as_column(a): """ Convert an array of shape (N,) into an array of shape (N, 1). This is equivalent to `a[:, np.newaxis]`. Parameters ---------- a : np.ndarray Example ------- >>> import numpy as np >>> a = np.arange(5) >>> a array([0, 1, 2, 3, 4]) >>> as_column...
Convert an array of shape (N,) into an array of shape (N, 1). This is equivalent to `a[:, np.newaxis]`. Parameters ---------- a : np.ndarray Example ------- >>> import numpy as np >>> a = np.arange(5) >>> a array([0, 1, 2, 3, 4]) >>> as_column(a) array([[0], ...
as_column
python
quantopian/zipline
zipline/utils/numpy_utils.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/numpy_utils.py
Apache-2.0
def changed_locations(a, include_first): """ Compute indices of values in ``a`` that differ from the previous value. Parameters ---------- a : np.ndarray The array on which to indices of change. include_first : bool Whether or not to consider the first index of the array as "cha...
Compute indices of values in ``a`` that differ from the previous value. Parameters ---------- a : np.ndarray The array on which to indices of change. include_first : bool Whether or not to consider the first index of the array as "changed". Example ------- >>> import n...
changed_locations
python
quantopian/zipline
zipline/utils/numpy_utils.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/numpy_utils.py
Apache-2.0
def bytes_array_to_native_str_object_array(a): """Convert an array of dtype S to an object array containing `str`. """ if six.PY2: return a.astype(object) else: return a.astype(str).astype(object)
Convert an array of dtype S to an object array containing `str`.
bytes_array_to_native_str_object_array
python
quantopian/zipline
zipline/utils/numpy_utils.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/numpy_utils.py
Apache-2.0
def _time_to_micros(time): """Convert a time into microseconds since midnight. Parameters ---------- time : datetime.time The time to convert. Returns ------- us : int The number of microseconds since midnight. Notes ----- This does not account for leap seconds or...
Convert a time into microseconds since midnight. Parameters ---------- time : datetime.time The time to convert. Returns ------- us : int The number of microseconds since midnight. Notes ----- This does not account for leap seconds or daylight savings.
_time_to_micros
python
quantopian/zipline
zipline/utils/pandas_utils.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/pandas_utils.py
Apache-2.0
def mask_between_time(dts, start, end, include_start=True, include_end=True): """Return a mask of all of the datetimes in ``dts`` that are between ``start`` and ``end``. Parameters ---------- dts : pd.DatetimeIndex The index to mask. start : time Mask away times less than the sta...
Return a mask of all of the datetimes in ``dts`` that are between ``start`` and ``end``. Parameters ---------- dts : pd.DatetimeIndex The index to mask. start : time Mask away times less than the start. end : time Mask away times greater than the end. include_start : ...
mask_between_time
python
quantopian/zipline
zipline/utils/pandas_utils.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/pandas_utils.py
Apache-2.0
def find_in_sorted_index(dts, dt): """ Find the index of ``dt`` in ``dts``. This function should be used instead of `dts.get_loc(dt)` if the index is large enough that we don't want to initialize a hash table in ``dts``. In particular, this should always be used on minutely trading calendars. ...
Find the index of ``dt`` in ``dts``. This function should be used instead of `dts.get_loc(dt)` if the index is large enough that we don't want to initialize a hash table in ``dts``. In particular, this should always be used on minutely trading calendars. Parameters ---------- dts : pd.Dat...
find_in_sorted_index
python
quantopian/zipline
zipline/utils/pandas_utils.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/pandas_utils.py
Apache-2.0
def nearest_unequal_elements(dts, dt): """ Find values in ``dts`` closest but not equal to ``dt``. Returns a pair of (last_before, first_after). When ``dt`` is less than any element in ``dts``, ``last_before`` is None. When ``dt`` is greater any element in ``dts``, ``first_after`` is None. ``...
Find values in ``dts`` closest but not equal to ``dt``. Returns a pair of (last_before, first_after). When ``dt`` is less than any element in ``dts``, ``last_before`` is None. When ``dt`` is greater any element in ``dts``, ``first_after`` is None. ``dts`` must be unique and sorted in increasing ...
nearest_unequal_elements
python
quantopian/zipline
zipline/utils/pandas_utils.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/pandas_utils.py
Apache-2.0
def clear_dataframe_indexer_caches(df): """ Clear cached attributes from a pandas DataFrame. By default pandas memoizes indexers (`iloc`, `loc`, `ix`, etc.) objects on DataFrames, resulting in refcycles that can lead to unexpectedly long-lived DataFrames. This function attempts to clear those cycle...
Clear cached attributes from a pandas DataFrame. By default pandas memoizes indexers (`iloc`, `loc`, `ix`, etc.) objects on DataFrames, resulting in refcycles that can lead to unexpectedly long-lived DataFrames. This function attempts to clear those cycles by deleting the cached indexers from the ...
clear_dataframe_indexer_caches
python
quantopian/zipline
zipline/utils/pandas_utils.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/pandas_utils.py
Apache-2.0
def categorical_df_concat(df_list, inplace=False): """ Prepare list of pandas DataFrames to be used as input to pd.concat. Ensure any columns of type 'category' have the same categories across each dataframe. Parameters ---------- df_list : list List of dataframes with same columns....
Prepare list of pandas DataFrames to be used as input to pd.concat. Ensure any columns of type 'category' have the same categories across each dataframe. Parameters ---------- df_list : list List of dataframes with same columns. inplace : bool True if input list can be modi...
categorical_df_concat
python
quantopian/zipline
zipline/utils/pandas_utils.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/pandas_utils.py
Apache-2.0
def _sort_set_none_first(set_): """Sort a set, sorting ``None`` before other elements, if present. """ if None in set_: set_.remove(None) out = [None] out.extend(sorted(set_)) set_.add(None) return out else: return sorted(set_)
Sort a set, sorting ``None`` before other elements, if present.
_sort_set_none_first
python
quantopian/zipline
zipline/utils/pandas_utils.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/pandas_utils.py
Apache-2.0
def check_indexes_all_same(indexes, message="Indexes are not equal."): """Check that a list of Index objects are all equal. Parameters ---------- indexes : iterable[pd.Index] Iterable of indexes to check. Raises ------ ValueError If the indexes are not all the same. """...
Check that a list of Index objects are all equal. Parameters ---------- indexes : iterable[pd.Index] Iterable of indexes to check. Raises ------ ValueError If the indexes are not all the same.
check_indexes_all_same
python
quantopian/zipline
zipline/utils/pandas_utils.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/pandas_utils.py
Apache-2.0
def ensure_directory(path): """ Ensure that a directory named "path" exists. """ try: os.makedirs(path) except OSError as exc: if exc.errno == EEXIST and os.path.isdir(path): return raise
Ensure that a directory named "path" exists.
ensure_directory
python
quantopian/zipline
zipline/utils/paths.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/paths.py
Apache-2.0
def ensure_file(path): """ Ensure that a file exists. This will create any parent directories needed and create an empty file if it does not exist. Parameters ---------- path : str The file path to ensure exists. """ ensure_directory_containing(path) open(path, 'a+').close()...
Ensure that a file exists. This will create any parent directories needed and create an empty file if it does not exist. Parameters ---------- path : str The file path to ensure exists.
ensure_file
python
quantopian/zipline
zipline/utils/paths.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/paths.py
Apache-2.0
def zipline_root(environ=None): """ Get the root directory for all zipline-managed files. For testing purposes, this accepts a dictionary to interpret as the os environment. Parameters ---------- environ : dict, optional A dict to interpret as the os environment. Returns -...
Get the root directory for all zipline-managed files. For testing purposes, this accepts a dictionary to interpret as the os environment. Parameters ---------- environ : dict, optional A dict to interpret as the os environment. Returns ------- root : string Path t...
zipline_root
python
quantopian/zipline
zipline/utils/paths.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/paths.py
Apache-2.0
def get(self): """Return the result of calling the function or reraise any exceptions that were raised. """ if not self._successful: raise self._value return self._value
Return the result of calling the function or reraise any exceptions that were raised.
get
python
quantopian/zipline
zipline/utils/pool.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/pool.py
Apache-2.0
def apply_async(f, args=(), kwargs=None, callback=None): """Apply a function but emulate the API of an asynchronous call. Parameters ---------- f : callable The function to call. args : tuple, optional The positional arguments. kwargs : dict, opti...
Apply a function but emulate the API of an asynchronous call. Parameters ---------- f : callable The function to call. args : tuple, optional The positional arguments. kwargs : dict, optional The keyword arguments. Returns ---...
apply_async
python
quantopian/zipline
zipline/utils/pool.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/pool.py
Apache-2.0
def preprocess(*_unused, **processors): """ Decorator that applies pre-processors to the arguments of a function before calling the function. Parameters ---------- **processors : dict Map from argument name -> processor function. A processor function takes three arguments: (fun...
Decorator that applies pre-processors to the arguments of a function before calling the function. Parameters ---------- **processors : dict Map from argument name -> processor function. A processor function takes three arguments: (func, argname, argvalue). `func` is the t...
preprocess
python
quantopian/zipline
zipline/utils/preprocess.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/preprocess.py
Apache-2.0
def call(f): """ Wrap a function in a processor that calls `f` on the argument before passing it along. Useful for creating simple arguments to the `@preprocess` decorator. Parameters ---------- f : function Function accepting a single argument and returning a replacement. Exa...
Wrap a function in a processor that calls `f` on the argument before passing it along. Useful for creating simple arguments to the `@preprocess` decorator. Parameters ---------- f : function Function accepting a single argument and returning a replacement. Examples -------- ...
call
python
quantopian/zipline
zipline/utils/preprocess.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/preprocess.py
Apache-2.0
def _build_preprocessed_function(func, processors, args_defaults, varargs, varkw): """ Build a preprocessed function with the same signature as `func`. Uses `exec` internally ...
Build a preprocessed function with the same signature as `func`. Uses `exec` internally to build a function that actually has the same signature as `func.
_build_preprocessed_function
python
quantopian/zipline
zipline/utils/preprocess.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/preprocess.py
Apache-2.0
def __iter__(self): """ Examples -------- >>> list(range(1)) [0] >>> list(range(5)) [0, 1, 2, 3, 4] >>> list(range(1, 5)) [1, 2, 3, 4] >>> list(range(0, 5, 2)) [0, 2, 4] >>> li...
Examples -------- >>> list(range(1)) [0] >>> list(range(5)) [0, 1, 2, 3, 4] >>> list(range(1, 5)) [1, 2, 3, 4] >>> list(range(0, 5, 2)) [0, 2, 4] >>> list(range(5, 0, -1)) [5,...
__iter__
python
quantopian/zipline
zipline/utils/range.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/range.py
Apache-2.0
def __len__(self): """ Examples -------- >>> len(range(1)) 1 >>> len(range(5)) 5 >>> len(range(1, 5)) 4 >>> len(range(0, 5, 2)) 3 >>> len(range(5, 0, -1)) 5 ...
Examples -------- >>> len(range(1)) 1 >>> len(range(5)) 5 >>> len(range(1, 5)) 4 >>> len(range(0, 5, 2)) 3 >>> len(range(5, 0, -1)) 5 >>> len(range(5, 0, 1)) ...
__len__
python
quantopian/zipline
zipline/utils/range.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/range.py
Apache-2.0
def __eq__(self, other): """ Examples -------- >>> range(1) == range(1) True >>> range(0, 5, 2) == range(0, 5, 2) True >>> range(5, 0, -2) == range(5, 0, -2) True >>> range(1) == range(2) ...
Examples -------- >>> range(1) == range(1) True >>> range(0, 5, 2) == range(0, 5, 2) True >>> range(5, 0, -2) == range(5, 0, -2) True >>> range(1) == range(2) False >>> range(0, 5, 2) ==...
__eq__
python
quantopian/zipline
zipline/utils/range.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/range.py
Apache-2.0
def from_tuple(tup): """Convert a tuple into a range with error handling. Parameters ---------- tup : tuple (len 2 or 3) The tuple to turn into a range. Returns ------- range : range The range from the tuple. Raises ------ ValueError Raised when the tup...
Convert a tuple into a range with error handling. Parameters ---------- tup : tuple (len 2 or 3) The tuple to turn into a range. Returns ------- range : range The range from the tuple. Raises ------ ValueError Raised when the tuple length is not 2 or 3. ...
from_tuple
python
quantopian/zipline
zipline/utils/range.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/range.py
Apache-2.0
def maybe_from_tuple(tup_or_range): """Convert a tuple into a range but pass ranges through silently. This is useful to ensure that input is a range so that attributes may be accessed with `.start`, `.stop` or so that containment checks are constant time. Parameters ---------- tup_or_range...
Convert a tuple into a range but pass ranges through silently. This is useful to ensure that input is a range so that attributes may be accessed with `.start`, `.stop` or so that containment checks are constant time. Parameters ---------- tup_or_range : tuple or range A tuple to pass t...
maybe_from_tuple
python
quantopian/zipline
zipline/utils/range.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/range.py
Apache-2.0
def _check_steps(a, b): """Check that the steps of ``a`` and ``b`` are both 1. Parameters ---------- a : range The first range to check. b : range The second range to check. Raises ------ ValueError Raised when either step is not 1. """ if a.step != 1: ...
Check that the steps of ``a`` and ``b`` are both 1. Parameters ---------- a : range The first range to check. b : range The second range to check. Raises ------ ValueError Raised when either step is not 1.
_check_steps
python
quantopian/zipline
zipline/utils/range.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/range.py
Apache-2.0
def overlap(a, b): """Check if two ranges overlap. Parameters ---------- a : range The first range. b : range The second range. Returns ------- overlaps : bool Do these ranges overlap. Notes ----- This function does not support ranges with step != ...
Check if two ranges overlap. Parameters ---------- a : range The first range. b : range The second range. Returns ------- overlaps : bool Do these ranges overlap. Notes ----- This function does not support ranges with step != 1.
overlap
python
quantopian/zipline
zipline/utils/range.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/range.py
Apache-2.0
def merge(a, b): """Merge two ranges with step == 1. Parameters ---------- a : range The first range. b : range The second range. """ _check_steps(a, b) return range(min(a.start, b.start), max(a.stop, b.stop))
Merge two ranges with step == 1. Parameters ---------- a : range The first range. b : range The second range.
merge
python
quantopian/zipline
zipline/utils/range.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/range.py
Apache-2.0
def intersecting_ranges(ranges): """Return any ranges that intersect. Parameters ---------- ranges : iterable[ranges] A sequence of ranges to check for intersections. Returns ------- intersections : iterable[ranges] A sequence of all of the ranges that intersected in ``rang...
Return any ranges that intersect. Parameters ---------- ranges : iterable[ranges] A sequence of ranges to check for intersections. Returns ------- intersections : iterable[ranges] A sequence of all of the ranges that intersected in ``ranges``. Examples -------- >>>...
intersecting_ranges
python
quantopian/zipline
zipline/utils/range.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/range.py
Apache-2.0
def _run(handle_data, initialize, before_trading_start, analyze, algofile, algotext, defines, data_frequency, capital_base, bundle, bundle_timestamp, start, end, output, trading_calendar, ...
Run a backtest for the given algorithm. This is shared between the cli and :func:`zipline.run_algo`.
_run
python
quantopian/zipline
zipline/utils/run_algo.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/run_algo.py
Apache-2.0
def load_extensions(default, extensions, strict, environ, reload=False): """Load all of the given extensions. This should be called by run_algo or the cli. Parameters ---------- default : bool Load the default exension (~/.zipline/extension.py)? extension : iterable[str] The pat...
Load all of the given extensions. This should be called by run_algo or the cli. Parameters ---------- default : bool Load the default exension (~/.zipline/extension.py)? extension : iterable[str] The paths to the extensions to load. If the path ends in ``.py`` it is treated ...
load_extensions
python
quantopian/zipline
zipline/utils/run_algo.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/run_algo.py
Apache-2.0
def run_algorithm(start, end, initialize, capital_base, handle_data=None, before_trading_start=None, analyze=None, data_frequency='daily', bundle='quantopian-quandl', ...
Run a trading algorithm. Parameters ---------- start : datetime The start date of the backtest. end : datetime The end date of the backtest.. initialize : callable[context -> None] The initialize function to use for the algorithm. This is called once at the very...
run_algorithm
python
quantopian/zipline
zipline/utils/run_algo.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/run_algo.py
Apache-2.0
def resolve(self, asset_finder, start_date, end_date): """ Resolve inputs into values to be passed to TradingAlgorithm. Returns a pair of ``(benchmark_sid, benchmark_returns)`` with at most one non-None value. Both values may be None if no benchmark source has been configured. ...
Resolve inputs into values to be passed to TradingAlgorithm. Returns a pair of ``(benchmark_sid, benchmark_returns)`` with at most one non-None value. Both values may be None if no benchmark source has been configured. Parameters ---------- asset_finder : zipli...
resolve
python
quantopian/zipline
zipline/utils/run_algo.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/run_algo.py
Apache-2.0
def __init__(self, data, current_date_func, asset_finder): """ data: a nested dictionary: knowledge_date -> lookup_date -> {add: [symbol list], 'delete': []}, delete: [symbol list]} current_date_func: function taking no parameters, returning current datetime...
data: a nested dictionary: knowledge_date -> lookup_date -> {add: [symbol list], 'delete': []}, delete: [symbol list]} current_date_func: function taking no parameters, returning current datetime
__init__
python
quantopian/zipline
zipline/utils/security_list.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/security_list.py
Apache-2.0
def load_from_directory(list_name): """ To resolve the symbol in the LEVERAGED_ETF list, the date on which the symbol was in effect is needed. Furthermore, to maintain a point in time record of our own maintenance of the restricted list, we need a knowledge date. Thus, restricted lists are dict...
To resolve the symbol in the LEVERAGED_ETF list, the date on which the symbol was in effect is needed. Furthermore, to maintain a point in time record of our own maintenance of the restricted list, we need a knowledge date. Thus, restricted lists are dictionaries of datetime->symbol lists. new...
load_from_directory
python
quantopian/zipline
zipline/utils/security_list.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/security_list.py
Apache-2.0
def format_docstring(owner_name, docstring, formatters): """ Template ``formatters`` into ``docstring``. Parameters ---------- owner_name : str The name of the function or class whose docstring is being templated. Only used for error messages. docstring : str The docstri...
Template ``formatters`` into ``docstring``. Parameters ---------- owner_name : str The name of the function or class whose docstring is being templated. Only used for error messages. docstring : str The docstring to template. formatters : dict[str -> str] Parame...
format_docstring
python
quantopian/zipline
zipline/utils/sharedoc.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/sharedoc.py
Apache-2.0
def templated_docstring(**docs): """ Decorator allowing the use of templated docstrings. Examples -------- >>> @templated_docstring(foo='bar') ... def my_func(self, foo): ... '''{foo}''' ... >>> my_func.__doc__ 'bar' """ def decorator(f): f.__doc__ = format_d...
Decorator allowing the use of templated docstrings. Examples -------- >>> @templated_docstring(foo='bar') ... def my_func(self, foo): ... '''{foo}''' ... >>> my_func.__doc__ 'bar'
templated_docstring
python
quantopian/zipline
zipline/utils/sharedoc.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/sharedoc.py
Apache-2.0
def _init_config_schema(self): """ Initializes `config_schema.json` in the user's data dir whenever the server extension starts. Users may add custom fields to their config schema to insert new keys into the Jupyter AI config. New in v2.31.1: Jupyter AI now merges the user's exi...
Initializes `config_schema.json` in the user's data dir whenever the server extension starts. Users may add custom fields to their config schema to insert new keys into the Jupyter AI config. New in v2.31.1: Jupyter AI now merges the user's existing config schema with Jupyter A...
_init_config_schema
python
jupyterlab/jupyter-ai
packages/jupyter-ai/jupyter_ai/config_manager.py
https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/config_manager.py
BSD-3-Clause
def _read_config(self) -> GlobalConfig: """Returns the user's current configuration as a GlobalConfig object. This should never be sent to the client as it includes API keys. Prefer self.get_config() for sending the config to the client.""" if self._config and self._last_read: ...
Returns the user's current configuration as a GlobalConfig object. This should never be sent to the client as it includes API keys. Prefer self.get_config() for sending the config to the client.
_read_config
python
jupyterlab/jupyter-ai
packages/jupyter-ai/jupyter_ai/config_manager.py
https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/config_manager.py
BSD-3-Clause
def _validate_config(self, config: GlobalConfig): """Method used to validate the configuration. This is called after every read and before every write to the config file. Guarantees that the config file conforms to the JSON Schema, and that the language and embedding models have authn cr...
Method used to validate the configuration. This is called after every read and before every write to the config file. Guarantees that the config file conforms to the JSON Schema, and that the language and embedding models have authn credentials if specified.
_validate_config
python
jupyterlab/jupyter-ai
packages/jupyter-ai/jupyter_ai/config_manager.py
https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/config_manager.py
BSD-3-Clause
def _validate_model(self, model_id: str, raise_exc=True): """ Validates a model against the set of allow/blocklists specified by the traitlets configuration, returning `True` if the model is allowed, and raising a `BlockedModelError` otherwise. If `raise_exc=False`, this function...
Validates a model against the set of allow/blocklists specified by the traitlets configuration, returning `True` if the model is allowed, and raising a `BlockedModelError` otherwise. If `raise_exc=False`, this function returns `False` if the model is not allowed.
_validate_model
python
jupyterlab/jupyter-ai
packages/jupyter-ai/jupyter_ai/config_manager.py
https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/config_manager.py
BSD-3-Clause
def _write_config(self, new_config: GlobalConfig): """Updates configuration and persists it to disk. This accepts a complete `GlobalConfig` object, and should not be called publicly.""" # remove any empty field dictionaries new_config.fields = {k: v for k, v in new_config.fields.items() ...
Updates configuration and persists it to disk. This accepts a complete `GlobalConfig` object, and should not be called publicly.
_write_config
python
jupyterlab/jupyter-ai
packages/jupyter-ai/jupyter_ai/config_manager.py
https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/config_manager.py
BSD-3-Clause
def persona(self) -> Persona: """ The current agent persona, set by the selected LM provider. If the selected LM provider is `None`, this property returns `JupyternautPersona` by default. """ lm_provider = self.lm_provider persona = getattr(lm_provider, "persona",...
The current agent persona, set by the selected LM provider. If the selected LM provider is `None`, this property returns `JupyternautPersona` by default.
persona
python
jupyterlab/jupyter-ai
packages/jupyter-ai/jupyter_ai/config_manager.py
https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/config_manager.py
BSD-3-Clause