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 _assert_valid_categorical_missing_value(value):
"""
Check that value is a valid categorical missing_value.
Raises a TypeError if the value is cannot be used as the missing_value for
a categorical_dtype Term.
"""
label_types = LabelArray.SUPPORTED_SCALAR_TYPES
if not isinstance(value, la... |
Check that value is a valid categorical missing_value.
Raises a TypeError if the value is cannot be used as the missing_value for
a categorical_dtype Term.
| _assert_valid_categorical_missing_value | python | quantopian/zipline | zipline/pipeline/term.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/term.py | Apache-2.0 |
def roots(g):
"Get nodes from graph G with indegree 0"
return set(n for n, d in iteritems(g.in_degree()) if d == 0) | Get nodes from graph G with indegree 0 | roots | python | quantopian/zipline | zipline/pipeline/visualize.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/visualize.py | Apache-2.0 |
def _render(g, out, format_, include_asset_exists=False):
"""
Draw `g` as a graph to `out`, in format `format`.
Parameters
----------
g : zipline.pipeline.graph.TermGraph
Graph to render.
out : file-like object
format_ : str {'png', 'svg'}
Output format.
include_asset_ex... |
Draw `g` as a graph to `out`, in format `format`.
Parameters
----------
g : zipline.pipeline.graph.TermGraph
Graph to render.
out : file-like object
format_ : str {'png', 'svg'}
Output format.
include_asset_exists : bool
Whether to filter out `AssetExists()` nodes.
... | _render | python | quantopian/zipline | zipline/pipeline/visualize.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/visualize.py | Apache-2.0 |
def display_graph(g, format='svg', include_asset_exists=False):
"""
Display a TermGraph interactively from within IPython.
"""
try:
import IPython.display as display
except ImportError:
raise NoIPython("IPython is not installed. Can't display graph.")
if format == 'svg':
... |
Display a TermGraph interactively from within IPython.
| display_graph | python | quantopian/zipline | zipline/pipeline/visualize.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/visualize.py | Apache-2.0 |
def format_attrs(attrs):
"""
Format key, value pairs from attrs into graphviz attrs format
Examples
--------
>>> format_attrs({'key1': 'value1', 'key2': 'value2'}) # doctest: +SKIP
'[key1=value1, key2=value2]'
"""
if not attrs:
return ''
entries = ['='.join((key, value)) fo... |
Format key, value pairs from attrs into graphviz attrs format
Examples
--------
>>> format_attrs({'key1': 'value1', 'key2': 'value2'}) # doctest: +SKIP
'[key1=value1, key2=value2]'
| format_attrs | python | quantopian/zipline | zipline/pipeline/visualize.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/visualize.py | Apache-2.0 |
def eq(self, other):
"""
Construct a Filter returning True for asset/date pairs where the output
of ``self`` matches ``other``.
"""
# We treat this as an error because missing_values have NaN semantics,
# which means this would return an array of all False, which is almos... |
Construct a Filter returning True for asset/date pairs where the output
of ``self`` matches ``other``.
| eq | python | quantopian/zipline | zipline/pipeline/classifiers/classifier.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/classifiers/classifier.py | Apache-2.0 |
def __ne__(self, other):
"""
Construct a Filter returning True for asset/date pairs where the output
of ``self`` matches ``other.
"""
if isinstance(other, Number) != (self.dtype == int64_dtype):
raise InvalidClassifierComparison(self, other)
if isinstance(oth... |
Construct a Filter returning True for asset/date pairs where the output
of ``self`` matches ``other.
| __ne__ | python | quantopian/zipline | zipline/pipeline/classifiers/classifier.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/classifiers/classifier.py | Apache-2.0 |
def startswith(self, prefix):
"""
Construct a Filter matching values starting with ``prefix``.
Parameters
----------
prefix : str
String prefix against which to compare values produced by ``self``.
Returns
-------
matches : Filter
... |
Construct a Filter matching values starting with ``prefix``.
Parameters
----------
prefix : str
String prefix against which to compare values produced by ``self``.
Returns
-------
matches : Filter
Filter returning True for all sid/date p... | startswith | python | quantopian/zipline | zipline/pipeline/classifiers/classifier.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/classifiers/classifier.py | Apache-2.0 |
def endswith(self, suffix):
"""
Construct a Filter matching values ending with ``suffix``.
Parameters
----------
suffix : str
String suffix against which to compare values produced by ``self``.
Returns
-------
matches : Filter
Fil... |
Construct a Filter matching values ending with ``suffix``.
Parameters
----------
suffix : str
String suffix against which to compare values produced by ``self``.
Returns
-------
matches : Filter
Filter returning True for all sid/date pai... | endswith | python | quantopian/zipline | zipline/pipeline/classifiers/classifier.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/classifiers/classifier.py | Apache-2.0 |
def has_substring(self, substring):
"""
Construct a Filter matching values containing ``substring``.
Parameters
----------
substring : str
Sub-string against which to compare values produced by ``self``.
Returns
-------
matches : Filter
... |
Construct a Filter matching values containing ``substring``.
Parameters
----------
substring : str
Sub-string against which to compare values produced by ``self``.
Returns
-------
matches : Filter
Filter returning True for all sid/date p... | has_substring | python | quantopian/zipline | zipline/pipeline/classifiers/classifier.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/classifiers/classifier.py | Apache-2.0 |
def matches(self, pattern):
"""
Construct a Filter that checks regex matches against ``pattern``.
Parameters
----------
pattern : str
Regex pattern against which to compare values produced by ``self``.
Returns
-------
matches : Filter
... |
Construct a Filter that checks regex matches against ``pattern``.
Parameters
----------
pattern : str
Regex pattern against which to compare values produced by ``self``.
Returns
-------
matches : Filter
Filter returning True for all sid/... | matches | python | quantopian/zipline | zipline/pipeline/classifiers/classifier.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/classifiers/classifier.py | Apache-2.0 |
def element_of(self, choices):
"""
Construct a Filter indicating whether values are in ``choices``.
Parameters
----------
choices : iterable[str or int]
An iterable of choices.
Returns
-------
matches : Filter
Filter returning Tru... |
Construct a Filter indicating whether values are in ``choices``.
Parameters
----------
choices : iterable[str or int]
An iterable of choices.
Returns
-------
matches : Filter
Filter returning True for all sid/date pairs for which ``self`... | element_of | python | quantopian/zipline | zipline/pipeline/classifiers/classifier.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/classifiers/classifier.py | Apache-2.0 |
def to_workspace_value(self, result, assets):
"""
Called with the result of a pipeline. This needs to return an object
which can be put into the workspace to continue doing computations.
This is the inverse of :func:`~zipline.pipeline.term.Term.postprocess`.
"""
if self.... |
Called with the result of a pipeline. This needs to return an object
which can be put into the workspace to continue doing computations.
This is the inverse of :func:`~zipline.pipeline.term.Term.postprocess`.
| to_workspace_value | python | quantopian/zipline | zipline/pipeline/classifiers/classifier.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/classifiers/classifier.py | Apache-2.0 |
def _to_integral(self, output_array):
"""
Convert an array produced by this classifier into an array of integer
labels and a missing value label.
"""
if self.dtype == int64_dtype:
group_labels = output_array
null_label = self.missing_value
elif sel... |
Convert an array produced by this classifier into an array of integer
labels and a missing value label.
| _to_integral | python | quantopian/zipline | zipline/pipeline/classifiers/classifier.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/classifiers/classifier.py | Apache-2.0 |
def peer_count(self, mask=NotSpecified):
"""
Construct a factor that gives the number of occurrences of
each distinct category in a classifier.
Parameters
----------
mask : zipline.pipeline.Filter, optional
If passed, only count assets passing the filter. De... |
Construct a factor that gives the number of occurrences of
each distinct category in a classifier.
Parameters
----------
mask : zipline.pipeline.Filter, optional
If passed, only count assets passing the filter. Default behavior
is to count all assets.
... | peer_count | python | quantopian/zipline | zipline/pipeline/classifiers/classifier.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/classifiers/classifier.py | Apache-2.0 |
def _allocate_output(self, windows, shape):
"""
Override the default array allocation to produce a LabelArray when we
have a string-like dtype.
"""
if self.dtype == int64_dtype:
return super(CustomClassifier, self)._allocate_output(
windows,
... |
Override the default array allocation to produce a LabelArray when we
have a string-like dtype.
| _allocate_output | python | quantopian/zipline | zipline/pipeline/classifiers/classifier.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/classifiers/classifier.py | Apache-2.0 |
def bind(self, name):
"""
Bind a `Column` object to its name.
"""
return _BoundColumnDescr(
dtype=self.dtype,
missing_value=self.missing_value,
name=name,
doc=self.doc,
metadata=self.metadata,
currency_aware=self.cur... |
Bind a `Column` object to its name.
| bind | python | quantopian/zipline | zipline/pipeline/data/dataset.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/data/dataset.py | Apache-2.0 |
def __get__(self, instance, owner):
"""
Produce a concrete BoundColumn object when accessed.
We don't bind to datasets at class creation time so that subclasses of
DataSets produce different BoundColumns.
"""
return BoundColumn(
dtype=self.dtype,
... |
Produce a concrete BoundColumn object when accessed.
We don't bind to datasets at class creation time so that subclasses of
DataSets produce different BoundColumns.
| __get__ | python | quantopian/zipline | zipline/pipeline/data/dataset.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/data/dataset.py | Apache-2.0 |
def fx(self, currency):
"""
Construct a currency-converted version of this column.
Parameters
----------
currency : str or zipline.currency.Currency
Currency into which to convert this column's data.
Returns
-------
column : BoundColumn
... |
Construct a currency-converted version of this column.
Parameters
----------
currency : str or zipline.currency.Currency
Currency into which to convert this column's data.
Returns
-------
column : BoundColumn
Column producing the same da... | fx | python | quantopian/zipline | zipline/pipeline/data/dataset.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/data/dataset.py | Apache-2.0 |
def qualname(self):
"""The fully-qualified name of this column.
"""
out = '.'.join([self.dataset.qualname, self.name])
conversion = self._currency_conversion
if conversion is not None:
out += '.fx({!r})'.format(conversion.currency.code)
return out | The fully-qualified name of this column.
| qualname | python | quantopian/zipline | zipline/pipeline/data/dataset.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/data/dataset.py | Apache-2.0 |
def specialize(self, domain):
"""
Specialize a generic DataSet to a concrete domain.
Parameters
----------
domain : zipline.pipeline.domain.Domain
Domain to which we should generate a specialization.
Returns
-------
specialized : type
... |
Specialize a generic DataSet to a concrete domain.
Parameters
----------
domain : zipline.pipeline.domain.Domain
Domain to which we should generate a specialization.
Returns
-------
specialized : type
A new :class:`~zipline.pipeline.data... | specialize | python | quantopian/zipline | zipline/pipeline/data/dataset.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/data/dataset.py | Apache-2.0 |
def get_column(cls, name):
"""Look up a column by name.
Parameters
----------
name : str
Name of the column to look up.
Returns
-------
column : zipline.pipeline.data.BoundColumn
Column with the given name.
Raises
------
... | Look up a column by name.
Parameters
----------
name : str
Name of the column to look up.
Returns
-------
column : zipline.pipeline.data.BoundColumn
Column with the given name.
Raises
------
AttributeError
If ... | get_column | python | quantopian/zipline | zipline/pipeline/data/dataset.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/data/dataset.py | Apache-2.0 |
def _make_dataset(cls, coords):
"""Construct a new dataset given the coordinates.
"""
class Slice(cls._SliceType):
extra_coords = coords
Slice.__name__ = '%s.slice(%s)' % (
cls.__name__,
', '.join('%s=%r' % item for item in coords.items()),
)
... | Construct a new dataset given the coordinates.
| _make_dataset | python | quantopian/zipline | zipline/pipeline/data/dataset.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/data/dataset.py | Apache-2.0 |
def slice(cls, *args, **kwargs):
"""Take a slice of a DataSetFamily to produce a dataset
indexed by asset and date.
Parameters
----------
*args
**kwargs
The coordinates to fix along each extra dimension.
Returns
-------
dataset : Data... | Take a slice of a DataSetFamily to produce a dataset
indexed by asset and date.
Parameters
----------
*args
**kwargs
The coordinates to fix along each extra dimension.
Returns
-------
dataset : DataSet
A regular pipeline dataset i... | slice | python | quantopian/zipline | zipline/pipeline/data/dataset.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/data/dataset.py | Apache-2.0 |
def from_span(cls, inputs, window_length, span, **kwargs):
"""
Convenience constructor for passing `decay_rate` in terms of `span`.
Forwards `decay_rate` as `1 - (2.0 / (1 + span))`. This provides the
behavior equivalent to passing `span` to pandas.ewma.
Examples
-----... |
Convenience constructor for passing `decay_rate` in terms of `span`.
Forwards `decay_rate` as `1 - (2.0 / (1 + span))`. This provides the
behavior equivalent to passing `span` to pandas.ewma.
Examples
--------
.. code-block:: python
# Equivalent to:
... | from_span | python | quantopian/zipline | zipline/pipeline/factors/basic.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/factors/basic.py | Apache-2.0 |
def from_halflife(cls, inputs, window_length, halflife, **kwargs):
"""
Convenience constructor for passing ``decay_rate`` in terms of half
life.
Forwards ``decay_rate`` as ``exp(log(.5) / halflife)``. This provides
the behavior equivalent to passing `halflife` to pandas.ewma.
... |
Convenience constructor for passing ``decay_rate`` in terms of half
life.
Forwards ``decay_rate`` as ``exp(log(.5) / halflife)``. This provides
the behavior equivalent to passing `halflife` to pandas.ewma.
Examples
--------
.. code-block:: python
... | from_halflife | python | quantopian/zipline | zipline/pipeline/factors/basic.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/factors/basic.py | Apache-2.0 |
def from_center_of_mass(cls,
inputs,
window_length,
center_of_mass,
**kwargs):
"""
Convenience constructor for passing `decay_rate` in terms of center of
mass.
Forwards `decay... |
Convenience constructor for passing `decay_rate` in terms of center of
mass.
Forwards `decay_rate` as `1 - (1 / 1 + center_of_mass)`. This provides
behavior equivalent to passing `center_of_mass` to pandas.ewma.
Examples
--------
.. code-block:: python
... | from_center_of_mass | python | quantopian/zipline | zipline/pipeline/factors/basic.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/factors/basic.py | Apache-2.0 |
def coerce_numbers_to_my_dtype(f):
"""
A decorator for methods whose signature is f(self, other) that coerces
``other`` to ``self.dtype``.
This is used to make comparison operations between numbers and `Factor`
instances work independently of whether the user supplies a float or
integer literal... |
A decorator for methods whose signature is f(self, other) that coerces
``other`` to ``self.dtype``.
This is used to make comparison operations between numbers and `Factor`
instances work independently of whether the user supplies a float or
integer literal.
For example, if I write::
... | coerce_numbers_to_my_dtype | python | quantopian/zipline | zipline/pipeline/factors/factor.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/factors/factor.py | Apache-2.0 |
def binop_return_dtype(op, left, right):
"""
Compute the expected return dtype for the given binary operator.
Parameters
----------
op : str
Operator symbol, (e.g. '+', '-', ...).
left : numpy.dtype
Dtype of left hand side.
right : numpy.dtype
Dtype of right hand sid... |
Compute the expected return dtype for the given binary operator.
Parameters
----------
op : str
Operator symbol, (e.g. '+', '-', ...).
left : numpy.dtype
Dtype of left hand side.
right : numpy.dtype
Dtype of right hand side.
Returns
-------
outdtype : numpy... | binop_return_dtype | python | quantopian/zipline | zipline/pipeline/factors/factor.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/factors/factor.py | Apache-2.0 |
def binary_operator(op):
"""
Factory function for making binary operator methods on a Factor subclass.
Returns a function, "binary_operator" suitable for implementing functions
like __add__.
"""
# When combining a Factor with a NumericalExpression, we use this
# attrgetter instance to defer... |
Factory function for making binary operator methods on a Factor subclass.
Returns a function, "binary_operator" suitable for implementing functions
like __add__.
| binary_operator | python | quantopian/zipline | zipline/pipeline/factors/factor.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/factors/factor.py | Apache-2.0 |
def reflected_binary_operator(op):
"""
Factory function for making binary operator methods on a Factor.
Returns a function, "reflected_binary_operator" suitable for implementing
functions like __radd__.
"""
assert not is_comparison(op)
@with_name(method_name_for_op(op, commute=True))
@... |
Factory function for making binary operator methods on a Factor.
Returns a function, "reflected_binary_operator" suitable for implementing
functions like __radd__.
| reflected_binary_operator | python | quantopian/zipline | zipline/pipeline/factors/factor.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/factors/factor.py | Apache-2.0 |
def unary_operator(op):
"""
Factory function for making unary operator methods for Factors.
"""
# Only negate is currently supported.
valid_ops = {'-'}
if op not in valid_ops:
raise ValueError("Invalid unary operator %s." % op)
@with_doc("Unary Operator: '%s'" % op)
@with_name(u... |
Factory function for making unary operator methods for Factors.
| unary_operator | python | quantopian/zipline | zipline/pipeline/factors/factor.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/factors/factor.py | Apache-2.0 |
def function_application(func):
"""
Factory function for producing function application methods for Factor
subclasses.
"""
if func not in NUMEXPR_MATH_FUNCS:
raise ValueError("Unsupported mathematical function '%s'" % func)
docstring = dedent(
"""\
Construct a Factor tha... |
Factory function for producing function application methods for Factor
subclasses.
| function_application | python | quantopian/zipline | zipline/pipeline/factors/factor.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/factors/factor.py | Apache-2.0 |
def f(self, mask=NotSpecified):
"""Create a 1-dimensional factor computing the {} of self, each day.
Parameters
----------
mask : zipline.pipeline.Filter, optional
A Filter representing assets to consider when computing results.
If supplied, we ignore asset/date pa... | Create a 1-dimensional factor computing the {} of self, each day.
Parameters
----------
mask : zipline.pipeline.Filter, optional
A Filter representing assets to consider when computing results.
If supplied, we ignore asset/date pairs where ``mask`` produces
``Fa... | f | python | quantopian/zipline | zipline/pipeline/factors/factor.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/factors/factor.py | Apache-2.0 |
def demean(self, mask=NotSpecified, groupby=NotSpecified):
"""
Construct a Factor that computes ``self`` and subtracts the mean from
row of the result.
If ``mask`` is supplied, ignore values where ``mask`` returns False
when computing row means, and output NaN anywhere the mask ... |
Construct a Factor that computes ``self`` and subtracts the mean from
row of the result.
If ``mask`` is supplied, ignore values where ``mask`` returns False
when computing row means, and output NaN anywhere the mask is False.
If ``groupby`` is supplied, compute by partitioning... | demean | python | quantopian/zipline | zipline/pipeline/factors/factor.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/factors/factor.py | Apache-2.0 |
def zscore(self, mask=NotSpecified, groupby=NotSpecified):
"""
Construct a Factor that Z-Scores each day's results.
The Z-Score of a row is defined as::
(row - row.mean()) / row.stddev()
If ``mask`` is supplied, ignore values where ``mask`` returns False
when compu... |
Construct a Factor that Z-Scores each day's results.
The Z-Score of a row is defined as::
(row - row.mean()) / row.stddev()
If ``mask`` is supplied, ignore values where ``mask`` returns False
when computing row means and standard deviations, and output NaN
anywher... | zscore | python | quantopian/zipline | zipline/pipeline/factors/factor.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/factors/factor.py | Apache-2.0 |
def rank(self,
method='ordinal',
ascending=True,
mask=NotSpecified,
groupby=NotSpecified):
"""
Construct a new Factor representing the sorted rank of each column
within each row.
Parameters
----------
method : str, {'or... |
Construct a new Factor representing the sorted rank of each column
within each row.
Parameters
----------
method : str, {'ordinal', 'min', 'max', 'dense', 'average'}
The method used to assign ranks to tied elements. See
`scipy.stats.rankdata` for a full ... | rank | python | quantopian/zipline | zipline/pipeline/factors/factor.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/factors/factor.py | Apache-2.0 |
def pearsonr(self, target, correlation_length, mask=NotSpecified):
"""
Construct a new Factor that computes rolling pearson correlation
coefficients between ``target`` and the columns of ``self``.
Parameters
----------
target : zipline.pipeline.Term
The term ... |
Construct a new Factor that computes rolling pearson correlation
coefficients between ``target`` and the columns of ``self``.
Parameters
----------
target : zipline.pipeline.Term
The term used to compute correlations against each column of data
produced ... | pearsonr | python | quantopian/zipline | zipline/pipeline/factors/factor.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/factors/factor.py | Apache-2.0 |
def spearmanr(self, target, correlation_length, mask=NotSpecified):
"""
Construct a new Factor that computes rolling spearman rank correlation
coefficients between ``target`` and the columns of ``self``.
Parameters
----------
target : zipline.pipeline.Term
Th... |
Construct a new Factor that computes rolling spearman rank correlation
coefficients between ``target`` and the columns of ``self``.
Parameters
----------
target : zipline.pipeline.Term
The term used to compute correlations against each column of data
pro... | spearmanr | python | quantopian/zipline | zipline/pipeline/factors/factor.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/factors/factor.py | Apache-2.0 |
def linear_regression(self, target, regression_length, mask=NotSpecified):
"""
Construct a new Factor that performs an ordinary least-squares
regression predicting the columns of `self` from `target`.
Parameters
----------
target : zipline.pipeline.Term
The t... |
Construct a new Factor that performs an ordinary least-squares
regression predicting the columns of `self` from `target`.
Parameters
----------
target : zipline.pipeline.Term
The term to use as the predictor/independent variable in each
regression. This ... | linear_regression | python | quantopian/zipline | zipline/pipeline/factors/factor.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/factors/factor.py | Apache-2.0 |
def top(self, N, mask=NotSpecified, groupby=NotSpecified):
"""
Construct a Filter matching the top N asset values of self each day.
If ``groupby`` is supplied, returns a Filter matching the top N asset
values for each group.
Parameters
----------
N : int
... |
Construct a Filter matching the top N asset values of self each day.
If ``groupby`` is supplied, returns a Filter matching the top N asset
values for each group.
Parameters
----------
N : int
Number of assets passing the returned filter each day.
ma... | top | python | quantopian/zipline | zipline/pipeline/factors/factor.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/factors/factor.py | Apache-2.0 |
def percentile_between(self,
min_percentile,
max_percentile,
mask=NotSpecified):
"""
Construct a Filter matching values of self that fall within the range
defined by ``min_percentile`` and ``max_percentile``.
... |
Construct a Filter matching values of self that fall within the range
defined by ``min_percentile`` and ``max_percentile``.
Parameters
----------
min_percentile : float [0.0, 100.0]
Return True for assets falling above this percentile in the data.
max_percen... | percentile_between | python | quantopian/zipline | zipline/pipeline/factors/factor.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/factors/factor.py | Apache-2.0 |
def _validate(self):
"""
Verify that the stored rank method is valid.
"""
if self._method not in _RANK_METHODS:
raise UnknownRankMethod(
method=self._method,
choices=set(_RANK_METHODS),
)
return super(Rank, self)._validate() |
Verify that the stored rank method is valid.
| _validate | python | quantopian/zipline | zipline/pipeline/factors/factor.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/factors/factor.py | Apache-2.0 |
def _compute(self, arrays, dates, assets, mask):
"""
For each row in the input, compute a like-shaped array of per-row
ranks.
"""
return masked_rankdata_2d(
arrays[0],
mask,
self.inputs[0].missing_value,
self._method,
se... |
For each row in the input, compute a like-shaped array of per-row
ranks.
| _compute | python | quantopian/zipline | zipline/pipeline/factors/factor.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/factors/factor.py | Apache-2.0 |
def winsorize(row, min_percentile, max_percentile):
"""
This implementation is based on scipy.stats.mstats.winsorize
"""
a = row.copy()
nan_count = isnan(row).sum()
nonnan_count = a.size - nan_count
# NOTE: argsort() sorts nans to the end of the array.
idx = a.argsort()
# Set value... |
This implementation is based on scipy.stats.mstats.winsorize
| winsorize | python | quantopian/zipline | zipline/pipeline/factors/factor.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/factors/factor.py | Apache-2.0 |
def vectorized_beta(dependents, independent, allowed_missing, out=None):
"""
Compute slopes of linear regressions between columns of ``dependents`` and
``independent``.
Parameters
----------
dependents : np.array[N, M]
Array with columns of data to be regressed against ``independent``.
... |
Compute slopes of linear regressions between columns of ``dependents`` and
``independent``.
Parameters
----------
dependents : np.array[N, M]
Array with columns of data to be regressed against ``independent``.
independent : np.array[N, 1]
Independent variable of the regression
... | vectorized_beta | python | quantopian/zipline | zipline/pipeline/factors/statistical.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/factors/statistical.py | Apache-2.0 |
def vectorized_pearson_r(dependents, independents, allowed_missing, out=None):
"""
Compute Pearson's r between columns of ``dependents`` and ``independents``.
Parameters
----------
dependents : np.array[N, M]
Array with columns of data to be regressed against ``independent``.
independen... |
Compute Pearson's r between columns of ``dependents`` and ``independents``.
Parameters
----------
dependents : np.array[N, M]
Array with columns of data to be regressed against ``independent``.
independents : np.array[N, M] or np.array[N, 1]
Independent variable(s) of the regressio... | vectorized_pearson_r | python | quantopian/zipline | zipline/pipeline/factors/statistical.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/factors/statistical.py | Apache-2.0 |
def binary_operator(op):
"""
Factory function for making binary operator methods on a Filter subclass.
Returns a function "binary_operator" suitable for implementing functions
like __and__ or __or__.
"""
# When combining a Filter with a NumericalExpression, we use this
# attrgetter instance... |
Factory function for making binary operator methods on a Filter subclass.
Returns a function "binary_operator" suitable for implementing functions
like __and__ or __or__.
| binary_operator | python | quantopian/zipline | zipline/pipeline/filters/filter.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/filters/filter.py | Apache-2.0 |
def unary_operator(op):
"""
Factory function for making unary operator methods for Filters.
"""
valid_ops = {'~'}
if op not in valid_ops:
raise ValueError("Invalid unary operator %s." % op)
def unary_operator(self):
# This can't be hoisted up a scope because the types returned b... |
Factory function for making unary operator methods for Filters.
| unary_operator | python | quantopian/zipline | zipline/pipeline/filters/filter.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/filters/filter.py | Apache-2.0 |
def if_else(self, if_true, if_false):
"""
Create a term that selects values from one of two choices.
Parameters
----------
if_true : zipline.pipeline.term.ComputableTerm
Expression whose values should be used at locations where this
filter outputs True.
... |
Create a term that selects values from one of two choices.
Parameters
----------
if_true : zipline.pipeline.term.ComputableTerm
Expression whose values should be used at locations where this
filter outputs True.
if_false : zipline.pipeline.term.Computabl... | if_else | python | quantopian/zipline | zipline/pipeline/filters/filter.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/filters/filter.py | Apache-2.0 |
def _compute(self, arrays, dates, assets, mask):
"""
Compute our result with numexpr, then re-apply `mask`.
"""
return super(NumExprFilter, self)._compute(
arrays,
dates,
assets,
mask,
) & mask |
Compute our result with numexpr, then re-apply `mask`.
| _compute | python | quantopian/zipline | zipline/pipeline/filters/filter.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/filters/filter.py | Apache-2.0 |
def _validate(self):
"""
Ensure that our percentile bounds are well-formed.
"""
if not 0.0 <= self._min_percentile < self._max_percentile <= 100.0:
raise BadPercentileBounds(
min_percentile=self._min_percentile,
max_percentile=self._max_percent... |
Ensure that our percentile bounds are well-formed.
| _validate | python | quantopian/zipline | zipline/pipeline/filters/filter.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/filters/filter.py | Apache-2.0 |
def _compute(self, arrays, dates, assets, mask):
"""
For each row in the input, compute a mask of all values falling between
the given percentiles.
"""
# TODO: Review whether there's a better way of handling small numbers
# of columns.
data = arrays[0].copy().asty... |
For each row in the input, compute a mask of all values falling between
the given percentiles.
| _compute | python | quantopian/zipline | zipline/pipeline/filters/filter.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/filters/filter.py | Apache-2.0 |
def delegating_hooks_method(method_name):
"""Factory function for making DelegatingHooks methods.
"""
if method_name in PIPELINE_HOOKS_CONTEXT_MANAGERS:
# Generate a contextmanager that enters the context of all child hooks.
@wraps(getattr(PipelineHooks, method_name))
@contextmanager... | Factory function for making DelegatingHooks methods.
| delegating_hooks_method | python | quantopian/zipline | zipline/pipeline/hooks/delegate.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/hooks/delegate.py | Apache-2.0 |
def running_pipeline(self, pipeline, start_date, end_date):
"""
Contextmanager entered during execution of run_pipeline or
run_chunked_pipeline.
Parameters
----------
pipeline : zipline.pipeline.Pipeline
The pipeline being executed.
start_date : pd.Ti... |
Contextmanager entered during execution of run_pipeline or
run_chunked_pipeline.
Parameters
----------
pipeline : zipline.pipeline.Pipeline
The pipeline being executed.
start_date : pd.Timestamp
First date of the execution.
end_date : pd.... | running_pipeline | python | quantopian/zipline | zipline/pipeline/hooks/iface.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/hooks/iface.py | Apache-2.0 |
def computing_chunk(self, terms, start_date, end_date):
"""
Contextmanager entered during execution of compute_chunk.
Parameters
----------
terms : list[zipline.pipeline.Term]
List of terms, in execution order, that will be computed. This
value may change... |
Contextmanager entered during execution of compute_chunk.
Parameters
----------
terms : list[zipline.pipeline.Term]
List of terms, in execution order, that will be computed. This
value may change between chunks if ``populate_initial_workspace``
prepo... | computing_chunk | python | quantopian/zipline | zipline/pipeline/hooks/iface.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/hooks/iface.py | Apache-2.0 |
def loading_terms(self, terms):
"""Contextmanager entered when loading a batch of LoadableTerms.
Parameters
----------
terms : list[zipline.pipeline.LoadableTerm]
Terms being loaded.
""" | Contextmanager entered when loading a batch of LoadableTerms.
Parameters
----------
terms : list[zipline.pipeline.LoadableTerm]
Terms being loaded.
| loading_terms | python | quantopian/zipline | zipline/pipeline/hooks/iface.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/hooks/iface.py | Apache-2.0 |
def computing_term(self, term):
"""Contextmanager entered when computing a ComputableTerm.
Parameters
----------
terms : zipline.pipeline.ComputableTerm
Terms being computed.
""" | Contextmanager entered when computing a ComputableTerm.
Parameters
----------
terms : zipline.pipeline.ComputableTerm
Terms being computed.
| computing_term | python | quantopian/zipline | zipline/pipeline/hooks/iface.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/hooks/iface.py | Apache-2.0 |
def _format_execution_time(total_seconds):
"""Helper method for displaying total execution time of a Pipeline.
Parameters
----------
total_seconds : float
Number of seconds elapsed.
Returns
-------
formatted : str
User-facing text represe... | Helper method for displaying total execution time of a Pipeline.
Parameters
----------
total_seconds : float
Number of seconds elapsed.
Returns
-------
formatted : str
User-facing text representation of elapsed time.
| _format_execution_time | python | quantopian/zipline | zipline/pipeline/hooks/progress.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/hooks/progress.py | Apache-2.0 |
def repr_htmlsafe(t):
"""Repr a value and html-escape the result.
If an error is thrown by the repr, show a placeholder.
"""
try:
r = repr(t)
except Exception:
r = "(Error Displaying {})".format(type(t).__name__)
return escape_html(str(r), quote=True) | Repr a value and html-escape the result.
If an error is thrown by the repr, show a placeholder.
| repr_htmlsafe | python | quantopian/zipline | zipline/pipeline/hooks/progress.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/hooks/progress.py | Apache-2.0 |
def testing_hooks_method(method_name):
"""Factory function for making testing methods.
"""
if method_name in PIPELINE_HOOKS_CONTEXT_MANAGERS:
# Generate a method that enters the context of all sub-hooks.
@wraps(getattr(PipelineHooks, method_name))
@contextmanager
def ctx(self... | Factory function for making testing methods.
| testing_hooks_method | python | quantopian/zipline | zipline/pipeline/hooks/testing.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/hooks/testing.py | Apache-2.0 |
def load_adjusted_array(self, domain, columns, dates, sids, mask):
"""
Load data for ``columns`` as AdjustedArrays.
Parameters
----------
domain : zipline.pipeline.domain.Domain
The domain of the pipeline for which the requested data must be
loaded.
... |
Load data for ``columns`` as AdjustedArrays.
Parameters
----------
domain : zipline.pipeline.domain.Domain
The domain of the pipeline for which the requested data must be
loaded.
columns : list[zipline.pipeline.data.dataset.BoundColumn]
Colum... | load_adjusted_array | python | quantopian/zipline | zipline/pipeline/loaders/base.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/base.py | Apache-2.0 |
def required_estimates_fields(columns):
"""
Compute the set of resource columns required to serve
`columns`.
"""
# We also expect any of the field names that our loadable columns
# are mapped to.
return metadata_columns.union(viewvalues(columns)) |
Compute the set of resource columns required to serve
`columns`.
| required_estimates_fields | python | quantopian/zipline | zipline/pipeline/loaders/earnings_estimates.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/earnings_estimates.py | Apache-2.0 |
def validate_column_specs(events, columns):
"""
Verify that the columns of ``events`` can be used by a
EarningsEstimatesLoader to serve the BoundColumns described by
`columns`.
"""
required = required_estimates_fields(columns)
received = set(events.columns)
missing = required - received
... |
Verify that the columns of ``events`` can be used by a
EarningsEstimatesLoader to serve the BoundColumns described by
`columns`.
| validate_column_specs | python | quantopian/zipline | zipline/pipeline/loaders/earnings_estimates.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/earnings_estimates.py | Apache-2.0 |
def get_requested_quarter_data(self,
zero_qtr_data,
zeroth_quarter_idx,
stacked_last_per_qtr,
num_announcements,
dates):
"""
Sele... |
Selects the requested data for each date.
Parameters
----------
zero_qtr_data : pd.DataFrame
The 'time zero' data for each calendar date per sid.
zeroth_quarter_idx : pd.Index
An index of calendar dates, sid, and normalized quarters, for only
... | get_requested_quarter_data | python | quantopian/zipline | zipline/pipeline/loaders/earnings_estimates.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/earnings_estimates.py | Apache-2.0 |
def get_split_adjusted_asof_idx(self, dates):
"""
Compute the index in `dates` where the split-adjusted-asof-date
falls. This is the date up to which, and including which, we will
need to unapply all adjustments for and then re-apply them as they
come in. After this date, adjustm... |
Compute the index in `dates` where the split-adjusted-asof-date
falls. This is the date up to which, and including which, we will
need to unapply all adjustments for and then re-apply them as they
come in. After this date, adjustments are applied as normal.
Parameters
-... | get_split_adjusted_asof_idx | python | quantopian/zipline | zipline/pipeline/loaders/earnings_estimates.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/earnings_estimates.py | Apache-2.0 |
def collect_overwrites_for_sid(self,
group,
dates,
requested_qtr_data,
last_per_qtr,
sid_idx,
columns,
... |
Given a sid, collect all overwrites that should be applied for this
sid at each quarter boundary.
Parameters
----------
group : pd.DataFrame
The data for `sid`.
dates : pd.DatetimeIndex
The calendar dates for which estimates data is requested.
... | collect_overwrites_for_sid | python | quantopian/zipline | zipline/pipeline/loaders/earnings_estimates.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/earnings_estimates.py | Apache-2.0 |
def get_adjustments_for_sid(self,
group,
dates,
requested_qtr_data,
last_per_qtr,
sid_to_idx,
columns,
... |
Parameters
----------
group : pd.DataFrame
The data for the given sid.
dates : pd.DatetimeIndex
The calendar dates for which estimates data is requested.
requested_qtr_data : pd.DataFrame
The DataFrame with the latest values for the requested... | get_adjustments_for_sid | python | quantopian/zipline | zipline/pipeline/loaders/earnings_estimates.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/earnings_estimates.py | Apache-2.0 |
def merge_into_adjustments_for_all_sids(self,
all_adjustments_for_sid,
col_to_all_adjustments):
"""
Merge adjustments for a particular sid into a dictionary containing
adjustments for all sids.
Param... |
Merge adjustments for a particular sid into a dictionary containing
adjustments for all sids.
Parameters
----------
all_adjustments_for_sid : dict[int -> AdjustedArray]
All adjustments for a particular sid.
col_to_all_adjustments : dict[int -> AdjustedArray]... | merge_into_adjustments_for_all_sids | python | quantopian/zipline | zipline/pipeline/loaders/earnings_estimates.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/earnings_estimates.py | Apache-2.0 |
def get_adjustments(self,
zero_qtr_data,
requested_qtr_data,
last_per_qtr,
dates,
assets,
columns,
**kwargs):
"""
Creates an AdjustedArr... |
Creates an AdjustedArray from the given estimates data for the given
dates.
Parameters
----------
zero_qtr_data : pd.DataFrame
The 'time zero' data for each calendar date per sid.
requested_qtr_data : pd.DataFrame
The requested quarter data for e... | get_adjustments | python | quantopian/zipline | zipline/pipeline/loaders/earnings_estimates.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/earnings_estimates.py | Apache-2.0 |
def create_overwrites_for_quarter(self,
col_to_overwrites,
next_qtr_start_idx,
last_per_qtr,
quarters_with_estimates_for_sid,
requ... |
Add entries to the dictionary of columns to adjustments for the given
sid and the given quarter.
Parameters
----------
col_to_overwrites : dict [column_name -> list of ArrayAdjustment]
A dictionary mapping column names to all overwrites for those
columns... | create_overwrites_for_quarter | python | quantopian/zipline | zipline/pipeline/loaders/earnings_estimates.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/earnings_estimates.py | Apache-2.0 |
def get_last_data_per_qtr(self,
assets_with_data,
columns,
dates,
data_query_cutoff_times):
"""
Determine the last piece of information we know for each column on each
date in ... |
Determine the last piece of information we know for each column on each
date in the index for each sid and quarter.
Parameters
----------
assets_with_data : pd.Index
Index of all assets that appear in the raw data given to the
loader.
columns : i... | get_last_data_per_qtr | python | quantopian/zipline | zipline/pipeline/loaders/earnings_estimates.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/earnings_estimates.py | Apache-2.0 |
def get_zeroth_quarter_idx(self, stacked_last_per_qtr):
"""
Filters for releases that are on or after each simulation date and
determines the next quarter by picking out the upcoming release for
each date in the index.
Parameters
----------
stacked_last_per_qtr :... |
Filters for releases that are on or after each simulation date and
determines the next quarter by picking out the upcoming release for
each date in the index.
Parameters
----------
stacked_last_per_qtr : pd.DataFrame
A DataFrame with index of calendar dates,... | get_zeroth_quarter_idx | python | quantopian/zipline | zipline/pipeline/loaders/earnings_estimates.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/earnings_estimates.py | Apache-2.0 |
def get_zeroth_quarter_idx(self, stacked_last_per_qtr):
"""
Filters for releases that are on or after each simulation date and
determines the previous quarter by picking out the most recent
release relative to each date in the index.
Parameters
----------
stacked... |
Filters for releases that are on or after each simulation date and
determines the previous quarter by picking out the most recent
release relative to each date in the index.
Parameters
----------
stacked_last_per_qtr : pd.DataFrame
A DataFrame with index of ... | get_zeroth_quarter_idx | python | quantopian/zipline | zipline/pipeline/loaders/earnings_estimates.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/earnings_estimates.py | Apache-2.0 |
def get_adjustments_for_sid(self,
group,
dates,
requested_qtr_data,
last_per_qtr,
sid_to_idx,
columns,
... |
Collects both overwrites and adjustments for a particular sid.
Parameters
----------
split_adjusted_asof_idx : int
The integer index of the date on which the data was split-adjusted.
split_adjusted_cols_for_group : list of str
The names of requested colu... | get_adjustments_for_sid | python | quantopian/zipline | zipline/pipeline/loaders/earnings_estimates.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/earnings_estimates.py | Apache-2.0 |
def get_adjustments(self,
zero_qtr_data,
requested_qtr_data,
last_per_qtr,
dates,
assets,
columns,
**kwargs):
"""
Calculates both split ... |
Calculates both split adjustments and overwrites for all sids.
| get_adjustments | python | quantopian/zipline | zipline/pipeline/loaders/earnings_estimates.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/earnings_estimates.py | Apache-2.0 |
def determine_end_idx_for_adjustment(self,
adjustment_ts,
dates,
upper_bound,
requested_quarter,
sid_estimates):
... |
Determines the date until which the adjustment at the given date
index should be applied for the given quarter.
Parameters
----------
adjustment_ts : pd.Timestamp
The timestamp at which the adjustment occurs.
dates : pd.DatetimeIndex
The calendar... | determine_end_idx_for_adjustment | python | quantopian/zipline | zipline/pipeline/loaders/earnings_estimates.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/earnings_estimates.py | Apache-2.0 |
def collect_pre_split_asof_date_adjustments(
self,
split_adjusted_asof_date_idx,
sid_idx,
pre_adjustments,
requested_split_adjusted_columns
):
"""
Collect split adjustments that occur before the
split-adjusted-asof-date. All those a... |
Collect split adjustments that occur before the
split-adjusted-asof-date. All those adjustments must first be
UN-applied at the first date index and then re-applied on the
appropriate dates in order to match point in time share pricing data.
Parameters
----------
... | collect_pre_split_asof_date_adjustments | python | quantopian/zipline | zipline/pipeline/loaders/earnings_estimates.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/earnings_estimates.py | Apache-2.0 |
def collect_post_asof_split_adjustments(self,
post_adjustments,
requested_qtr_data,
sid,
sid_idx,
si... |
Collect split adjustments that occur after the
split-adjusted-asof-date. Each adjustment needs to be applied to all
dates on which knowledge for the requested quarter was older than the
date of the adjustment.
Parameters
----------
post_adjustments : tuple(list(... | collect_post_asof_split_adjustments | python | quantopian/zipline | zipline/pipeline/loaders/earnings_estimates.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/earnings_estimates.py | Apache-2.0 |
def retrieve_split_adjustment_data_for_sid(self,
dates,
sid,
split_adjusted_asof_idx):
"""
dates : pd.DatetimeIndex
The calendar dates.
sid : i... |
dates : pd.DatetimeIndex
The calendar dates.
sid : int
The sid for which we want to retrieve adjustments.
split_adjusted_asof_idx : int
The index in `dates` as-of which the data is split adjusted.
Returns
-------
pre_adjustments : tup... | retrieve_split_adjustment_data_for_sid | python | quantopian/zipline | zipline/pipeline/loaders/earnings_estimates.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/earnings_estimates.py | Apache-2.0 |
def merge_split_adjustments_with_overwrites(
self,
pre,
post,
overwrites,
requested_split_adjusted_columns
):
"""
Merge split adjustments with the dict containing overwrites.
Parameters
----------
pre : dict[str -> dict[int -> list]]
... |
Merge split adjustments with the dict containing overwrites.
Parameters
----------
pre : dict[str -> dict[int -> list]]
The adjustments that occur before the split-adjusted-asof-date.
post : dict[str -> dict[int -> list]]
The adjustments that occur after... | merge_split_adjustments_with_overwrites | python | quantopian/zipline | zipline/pipeline/loaders/earnings_estimates.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/earnings_estimates.py | Apache-2.0 |
def collect_split_adjustments(self,
adjustments_for_sid,
requested_qtr_data,
dates,
sid,
sid_idx,
sid_estimates,
... |
Collect split adjustments for previous quarters and apply them to the
given dictionary of splits for the given sid. Since overwrites just
replace all estimates before the new quarter with NaN, we don't need to
worry about re-applying split adjustments.
Parameters
------... | collect_split_adjustments | python | quantopian/zipline | zipline/pipeline/loaders/earnings_estimates.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/earnings_estimates.py | Apache-2.0 |
def collect_split_adjustments(self,
adjustments_for_sid,
requested_qtr_data,
dates,
sid,
sid_idx,
sid_estimates,
... |
Collect split adjustments for future quarters. Re-apply adjustments
that would be overwritten by overwrites. Merge split adjustments with
overwrites into the given dictionary of splits for the given sid.
Parameters
----------
adjustments_for_sid : dict[str -> dict[int -... | collect_split_adjustments | python | quantopian/zipline | zipline/pipeline/loaders/earnings_estimates.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/earnings_estimates.py | Apache-2.0 |
def without_fx(cls, raw_price_reader, adjustments_reader):
"""
Construct an EquityPricingLoader without support for fx rates.
The returned loader will raise an error if requested to load
currency-converted columns.
Parameters
----------
raw_price_reader : ziplin... |
Construct an EquityPricingLoader without support for fx rates.
The returned loader will raise an error if requested to load
currency-converted columns.
Parameters
----------
raw_price_reader : zipline.data.session_bars.SessionBarReader
Reader providing raw ... | without_fx | python | quantopian/zipline | zipline/pipeline/loaders/equity_pricing_loader.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/equity_pricing_loader.py | Apache-2.0 |
def _inplace_currency_convert(self, columns, arrays, dates, sids):
"""
Currency convert raw data loaded for ``column``.
Parameters
----------
columns : list[zipline.pipeline.data.BoundColumn]
List of columns whose raw data has been loaded.
arrays : list[np.ar... |
Currency convert raw data loaded for ``column``.
Parameters
----------
columns : list[zipline.pipeline.data.BoundColumn]
List of columns whose raw data has been loaded.
arrays : list[np.array]
List of arrays, parallel to ``columns`` containing data for t... | _inplace_currency_convert | python | quantopian/zipline | zipline/pipeline/loaders/equity_pricing_loader.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/equity_pricing_loader.py | Apache-2.0 |
def _split_column_types(self, columns):
"""Split out currency columns from OHLCV columns.
Parameters
----------
columns : list[zipline.pipeline.data.BoundColumn]
Columns to be loaded by ``load_adjusted_array``.
Returns
-------
ohlcv_columns : list[zi... | Split out currency columns from OHLCV columns.
Parameters
----------
columns : list[zipline.pipeline.data.BoundColumn]
Columns to be loaded by ``load_adjusted_array``.
Returns
-------
ohlcv_columns : list[zipline.pipeline.data.BoundColumn]
Price ... | _split_column_types | python | quantopian/zipline | zipline/pipeline/loaders/equity_pricing_loader.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/equity_pricing_loader.py | Apache-2.0 |
def required_event_fields(next_value_columns, previous_value_columns):
"""
Compute the set of resource columns required to serve
``next_value_columns`` and ``previous_value_columns``.
"""
# These metadata columns are used to align event indexers.
return {
TS_FIELD_NAME,
SID_FIELD... |
Compute the set of resource columns required to serve
``next_value_columns`` and ``previous_value_columns``.
| required_event_fields | python | quantopian/zipline | zipline/pipeline/loaders/events.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/events.py | Apache-2.0 |
def validate_column_specs(events, next_value_columns, previous_value_columns):
"""
Verify that the columns of ``events`` can be used by an EventsLoader to
serve the BoundColumns described by ``next_value_columns`` and
``previous_value_columns``.
"""
required = required_event_fields(next_value_co... |
Verify that the columns of ``events`` can be used by an EventsLoader to
serve the BoundColumns described by ``next_value_columns`` and
``previous_value_columns``.
| validate_column_specs | python | quantopian/zipline | zipline/pipeline/loaders/events.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/events.py | Apache-2.0 |
def split_next_and_previous_event_columns(self, requested_columns):
"""
Split requested columns into columns that should load the next known
value and columns that should load the previous known value.
Parameters
----------
requested_columns : iterable[BoundColumn]
... |
Split requested columns into columns that should load the next known
value and columns that should load the previous known value.
Parameters
----------
requested_columns : iterable[BoundColumn]
Returns
-------
next_cols, previous_cols : iterable[BoundCo... | split_next_and_previous_event_columns | python | quantopian/zipline | zipline/pipeline/loaders/events.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/events.py | Apache-2.0 |
def format_adjustments(self, dates, assets):
"""
Build a dict of Adjustment objects in the format expected by
AdjustedArray.
Returns a dict of the form:
{
# Integer index into `dates` for the date on which we should
# apply the list of adjustments.
... |
Build a dict of Adjustment objects in the format expected by
AdjustedArray.
Returns a dict of the form:
{
# Integer index into `dates` for the date on which we should
# apply the list of adjustments.
1 : [
Float64Multiply(first_row=2,... | format_adjustments | python | quantopian/zipline | zipline/pipeline/loaders/frame.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/frame.py | Apache-2.0 |
def load_adjusted_array(self, domain, columns, dates, sids, mask):
"""
Load data from our stored baseline.
"""
if len(columns) != 1:
raise ValueError(
"Can't load multiple columns with DataFrameLoader"
)
column = columns[0]
self._v... |
Load data from our stored baseline.
| load_adjusted_array | python | quantopian/zipline | zipline/pipeline/loaders/frame.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/frame.py | Apache-2.0 |
def _validate_input_column(self, column):
"""Make sure a passed column is our column.
"""
if column != self.column and column.unspecialize() != self.column:
raise ValueError("Can't load unknown column %s" % column) | Make sure a passed column is our column.
| _validate_input_column | python | quantopian/zipline | zipline/pipeline/loaders/frame.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/frame.py | Apache-2.0 |
def load_adjusted_array(self, domain, columns, dates, sids, mask):
"""
Load by delegating to sub-loaders.
"""
out = {}
for col in columns:
try:
loader = self._loaders.get(col)
if loader is None:
loader = self._loader... |
Load by delegating to sub-loaders.
| load_adjusted_array | python | quantopian/zipline | zipline/pipeline/loaders/synthetic.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/synthetic.py | Apache-2.0 |
def values(self, dtype, dates, sids):
"""
Make a random array of shape (len(dates), len(sids)) with ``dtype``.
"""
shape = (len(dates), len(sids))
return {
datetime64ns_dtype: self._datetime_values,
float64_dtype: self._float_values,
int64_dtyp... |
Make a random array of shape (len(dates), len(sids)) with ``dtype``.
| values | python | quantopian/zipline | zipline/pipeline/loaders/synthetic.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/synthetic.py | Apache-2.0 |
def _int_values(self, shape):
"""
Return uniformly-distributed integers between 0 and 100.
"""
return (self.state.randint(low=0, high=100, size=shape)
.astype('int64')) # default is system int |
Return uniformly-distributed integers between 0 and 100.
| _int_values | python | quantopian/zipline | zipline/pipeline/loaders/synthetic.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/synthetic.py | Apache-2.0 |
def make_bar_data(asset_info, calendar, holes=None):
"""
For a given asset/date/column combination, we generate a corresponding raw
value using the following formula for OHLCV columns:
data(asset, date, column) = (100,000 * asset_id)
+ (10,000 * column_num)
... |
For a given asset/date/column combination, we generate a corresponding raw
value using the following formula for OHLCV columns:
data(asset, date, column) = (100,000 * asset_id)
+ (10,000 * column_num)
+ (date - Jan 1 2000).days # ~6000 for 2015... | make_bar_data | python | quantopian/zipline | zipline/pipeline/loaders/synthetic.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/synthetic.py | Apache-2.0 |
def _raw_data_for_asset(asset_id):
"""
Generate 'raw' data that encodes information about the asset.
See docstring for a description of the data format.
"""
# Get the dates for which this asset existed according to our asset
# info.
datetimes = calendar[calendar.... |
Generate 'raw' data that encodes information about the asset.
See docstring for a description of the data format.
| _raw_data_for_asset | python | quantopian/zipline | zipline/pipeline/loaders/synthetic.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/synthetic.py | Apache-2.0 |
def expected_bar_value(asset_id, date, colname):
"""
Check that the raw value for an asset/date/column triple is as
expected.
Used by tests to verify data written by a writer.
"""
from_asset = asset_id * 100000
from_colname = OHLCV.index(colname) * 1000
from_date = (date - PSEUDO_EPOCH)... |
Check that the raw value for an asset/date/column triple is as
expected.
Used by tests to verify data written by a writer.
| expected_bar_value | python | quantopian/zipline | zipline/pipeline/loaders/synthetic.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/synthetic.py | Apache-2.0 |
def expected_bar_values_2d(dates,
assets,
asset_info,
colname,
holes=None):
"""
Return an 2D array containing cls.expected_value(asset_id, date,
colname) for each date/asset pair in the inputs.
M... |
Return an 2D array containing cls.expected_value(asset_id, date,
colname) for each date/asset pair in the inputs.
Missing locs are filled with 0 for volume and NaN for price columns:
- Values before/after an asset's lifetime.
- Values for asset_ids not contained in asset_info.
- L... | expected_bar_values_2d | python | quantopian/zipline | zipline/pipeline/loaders/synthetic.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/synthetic.py | Apache-2.0 |
def next_event_indexer(all_dates,
data_query_cutoff,
all_sids,
event_dates,
event_timestamps,
event_sids):
"""
Construct an index array that, when applied to an array of values, produces
a 2D a... |
Construct an index array that, when applied to an array of values, produces
a 2D array containing the values associated with the next event for each
sid at each moment in time.
Locations where no next event was known will be filled with -1.
Parameters
----------
all_dates : ndarray[dateti... | next_event_indexer | python | quantopian/zipline | zipline/pipeline/loaders/utils.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/utils.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.