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 load(name):
"""Return an instance of the metrics set registered with the given name.
Returns
-------
metrics : set[Metric]
A new instance of the metrics set.
Raises
------
ValueError
Raised when no metrics set is registered to ``name`... | Return an instance of the metrics set registered with the given name.
Returns
-------
metrics : set[Metric]
A new instance of the metrics set.
Raises
------
ValueError
Raised when no metrics set is registered to ``name``
| load | python | quantopian/zipline | zipline/finance/metrics/core.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/metrics/core.py | Apache-2.0 |
def risk_metric_period(cls,
start_session,
end_session,
algorithm_returns,
benchmark_returns,
algorithm_leverages):
"""
Creates a dictionary representing the state of th... |
Creates a dictionary representing the state of the risk report.
Parameters
----------
start_session : pd.Timestamp
Start of period (inclusive) to produce metrics on
end_session : pd.Timestamp
End of period (inclusive) to produce metrics on
algori... | risk_metric_period | python | quantopian/zipline | zipline/finance/metrics/metric.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/metrics/metric.py | Apache-2.0 |
def handle_minute_close(self, dt, data_portal):
"""
Handles the close of the given minute in minute emission.
Parameters
----------
dt : Timestamp
The minute that is ending
Returns
-------
A minute perf packet.
"""
self.sync_l... |
Handles the close of the given minute in minute emission.
Parameters
----------
dt : Timestamp
The minute that is ending
Returns
-------
A minute perf packet.
| handle_minute_close | python | quantopian/zipline | zipline/finance/metrics/tracker.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/metrics/tracker.py | Apache-2.0 |
def handle_market_open(self, session_label, data_portal):
"""Handles the start of each session.
Parameters
----------
session_label : Timestamp
The label of the session that is about to begin.
data_portal : DataPortal
The current data portal.
"""
... | Handles the start of each session.
Parameters
----------
session_label : Timestamp
The label of the session that is about to begin.
data_portal : DataPortal
The current data portal.
| handle_market_open | python | quantopian/zipline | zipline/finance/metrics/tracker.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/metrics/tracker.py | Apache-2.0 |
def handle_market_close(self, dt, data_portal):
"""Handles the close of the given day.
Parameters
----------
dt : Timestamp
The most recently completed simulation datetime.
data_portal : DataPortal
The current data portal.
Returns
-------... | Handles the close of the given day.
Parameters
----------
dt : Timestamp
The most recently completed simulation datetime.
data_portal : DataPortal
The current data portal.
Returns
-------
A daily perf packet.
| handle_market_close | python | quantopian/zipline | zipline/finance/metrics/tracker.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/metrics/tracker.py | Apache-2.0 |
def handle_simulation_end(self, data_portal):
"""
When the simulation is complete, run the full period risk report
and send it out on the results socket.
"""
log.info(
'Simulated {} trading days\n'
'first open: {}\n'
'last close: {}',
... |
When the simulation is complete, run the full period risk report
and send it out on the results socket.
| handle_simulation_end | python | quantopian/zipline | zipline/finance/metrics/tracker.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/metrics/tracker.py | Apache-2.0 |
def date_sorted_sources(*sources):
"""
Takes an iterable of sources, generating namestrings and
piping their output into date_sort.
"""
sorted_stream = heapq.merge(*(_decorate_source(s) for s in sources))
# Strip out key decoration
for _, message in sorted_stream:
yield message |
Takes an iterable of sources, generating namestrings and
piping their output into date_sort.
| date_sorted_sources | python | quantopian/zipline | zipline/gens/composites.py | https://github.com/quantopian/zipline/blob/master/zipline/gens/composites.py | Apache-2.0 |
def _cleanup_expired_assets(self, dt, position_assets):
"""
Clear out any assets that have expired before starting a new sim day.
Performs two functions:
1. Finds all assets for which we have open orders and clears any
orders whose assets are on or after their auto_close_dat... |
Clear out any assets that have expired before starting a new sim day.
Performs two functions:
1. Finds all assets for which we have open orders and clears any
orders whose assets are on or after their auto_close_date.
2. Finds all assets for which we have positions and gen... | _cleanup_expired_assets | python | quantopian/zipline | zipline/gens/tradesimulation.py | https://github.com/quantopian/zipline/blob/master/zipline/gens/tradesimulation.py | Apache-2.0 |
def _get_daily_message(self, dt, algo, metrics_tracker):
"""
Get a perf message for the given datetime.
"""
perf_message = metrics_tracker.handle_market_close(
dt,
self.data_portal,
)
perf_message['daily_perf']['recorded_vars'] = algo.recorded_vars... |
Get a perf message for the given datetime.
| _get_daily_message | python | quantopian/zipline | zipline/gens/tradesimulation.py | https://github.com/quantopian/zipline/blob/master/zipline/gens/tradesimulation.py | Apache-2.0 |
def hash_args(*args, **kwargs):
"""Define a unique string for any set of representable args."""
arg_string = '_'.join([str(arg) for arg in args])
kwarg_string = '_'.join([str(key) + '=' + str(value)
for key, value in iteritems(kwargs)])
combined = ':'.join([arg_string, kwarg... | Define a unique string for any set of representable args. | hash_args | python | quantopian/zipline | zipline/gens/utils.py | https://github.com/quantopian/zipline/blob/master/zipline/gens/utils.py | Apache-2.0 |
def assert_datasource_protocol(event):
"""Assert that an event meets the protocol for datasource outputs."""
assert event.type in DATASOURCE_TYPE
# Done packets have no dt.
if not event.type == DATASOURCE_TYPE.DONE:
assert isinstance(event.dt, datetime)
assert event.dt.tzinfo == pytz.u... | Assert that an event meets the protocol for datasource outputs. | assert_datasource_protocol | python | quantopian/zipline | zipline/gens/utils.py | https://github.com/quantopian/zipline/blob/master/zipline/gens/utils.py | Apache-2.0 |
def assert_trade_protocol(event):
"""Assert that an event meets the protocol for datasource TRADE outputs."""
assert_datasource_protocol(event)
assert event.type == DATASOURCE_TYPE.TRADE
assert isinstance(event.price, numbers.Real)
assert isinstance(event.volume, numbers.Integral)
assert isinst... | Assert that an event meets the protocol for datasource TRADE outputs. | assert_trade_protocol | python | quantopian/zipline | zipline/gens/utils.py | https://github.com/quantopian/zipline/blob/master/zipline/gens/utils.py | Apache-2.0 |
def _normalize_array(data, missing_value):
"""
Coerce buffer data for an AdjustedArray into a standard scalar
representation, returning the coerced array and a dict of argument to pass
to np.view to use when providing a user-facing view of the underlying data.
- float* data is coerced to float64 wi... |
Coerce buffer data for an AdjustedArray into a standard scalar
representation, returning the coerced array and a dict of argument to pass
to np.view to use when providing a user-facing view of the underlying data.
- float* data is coerced to float64 with viewtype float64.
- int32, int64, and uint3... | _normalize_array | python | quantopian/zipline | zipline/lib/adjusted_array.py | https://github.com/quantopian/zipline/blob/master/zipline/lib/adjusted_array.py | Apache-2.0 |
def _merge_simple(adjustment_lists, front_idx, back_idx):
"""
Merge lists of new and existing adjustments for a given index by appending
or prepending new adjustments to existing adjustments.
Notes
-----
This method is meant to be used with ``toolz.merge_with`` to merge
adjustment mappings.... |
Merge lists of new and existing adjustments for a given index by appending
or prepending new adjustments to existing adjustments.
Notes
-----
This method is meant to be used with ``toolz.merge_with`` to merge
adjustment mappings. In case of a collision ``adjustment_lists`` contains
two lis... | _merge_simple | python | quantopian/zipline | zipline/lib/adjusted_array.py | https://github.com/quantopian/zipline/blob/master/zipline/lib/adjusted_array.py | Apache-2.0 |
def copy(self):
"""Copy an adjusted array, deep-copying the ``data`` array.
"""
if self._invalidated:
raise ValueError('cannot copy invalidated AdjustedArray')
return type(self)(
self.data.copy(order='F'),
self.adjustments,
self.missing_va... | Copy an adjusted array, deep-copying the ``data`` array.
| copy | python | quantopian/zipline | zipline/lib/adjusted_array.py | https://github.com/quantopian/zipline/blob/master/zipline/lib/adjusted_array.py | Apache-2.0 |
def update_adjustments(self, adjustments, method):
"""
Merge ``adjustments`` with existing adjustments, handling index
collisions according to ``method``.
Parameters
----------
adjustments : dict[int -> list[Adjustment]]
The mapping of row indices to lists of... |
Merge ``adjustments`` with existing adjustments, handling index
collisions according to ``method``.
Parameters
----------
adjustments : dict[int -> list[Adjustment]]
The mapping of row indices to lists of adjustments that should be
appended to existing a... | update_adjustments | python | quantopian/zipline | zipline/lib/adjusted_array.py | https://github.com/quantopian/zipline/blob/master/zipline/lib/adjusted_array.py | Apache-2.0 |
def _iterator_type(self):
"""
The iterator produced when `traverse` is called on this Array.
"""
if isinstance(self._data, LabelArray):
return LabelWindow
return CONCRETE_WINDOW_TYPES[self._data.dtype] |
The iterator produced when `traverse` is called on this Array.
| _iterator_type | python | quantopian/zipline | zipline/lib/adjusted_array.py | https://github.com/quantopian/zipline/blob/master/zipline/lib/adjusted_array.py | Apache-2.0 |
def inspect(self):
"""
Return a string representation of the data stored in this array.
"""
return dedent(
"""\
Adjusted Array ({dtype}):
Data:
{data!r}
Adjustments:
{adjustments}
"""
).format(
... |
Return a string representation of the data stored in this array.
| inspect | python | quantopian/zipline | zipline/lib/adjusted_array.py | https://github.com/quantopian/zipline/blob/master/zipline/lib/adjusted_array.py | Apache-2.0 |
def update_labels(self, func):
"""
Map a function over baseline and adjustment values in place.
Note that the baseline data values must be a LabelArray.
"""
if not isinstance(self.data, LabelArray):
raise TypeError(
'update_labels only supported if da... |
Map a function over baseline and adjustment values in place.
Note that the baseline data values must be a LabelArray.
| update_labels | python | quantopian/zipline | zipline/lib/adjusted_array.py | https://github.com/quantopian/zipline/blob/master/zipline/lib/adjusted_array.py | Apache-2.0 |
def ensure_ndarray(ndarray_or_adjusted_array):
"""
Return the input as a numpy ndarray.
This is a no-op if the input is already an ndarray. If the input is an
adjusted_array, this extracts a read-only view of its internal data buffer.
Parameters
----------
ndarray_or_adjusted_array : nump... |
Return the input as a numpy ndarray.
This is a no-op if the input is already an ndarray. If the input is an
adjusted_array, this extracts a read-only view of its internal data buffer.
Parameters
----------
ndarray_or_adjusted_array : numpy.ndarray | zipline.data.adjusted_array
Returns
... | ensure_ndarray | python | quantopian/zipline | zipline/lib/adjusted_array.py | https://github.com/quantopian/zipline/blob/master/zipline/lib/adjusted_array.py | Apache-2.0 |
def _check_window_params(data, window_length):
"""
Check that a window of length `window_length` is well-defined on `data`.
Parameters
----------
data : np.ndarray[ndim=2]
The array of data to check.
window_length : int
Length of the desired window.
Returns
-------
... |
Check that a window of length `window_length` is well-defined on `data`.
Parameters
----------
data : np.ndarray[ndim=2]
The array of data to check.
window_length : int
Length of the desired window.
Returns
-------
None
Raises
------
WindowLengthNotPositiv... | _check_window_params | python | quantopian/zipline | zipline/lib/adjusted_array.py | https://github.com/quantopian/zipline/blob/master/zipline/lib/adjusted_array.py | Apache-2.0 |
def compare_arrays(left, right):
"Eq check with a short-circuit for identical objects."
return (
left is right
or ((left.shape == right.shape) and (left == right).all())
) | Eq check with a short-circuit for identical objects. | compare_arrays | python | quantopian/zipline | zipline/lib/labelarray.py | https://github.com/quantopian/zipline/blob/master/zipline/lib/labelarray.py | Apache-2.0 |
def from_codes_and_metadata(cls,
codes,
categories,
reverse_categories,
missing_value):
"""
Rehydrate a LabelArray from the codes and metadata.
Parameters
----... |
Rehydrate a LabelArray from the codes and metadata.
Parameters
----------
codes : np.ndarray[integral]
The codes for the label array.
categories : np.ndarray[object]
The unique string categories.
reverse_categories : dict[str, int]
Th... | from_codes_and_metadata | python | quantopian/zipline | zipline/lib/labelarray.py | https://github.com/quantopian/zipline/blob/master/zipline/lib/labelarray.py | Apache-2.0 |
def from_categorical(cls, categorical, missing_value=None):
"""
Create a LabelArray from a pandas categorical.
Parameters
----------
categorical : pd.Categorical
The categorical object to convert.
missing_value : bytes, unicode, or None, optional
... |
Create a LabelArray from a pandas categorical.
Parameters
----------
categorical : pd.Categorical
The categorical object to convert.
missing_value : bytes, unicode, or None, optional
The missing value to use for this LabelArray.
Returns
... | from_categorical | python | quantopian/zipline | zipline/lib/labelarray.py | https://github.com/quantopian/zipline/blob/master/zipline/lib/labelarray.py | Apache-2.0 |
def __array_finalize__(self, obj):
"""
Called by Numpy after array construction.
There are three cases where this can happen:
1. Someone tries to directly construct a new array by doing::
>>> ndarray.__new__(LabelArray, ...) # doctest: +SKIP
In this case, obj ... |
Called by Numpy after array construction.
There are three cases where this can happen:
1. Someone tries to directly construct a new array by doing::
>>> ndarray.__new__(LabelArray, ...) # doctest: +SKIP
In this case, obj will be None. We treat this as an error case ... | __array_finalize__ | python | quantopian/zipline | zipline/lib/labelarray.py | https://github.com/quantopian/zipline/blob/master/zipline/lib/labelarray.py | Apache-2.0 |
def as_int_array(self):
"""
Convert self into a regular ndarray of ints.
This is an O(1) operation. It does not copy the underlying data.
"""
return self.view(
type=ndarray,
dtype=unsigned_int_dtype_with_size_in_bytes(self.itemsize),
) |
Convert self into a regular ndarray of ints.
This is an O(1) operation. It does not copy the underlying data.
| as_int_array | python | quantopian/zipline | zipline/lib/labelarray.py | https://github.com/quantopian/zipline/blob/master/zipline/lib/labelarray.py | Apache-2.0 |
def as_categorical(self):
"""
Coerce self into a pandas categorical.
This is only defined on 1D arrays, since that's all pandas supports.
"""
if len(self.shape) > 1:
raise ValueError("Can't convert a 2D array to a categorical.")
with ignore_pandas_nan_catego... |
Coerce self into a pandas categorical.
This is only defined on 1D arrays, since that's all pandas supports.
| as_categorical | python | quantopian/zipline | zipline/lib/labelarray.py | https://github.com/quantopian/zipline/blob/master/zipline/lib/labelarray.py | Apache-2.0 |
def as_categorical_frame(self, index, columns, name=None):
"""
Coerce self into a pandas DataFrame of Categoricals.
"""
if len(self.shape) != 2:
raise ValueError(
"Can't convert a non-2D LabelArray into a DataFrame."
)
expected_shape = (le... |
Coerce self into a pandas DataFrame of Categoricals.
| as_categorical_frame | python | quantopian/zipline | zipline/lib/labelarray.py | https://github.com/quantopian/zipline/blob/master/zipline/lib/labelarray.py | Apache-2.0 |
def set_scalar(self, indexer, value):
"""
Set scalar value into the array.
Parameters
----------
indexer : any
The indexer to set the value at.
value : str
The value to assign at the given locations.
Raises
------
ValueErr... |
Set scalar value into the array.
Parameters
----------
indexer : any
The indexer to set the value at.
value : str
The value to assign at the given locations.
Raises
------
ValueError
Raised when ``value`` is not a val... | set_scalar | python | quantopian/zipline | zipline/lib/labelarray.py | https://github.com/quantopian/zipline/blob/master/zipline/lib/labelarray.py | Apache-2.0 |
def is_missing(self):
"""
Like isnan, but checks for locations where we store missing values.
"""
return (
self.as_int_array() == self.reverse_categories[self.missing_value]
) |
Like isnan, but checks for locations where we store missing values.
| is_missing | python | quantopian/zipline | zipline/lib/labelarray.py | https://github.com/quantopian/zipline/blob/master/zipline/lib/labelarray.py | Apache-2.0 |
def not_missing(self):
"""
Like ~isnan, but checks for locations where we store missing values.
"""
return (
self.as_int_array() != self.reverse_categories[self.missing_value]
) |
Like ~isnan, but checks for locations where we store missing values.
| not_missing | python | quantopian/zipline | zipline/lib/labelarray.py | https://github.com/quantopian/zipline/blob/master/zipline/lib/labelarray.py | Apache-2.0 |
def _equality_check(op):
"""
Shared code for __eq__ and __ne__, parameterized on the actual
comparison operator to use.
"""
def method(self, other):
if isinstance(other, LabelArray):
self_mv = self.missing_value
other_mv = other.missin... |
Shared code for __eq__ and __ne__, parameterized on the actual
comparison operator to use.
| _equality_check | python | quantopian/zipline | zipline/lib/labelarray.py | https://github.com/quantopian/zipline/blob/master/zipline/lib/labelarray.py | Apache-2.0 |
def empty_like(self, shape):
"""
Make an empty LabelArray with the same categories as ``self``, filled
with ``self.missing_value``.
"""
return type(self).from_codes_and_metadata(
codes=np.full(
shape,
self.reverse_categories[self.missin... |
Make an empty LabelArray with the same categories as ``self``, filled
with ``self.missing_value``.
| empty_like | python | quantopian/zipline | zipline/lib/labelarray.py | https://github.com/quantopian/zipline/blob/master/zipline/lib/labelarray.py | Apache-2.0 |
def map_predicate(self, f):
"""
Map a function from str -> bool element-wise over ``self``.
``f`` will be applied exactly once to each non-missing unique value in
``self``. Missing values will always return False.
"""
# Functions passed to this are of type str -> bool. ... |
Map a function from str -> bool element-wise over ``self``.
``f`` will be applied exactly once to each non-missing unique value in
``self``. Missing values will always return False.
| map_predicate | python | quantopian/zipline | zipline/lib/labelarray.py | https://github.com/quantopian/zipline/blob/master/zipline/lib/labelarray.py | Apache-2.0 |
def map(self, f):
"""
Map a function from str -> str element-wise over ``self``.
``f`` will be applied exactly once to each non-missing unique value in
``self``. Missing values will always map to ``self.missing_value``.
"""
# f() should only return None if None is our mi... |
Map a function from str -> str element-wise over ``self``.
``f`` will be applied exactly once to each non-missing unique value in
``self``. Missing values will always map to ``self.missing_value``.
| map | python | quantopian/zipline | zipline/lib/labelarray.py | https://github.com/quantopian/zipline/blob/master/zipline/lib/labelarray.py | Apache-2.0 |
def labelarray_where(cond, trues, falses):
"""LabelArray-aware implementation of np.where.
"""
if trues.missing_value != falses.missing_value:
raise ValueError(
"Can't compute where on arrays with different missing values."
)
strs = np.where(cond, trues.as_string_array(), fa... | LabelArray-aware implementation of np.where.
| labelarray_where | python | quantopian/zipline | zipline/lib/labelarray.py | https://github.com/quantopian/zipline/blob/master/zipline/lib/labelarray.py | Apache-2.0 |
def naive_grouped_rowwise_apply(data,
group_labels,
func,
func_args=(),
out=None):
"""
Simple implementation of grouped row-wise function application.
Parameters
----------
... |
Simple implementation of grouped row-wise function application.
Parameters
----------
data : ndarray[ndim=2]
Input array over which to apply a grouped function.
group_labels : ndarray[ndim=2, dtype=int64]
Labels to use to bucket inputs from array.
Should be the same shape a... | naive_grouped_rowwise_apply | python | quantopian/zipline | zipline/lib/normalize.py | https://github.com/quantopian/zipline/blob/master/zipline/lib/normalize.py | Apache-2.0 |
def quantiles(data, nbins_or_partition_bounds):
"""
Compute rowwise array quantiles on an input.
"""
return apply_along_axis(
qcut,
1,
data,
q=nbins_or_partition_bounds, labels=False,
) |
Compute rowwise array quantiles on an input.
| quantiles | python | quantopian/zipline | zipline/lib/quantiles.py | https://github.com/quantopian/zipline/blob/master/zipline/lib/quantiles.py | Apache-2.0 |
def restrict_to_dtype(dtype, message_template):
"""
A factory for decorators that restrict Term methods to only be callable on
Terms with a specific dtype.
This is conceptually similar to
zipline.utils.input_validation.expect_dtypes, but provides more flexibility
for providing error messages th... |
A factory for decorators that restrict Term methods to only be callable on
Terms with a specific dtype.
This is conceptually similar to
zipline.utils.input_validation.expect_dtypes, but provides more flexibility
for providing error messages that are specifically targeting Term methods.
Parame... | restrict_to_dtype | python | quantopian/zipline | zipline/pipeline/api_utils.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/api_utils.py | Apache-2.0 |
def all_sessions(self):
"""
Get all trading sessions for the calendar of this domain.
This determines the row labels of Pipeline outputs for pipelines run on
this domain.
Returns
-------
sessions : pd.DatetimeIndex
An array of all session labels for ... |
Get all trading sessions for the calendar of this domain.
This determines the row labels of Pipeline outputs for pipelines run on
this domain.
Returns
-------
sessions : pd.DatetimeIndex
An array of all session labels for this domain.
| all_sessions | python | quantopian/zipline | zipline/pipeline/domain.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/domain.py | Apache-2.0 |
def country_code(self):
"""The country code for this domain.
Returns
-------
code : str
The two-character country iso3166 country code for this domain.
""" | The country code for this domain.
Returns
-------
code : str
The two-character country iso3166 country code for this domain.
| country_code | python | quantopian/zipline | zipline/pipeline/domain.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/domain.py | Apache-2.0 |
def data_query_cutoff_for_sessions(self, sessions):
"""Compute the data query cutoff time for the given sessions.
Parameters
----------
sessions : pd.DatetimeIndex
The sessions to get the data query cutoff times for. This index
will contain all midnight UTC value... | Compute the data query cutoff time for the given sessions.
Parameters
----------
sessions : pd.DatetimeIndex
The sessions to get the data query cutoff times for. This index
will contain all midnight UTC values.
Returns
-------
data_query_cutoff :... | data_query_cutoff_for_sessions | python | quantopian/zipline | zipline/pipeline/domain.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/domain.py | Apache-2.0 |
def roll_forward(self, dt):
"""
Given a date, align it to the calendar of the pipeline's domain.
Parameters
----------
dt : pd.Timestamp
Returns
-------
pd.Timestamp
"""
dt = pd.Timestamp(dt, tz='UTC')
trading_days = self.all_ses... |
Given a date, align it to the calendar of the pipeline's domain.
Parameters
----------
dt : pd.Timestamp
Returns
-------
pd.Timestamp
| roll_forward | python | quantopian/zipline | zipline/pipeline/domain.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/domain.py | Apache-2.0 |
def infer_domain(terms):
"""
Infer the domain from a collection of terms.
The algorithm for inferring domains is as follows:
- If all input terms have a domain of GENERIC, the result is GENERIC.
- If there is exactly one non-generic domain in the input terms, the result
is that domain.
... |
Infer the domain from a collection of terms.
The algorithm for inferring domains is as follows:
- If all input terms have a domain of GENERIC, the result is GENERIC.
- If there is exactly one non-generic domain in the input terms, the result
is that domain.
- Otherwise, an AmbiguousDomain... | infer_domain | python | quantopian/zipline | zipline/pipeline/domain.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/domain.py | Apache-2.0 |
def select_sampling_indices(dates, frequency):
"""
Choose entries from ``dates`` to use for downsampling at ``frequency``.
Parameters
----------
dates : pd.DatetimeIndex
Dates from which to select sample choices.
{frequency}
Returns
-------
indices : np.array[int64]
... |
Choose entries from ``dates`` to use for downsampling at ``frequency``.
Parameters
----------
dates : pd.DatetimeIndex
Dates from which to select sample choices.
{frequency}
Returns
-------
indices : np.array[int64]
An array condtaining indices of dates on which sample... | select_sampling_indices | python | quantopian/zipline | zipline/pipeline/downsample_helpers.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/downsample_helpers.py | Apache-2.0 |
def run_chunked_pipeline(self,
pipeline,
start_date,
end_date,
chunksize,
hooks=None):
"""
Compute values for ``pipeline`` from ``start_date`` to ``end_date``,... |
Compute values for ``pipeline`` from ``start_date`` to ``end_date``, in
date chunks of size ``chunksize``.
Chunked execution reduces memory consumption, and may reduce
computation time depending on the contents of your pipeline.
Parameters
----------
pipeline :... | run_chunked_pipeline | python | quantopian/zipline | zipline/pipeline/engine.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/engine.py | Apache-2.0 |
def default_populate_initial_workspace(initial_workspace,
root_mask_term,
execution_plan,
dates,
assets):
"""The default implementation for ``populate_initial_w... | The default implementation for ``populate_initial_workspace``. This
function returns the ``initial_workspace`` argument without making any
modifications.
Parameters
----------
initial_workspace : dict[array-like]
The initial workspace before we have populated it with any cached
term... | default_populate_initial_workspace | python | quantopian/zipline | zipline/pipeline/engine.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/engine.py | Apache-2.0 |
def run_pipeline(self, pipeline, start_date, end_date, hooks=None):
"""
Compute values for ``pipeline`` from ``start_date`` to ``end_date``.
Parameters
----------
pipeline : zipline.pipeline.Pipeline
The pipeline to run.
start_date : pd.Timestamp
... |
Compute values for ``pipeline`` from ``start_date`` to ``end_date``.
Parameters
----------
pipeline : zipline.pipeline.Pipeline
The pipeline to run.
start_date : pd.Timestamp
Start date of the computed matrix.
end_date : pd.Timestamp
... | run_pipeline | python | quantopian/zipline | zipline/pipeline/engine.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/engine.py | Apache-2.0 |
def _compute_root_mask(self, domain, start_date, end_date, extra_rows):
"""
Compute a lifetimes matrix from our AssetFinder, then drop columns that
didn't exist at all during the query dates.
Parameters
----------
domain : zipline.pipeline.domain.Domain
Domai... |
Compute a lifetimes matrix from our AssetFinder, then drop columns that
didn't exist at all during the query dates.
Parameters
----------
domain : zipline.pipeline.domain.Domain
Domain for which we're computing a pipeline.
start_date : pd.Timestamp
... | _compute_root_mask | python | quantopian/zipline | zipline/pipeline/engine.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/engine.py | Apache-2.0 |
def _inputs_for_term(term, workspace, graph, domain, refcounts):
"""
Compute inputs for the given term.
This is mostly complicated by the fact that for each input we store as
many rows as will be necessary to serve **any** computation requiring
that input.
"""
of... |
Compute inputs for the given term.
This is mostly complicated by the fact that for each input we store as
many rows as will be necessary to serve **any** computation requiring
that input.
| _inputs_for_term | python | quantopian/zipline | zipline/pipeline/engine.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/engine.py | Apache-2.0 |
def compute_chunk(self,
graph,
dates,
sids,
workspace,
refcounts,
execution_order,
hooks):
"""
Compute the Pipeline terms in the graph for the request... |
Compute the Pipeline terms in the graph for the requested start and end
dates.
This is where we do the actual work of running a pipeline.
Parameters
----------
graph : zipline.pipeline.graph.ExecutionPlan
Dependency graph of the terms to be executed.
... | compute_chunk | python | quantopian/zipline | zipline/pipeline/engine.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/engine.py | Apache-2.0 |
def _to_narrow(self, terms, data, mask, dates, assets):
"""
Convert raw computed pipeline results into a DataFrame for public APIs.
Parameters
----------
terms : dict[str -> Term]
Dict mapping column names to terms.
data : dict[str -> ndarray[ndim=2]]
... |
Convert raw computed pipeline results into a DataFrame for public APIs.
Parameters
----------
terms : dict[str -> Term]
Dict mapping column names to terms.
data : dict[str -> ndarray[ndim=2]]
Dict mapping column names to computed results for those names.... | _to_narrow | python | quantopian/zipline | zipline/pipeline/engine.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/engine.py | Apache-2.0 |
def _validate_compute_chunk_params(self,
graph,
dates,
sids,
initial_workspace):
"""
Verify that the values passed to compute_chunk are well-formed.... |
Verify that the values passed to compute_chunk are well-formed.
| _validate_compute_chunk_params | python | quantopian/zipline | zipline/pipeline/engine.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/engine.py | Apache-2.0 |
def _ensure_can_load(self, loader, terms):
"""Ensure that ``loader`` can load ``terms``.
"""
if not loader.currency_aware:
bad = [t for t in terms if t.currency_conversion is not None]
if bad:
raise ValueError(
"Requested currency conve... | Ensure that ``loader`` can load ``terms``.
| _ensure_can_load | python | quantopian/zipline | zipline/pipeline/engine.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/engine.py | Apache-2.0 |
def _pipeline_output_index(dates, assets, mask):
"""
Create a MultiIndex for a pipeline output.
Parameters
----------
dates : pd.DatetimeIndex
Row labels for ``mask``.
assets : pd.Index
Column labels for ``mask``.
mask : np.ndarray[bool]
Mask array indicating date/as... |
Create a MultiIndex for a pipeline output.
Parameters
----------
dates : pd.DatetimeIndex
Row labels for ``mask``.
assets : pd.Index
Column labels for ``mask``.
mask : np.ndarray[bool]
Mask array indicating date/asset pairs that should be included in
output inde... | _pipeline_output_index | python | quantopian/zipline | zipline/pipeline/engine.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/engine.py | Apache-2.0 |
def _ensure_element(tup, elem):
"""
Create a tuple containing all elements of tup, plus elem.
Returns the new tuple and the index of elem in the new tuple.
"""
try:
return tup, tup.index(elem)
except ValueError:
return tuple(chain(tup, (elem,))), len(tup) |
Create a tuple containing all elements of tup, plus elem.
Returns the new tuple and the index of elem in the new tuple.
| _ensure_element | python | quantopian/zipline | zipline/pipeline/expression.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/expression.py | Apache-2.0 |
def method_name_for_op(op, commute=False):
"""
Get the name of the Python magic method corresponding to `op`.
Parameters
----------
op : str {'+','-','*', '/','**','&','|','^','<','<=','==','!=','>=','>'}
The requested operation.
commute : bool
Whether to return the name of an e... |
Get the name of the Python magic method corresponding to `op`.
Parameters
----------
op : str {'+','-','*', '/','**','&','|','^','<','<=','==','!=','>=','>'}
The requested operation.
commute : bool
Whether to return the name of an equivalent method after flipping args.
Returns... | method_name_for_op | python | quantopian/zipline | zipline/pipeline/expression.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/expression.py | Apache-2.0 |
def _validate(self):
"""
Ensure that our expression string has variables of the form x_0, x_1,
... x_(N - 1), where N is the length of our inputs.
"""
variable_names, _unused = getExprNames(self._expr, {})
expr_indices = []
for name in variable_names:
... |
Ensure that our expression string has variables of the form x_0, x_1,
... x_(N - 1), where N is the length of our inputs.
| _validate | python | quantopian/zipline | zipline/pipeline/expression.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/expression.py | Apache-2.0 |
def _compute(self, arrays, dates, assets, mask):
"""
Compute our stored expression string with numexpr.
"""
out = full(mask.shape, self.missing_value, dtype=self.dtype)
# This writes directly into our output buffer.
numexpr.evaluate(
self._expr,
lo... |
Compute our stored expression string with numexpr.
| _compute | python | quantopian/zipline | zipline/pipeline/expression.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/expression.py | Apache-2.0 |
def _rebind_variables(self, new_inputs):
"""
Return self._expr with all variables rebound to the indices implied by
new_inputs.
"""
expr = self._expr
# If we have 11+ variables, some of our variable names may be
# substrings of other variable names. For example, ... |
Return self._expr with all variables rebound to the indices implied by
new_inputs.
| _rebind_variables | python | quantopian/zipline | zipline/pipeline/expression.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/expression.py | Apache-2.0 |
def _merge_expressions(self, other):
"""
Merge the inputs of two NumericalExpressions into a single input tuple,
rewriting their respective string expressions to make input names
resolve correctly.
Returns a tuple of (new_self_expr, new_other_expr, new_inputs)
"""
... |
Merge the inputs of two NumericalExpressions into a single input tuple,
rewriting their respective string expressions to make input names
resolve correctly.
Returns a tuple of (new_self_expr, new_other_expr, new_inputs)
| _merge_expressions | python | quantopian/zipline | zipline/pipeline/expression.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/expression.py | Apache-2.0 |
def build_binary_op(self, op, other):
"""
Compute new expression strings and a new inputs tuple for combining
self and other with a binary operator.
"""
if isinstance(other, NumericalExpression):
self_expr, other_expr, new_inputs = self._merge_expressions(other)
... |
Compute new expression strings and a new inputs tuple for combining
self and other with a binary operator.
| build_binary_op | python | quantopian/zipline | zipline/pipeline/expression.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/expression.py | Apache-2.0 |
def graph_repr(self):
"""Short repr to use when rendering Pipeline graphs."""
# Replace any floating point numbers in the expression
# with their scientific notation
final = re.sub(r"[-+]?\d*\.\d+",
lambda x: format(float(x.group(0)), '.2E'),
... | Short repr to use when rendering Pipeline graphs. | graph_repr | python | quantopian/zipline | zipline/pipeline/expression.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/expression.py | Apache-2.0 |
def _add_to_graph(self, term, parents):
"""
Add a term and all its children to ``graph``.
``parents`` is the set of all the parents of ``term` that we've added
so far. It is only used to detect dependency cycles.
"""
if self._frozen:
raise ValueError(
... |
Add a term and all its children to ``graph``.
``parents`` is the set of all the parents of ``term` that we've added
so far. It is only used to detect dependency cycles.
| _add_to_graph | python | quantopian/zipline | zipline/pipeline/graph.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/graph.py | Apache-2.0 |
def execution_order(self, workspace, refcounts):
"""
Return a topologically-sorted list of the terms in ``self`` which
need to be computed.
Filters out any terms that are already present in ``workspace``, as
well as any terms with refcounts of 0.
Parameters
----... |
Return a topologically-sorted list of the terms in ``self`` which
need to be computed.
Filters out any terms that are already present in ``workspace``, as
well as any terms with refcounts of 0.
Parameters
----------
workspace : dict[Term, np.ndarray]
... | execution_order | python | quantopian/zipline | zipline/pipeline/graph.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/graph.py | Apache-2.0 |
def initial_refcounts(self, initial_terms):
"""
Calculate initial refcounts for execution of this graph.
Parameters
----------
initial_terms : iterable[Term]
An iterable of terms that were pre-computed before graph execution.
Each node starts with a refcount... |
Calculate initial refcounts for execution of this graph.
Parameters
----------
initial_terms : iterable[Term]
An iterable of terms that were pre-computed before graph execution.
Each node starts with a refcount equal to its outdegree, and output
nodes get o... | initial_refcounts | python | quantopian/zipline | zipline/pipeline/graph.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/graph.py | Apache-2.0 |
def _decref_dependencies_recursive(self, term, refcounts, garbage):
"""
Decrement terms recursively.
Notes
-----
This should only be used to build the initial workspace, after that we
should use:
:meth:`~zipline.pipeline.graph.TermGraph.decref_dependencies`
... |
Decrement terms recursively.
Notes
-----
This should only be used to build the initial workspace, after that we
should use:
:meth:`~zipline.pipeline.graph.TermGraph.decref_dependencies`
| _decref_dependencies_recursive | python | quantopian/zipline | zipline/pipeline/graph.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/graph.py | Apache-2.0 |
def decref_dependencies(self, term, refcounts):
"""
Decrement in-edges for ``term`` after computation.
Parameters
----------
term : zipline.pipeline.Term
The term whose parents should be decref'ed.
refcounts : dict[Term -> int]
Dictionary of refco... |
Decrement in-edges for ``term`` after computation.
Parameters
----------
term : zipline.pipeline.Term
The term whose parents should be decref'ed.
refcounts : dict[Term -> int]
Dictionary of refcounts.
Return
------
garbage : set[... | decref_dependencies | python | quantopian/zipline | zipline/pipeline/graph.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/graph.py | Apache-2.0 |
def offset(self):
"""
For all pairs (term, input) such that `input` is an input to `term`,
compute a mapping::
(term, input) -> offset(term, input)
where ``offset(term, input)`` is the number of rows that ``term``
should truncate off the raw array produced for ``inp... |
For all pairs (term, input) such that `input` is an input to `term`,
compute a mapping::
(term, input) -> offset(term, input)
where ``offset(term, input)`` is the number of rows that ``term``
should truncate off the raw array produced for ``input`` before using
it.... | offset | python | quantopian/zipline | zipline/pipeline/graph.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/graph.py | Apache-2.0 |
def extra_rows(self):
"""
A dict mapping `term` -> `# of extra rows to load/compute of `term`.
Notes
----
This value depends on the other terms in the graph that require `term`
**as an input**. This is not to be confused with `term.dependencies`,
which describes... |
A dict mapping `term` -> `# of extra rows to load/compute of `term`.
Notes
----
This value depends on the other terms in the graph that require `term`
**as an input**. This is not to be confused with `term.dependencies`,
which describes how many additional rows of `ter... | extra_rows | python | quantopian/zipline | zipline/pipeline/graph.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/graph.py | Apache-2.0 |
def _ensure_extra_rows(self, term, N):
"""
Ensure that we're going to compute at least N extra rows of `term`.
"""
attrs = self.graph.node[term]
attrs['extra_rows'] = max(N, attrs.get('extra_rows', 0)) |
Ensure that we're going to compute at least N extra rows of `term`.
| _ensure_extra_rows | python | quantopian/zipline | zipline/pipeline/graph.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/graph.py | Apache-2.0 |
def mask_and_dates_for_term(self,
term,
root_mask_term,
workspace,
all_dates):
"""
Load mask and mask row labels for term.
Parameters
----------
term :... |
Load mask and mask row labels for term.
Parameters
----------
term : Term
The term to load the mask and labels for.
root_mask_term : Term
The term that represents the root asset exists mask.
workspace : dict[Term, any]
The values that... | mask_and_dates_for_term | python | quantopian/zipline | zipline/pipeline/graph.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/graph.py | Apache-2.0 |
def _assert_all_loadable_terms_specialized_to(self, domain):
"""Make sure that we've specialized all loadable terms in the graph.
"""
for term in self.graph.node:
if isinstance(term, LoadableTerm):
assert term.domain is domain | Make sure that we've specialized all loadable terms in the graph.
| _assert_all_loadable_terms_specialized_to | python | quantopian/zipline | zipline/pipeline/graph.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/graph.py | Apache-2.0 |
def compute(self, today, assets, out, *arrays):
"""
Override this method with a function that writes a value into `out`.
"""
raise NotImplementedError(
"{name} must define a compute method".format(
name=type(self).__name__
)
) |
Override this method with a function that writes a value into `out`.
| compute | python | quantopian/zipline | zipline/pipeline/mixins.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/mixins.py | Apache-2.0 |
def _allocate_output(self, windows, shape):
"""
Allocate an output array whose rows should be passed to `self.compute`.
The resulting array must have a shape of ``shape``.
If we have standard outputs (i.e. self.outputs is NotSpecified), the
default is an empty ndarray whose dty... |
Allocate an output array whose rows should be passed to `self.compute`.
The resulting array must have a shape of ``shape``.
If we have standard outputs (i.e. self.outputs is NotSpecified), the
default is an empty ndarray whose dtype is ``self.dtype``.
If we have an outputs tu... | _allocate_output | python | quantopian/zipline | zipline/pipeline/mixins.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/mixins.py | Apache-2.0 |
def _compute(self, windows, dates, assets, mask):
"""
Call the user's `compute` function on each window with a pre-built
output array.
"""
format_inputs = self._format_inputs
compute = self.compute
params = self.params
ndim = self.ndim
shape = (le... |
Call the user's `compute` function on each window with a pre-built
output array.
| _compute | python | quantopian/zipline | zipline/pipeline/mixins.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/mixins.py | Apache-2.0 |
def universal_mixin_specialization(cls, principal_type):
"""
Create a new subtype of `principal_type` that adds this mixin to
``principal_type``. ``principal_type`` will be one of Factor, Filter,
or Classifier.
"""
mixin = cls._universal_mixin_type()
memo_key = (m... |
Create a new subtype of `principal_type` that adds this mixin to
``principal_type``. ``principal_type`` will be one of Factor, Filter,
or Classifier.
| universal_mixin_specialization | python | quantopian/zipline | zipline/pipeline/mixins.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/mixins.py | Apache-2.0 |
def compute_extra_rows(self,
all_dates,
start_date,
end_date,
min_extra_rows):
"""
Ensure that min_extra_rows pushes us back to a computation date.
Parameters
----------
a... |
Ensure that min_extra_rows pushes us back to a computation date.
Parameters
----------
all_dates : pd.DatetimeIndex
The trading sessions against which ``self`` will be computed.
start_date : pd.Timestamp
The first date for which final output is requested... | compute_extra_rows | python | quantopian/zipline | zipline/pipeline/mixins.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/mixins.py | Apache-2.0 |
def _compute(self, inputs, dates, assets, mask):
"""
Compute by delegating to self._wrapped_term._compute on sample dates.
On non-sample dates, forward-fill from previously-computed samples.
"""
to_sample = dates[select_sampling_indices(dates, self._frequency)]
assert to... |
Compute by delegating to self._wrapped_term._compute on sample dates.
On non-sample dates, forward-fill from previously-computed samples.
| _compute | python | quantopian/zipline | zipline/pipeline/mixins.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/mixins.py | Apache-2.0 |
def add(self, term, name, overwrite=False):
"""Add a column.
The results of computing ``term`` will show up as a column in the
DataFrame produced by running this pipeline.
Parameters
----------
column : zipline.pipeline.Term
A Filter, Factor, or Classifier t... | Add a column.
The results of computing ``term`` will show up as a column in the
DataFrame produced by running this pipeline.
Parameters
----------
column : zipline.pipeline.Term
A Filter, Factor, or Classifier to add to the pipeline.
name : str
N... | add | python | quantopian/zipline | zipline/pipeline/pipeline.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/pipeline.py | Apache-2.0 |
def set_screen(self, screen, overwrite=False):
"""Set a screen on this Pipeline.
Parameters
----------
filter : zipline.pipeline.Filter
The filter to apply as a screen.
overwrite : bool
Whether to overwrite any existing screen. If overwrite is False
... | Set a screen on this Pipeline.
Parameters
----------
filter : zipline.pipeline.Filter
The filter to apply as a screen.
overwrite : bool
Whether to overwrite any existing screen. If overwrite is False
and self.screen is not None, we raise an error.
... | set_screen | python | quantopian/zipline | zipline/pipeline/pipeline.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/pipeline.py | Apache-2.0 |
def to_execution_plan(self,
domain,
default_screen,
start_date,
end_date):
"""
Compile into an ExecutionPlan.
Parameters
----------
domain : zipline.pipeline.domain.Domain
... |
Compile into an ExecutionPlan.
Parameters
----------
domain : zipline.pipeline.domain.Domain
Domain on which the pipeline will be executed.
default_screen : zipline.pipeline.Term
Term to use as a screen if self.screen is None.
all_dates : pd.Date... | to_execution_plan | python | quantopian/zipline | zipline/pipeline/pipeline.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/pipeline.py | Apache-2.0 |
def show_graph(self, format='svg'):
"""
Render this Pipeline as a DAG.
Parameters
----------
format : {'svg', 'png', 'jpeg'}
Image format to render with. Default is 'svg'.
"""
g = self.to_simple_graph(AssetExists())
if format == 'svg':
... |
Render this Pipeline as a DAG.
Parameters
----------
format : {'svg', 'png', 'jpeg'}
Image format to render with. Default is 'svg'.
| show_graph | python | quantopian/zipline | zipline/pipeline/pipeline.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/pipeline.py | Apache-2.0 |
def _output_terms(self):
"""
A list of terms that are outputs of this pipeline.
Includes all terms registered as data outputs of the pipeline, plus the
screen, if present.
"""
terms = list(six.itervalues(self._columns))
screen = self.screen
if screen is n... |
A list of terms that are outputs of this pipeline.
Includes all terms registered as data outputs of the pipeline, plus the
screen, if present.
| _output_terms | python | quantopian/zipline | zipline/pipeline/pipeline.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/pipeline.py | Apache-2.0 |
def domain(self, default):
"""
Get the domain for this pipeline.
- If an explicit domain was provided at construction time, use it.
- Otherwise, infer a domain from the registered columns.
- If no domain can be inferred, return ``default``.
Parameters
----------... |
Get the domain for this pipeline.
- If an explicit domain was provided at construction time, use it.
- Otherwise, infer a domain from the registered columns.
- If no domain can be inferred, return ``default``.
Parameters
----------
default : zipline.pipeline.do... | domain | python | quantopian/zipline | zipline/pipeline/pipeline.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/pipeline.py | Apache-2.0 |
def __new__(cls,
domain=NotSpecified,
dtype=NotSpecified,
missing_value=NotSpecified,
window_safe=NotSpecified,
ndim=NotSpecified,
# params is explicitly not allowed to be passed to an instance.
*args,
... |
Memoized constructor for Terms.
Caching previously-constructed Terms is useful because it allows us to
only compute equivalent sub-expressions once when traversing a Pipeline
dependency graph.
Caching previously-constructed Terms is **sane** because terms and
their inp... | __new__ | python | quantopian/zipline | zipline/pipeline/term.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/term.py | Apache-2.0 |
def _pop_params(cls, kwargs):
"""
Pop entries from the `kwargs` passed to cls.__new__ based on the values
in `cls.params`.
Parameters
----------
kwargs : dict
The kwargs passed to cls.__new__.
Returns
-------
params : list[(str, objec... |
Pop entries from the `kwargs` passed to cls.__new__ based on the values
in `cls.params`.
Parameters
----------
kwargs : dict
The kwargs passed to cls.__new__.
Returns
-------
params : list[(str, object)]
A list of string, value p... | _pop_params | python | quantopian/zipline | zipline/pipeline/term.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/term.py | Apache-2.0 |
def _static_identity(cls,
domain,
dtype,
missing_value,
window_safe,
ndim,
params):
"""
Return the identity of the Term that would be constructed from the... |
Return the identity of the Term that would be constructed from the
given arguments.
Identities that compare equal will cause us to return a cached instance
rather than constructing a new one. We do this primarily because it
makes dependency resolution easier.
This is ... | _static_identity | python | quantopian/zipline | zipline/pipeline/term.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/term.py | Apache-2.0 |
def _init(self, domain, dtype, missing_value, window_safe, ndim, params):
"""
Parameters
----------
domain : zipline.pipeline.domain.Domain
The domain of this term.
dtype : np.dtype
Dtype of this term's output.
missing_value : object
Mi... |
Parameters
----------
domain : zipline.pipeline.domain.Domain
The domain of this term.
dtype : np.dtype
Dtype of this term's output.
missing_value : object
Missing value for this term.
ndim : 1 or 2
The dimensionality of th... | _init | python | quantopian/zipline | zipline/pipeline/term.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/term.py | Apache-2.0 |
def _validate(self):
"""
Assert that this term is well-formed. This should be called exactly
once, at the end of Term._init().
"""
# mark that we got here to enforce that subclasses overriding _validate
# call super().
self._subclass_called_super_validate = True |
Assert that this term is well-formed. This should be called exactly
once, at the end of Term._init().
| _validate | python | quantopian/zipline | zipline/pipeline/term.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/term.py | Apache-2.0 |
def compute_extra_rows(self,
all_dates,
start_date,
end_date,
min_extra_rows):
"""
Calculate the number of extra rows needed to compute ``self``.
Must return at least ``min_extra_rows``, ... |
Calculate the number of extra rows needed to compute ``self``.
Must return at least ``min_extra_rows``, and the default implementation
is to just return ``min_extra_rows``. This is overridden by
downsampled terms to ensure that the first date computed is a
recomputation date.
... | compute_extra_rows | python | quantopian/zipline | zipline/pipeline/term.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/term.py | Apache-2.0 |
def windowed(self):
"""
Whether or not this term represents a trailing window computation.
If term.windowed is truthy, its compute_from_windows method will be
called with instances of AdjustedArray as inputs.
If term.windowed is falsey, its compute_from_baseline will be called
... |
Whether or not this term represents a trailing window computation.
If term.windowed is truthy, its compute_from_windows method will be
called with instances of AdjustedArray as inputs.
If term.windowed is falsey, its compute_from_baseline will be called
with instances of np.nd... | windowed | python | quantopian/zipline | zipline/pipeline/term.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/term.py | Apache-2.0 |
def dependencies(self):
"""
The number of extra rows needed for each of our inputs to compute this
term.
"""
extra_input_rows = max(0, self.window_length - 1)
out = {}
for term in self.inputs:
out[term] = extra_input_rows
out[self.mask] = 0
... |
The number of extra rows needed for each of our inputs to compute this
term.
| dependencies | python | quantopian/zipline | zipline/pipeline/term.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/term.py | Apache-2.0 |
def to_workspace_value(self, result, assets):
"""
Called with a column of the result of a pipeline. This needs to put
the data into a format that can be used in a workspace to continue
doing computations.
Parameters
----------
result : pd.Series
A mul... |
Called with a column of the result of a pipeline. This needs to put
the data into a format that can be used in a workspace to continue
doing computations.
Parameters
----------
result : pd.Series
A multiindexed series with (dates, assets) whose values are th... | to_workspace_value | python | quantopian/zipline | zipline/pipeline/term.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/term.py | Apache-2.0 |
def downsample(self, frequency):
"""
Make a term that computes from ``self`` at lower-than-daily frequency.
Parameters
----------
{frequency}
"""
from .mixins import DownsampledMixin
downsampled_type = type(self)._with_mixin(DownsampledMixin)
retu... |
Make a term that computes from ``self`` at lower-than-daily frequency.
Parameters
----------
{frequency}
| downsample | python | quantopian/zipline | zipline/pipeline/term.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/term.py | Apache-2.0 |
def alias(self, name):
"""
Make a term from ``self`` that names the expression.
Parameters
----------
{name}
Returns
-------
aliased : Aliased
``self`` with a name.
Notes
-----
This is useful for giving a name to a nu... |
Make a term from ``self`` that names the expression.
Parameters
----------
{name}
Returns
-------
aliased : Aliased
``self`` with a name.
Notes
-----
This is useful for giving a name to a numerical or boolean expression.
... | alias | python | quantopian/zipline | zipline/pipeline/term.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/term.py | Apache-2.0 |
def isnull(self):
"""
A Filter producing True for values where this Factor has missing data.
Equivalent to self.isnan() when ``self.dtype`` is float64.
Otherwise equivalent to ``self.eq(self.missing_value)``.
Returns
-------
filter : zipline.pipeline.Filter
... |
A Filter producing True for values where this Factor has missing data.
Equivalent to self.isnan() when ``self.dtype`` is float64.
Otherwise equivalent to ``self.eq(self.missing_value)``.
Returns
-------
filter : zipline.pipeline.Filter
| isnull | python | quantopian/zipline | zipline/pipeline/term.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/term.py | Apache-2.0 |
def notnull(self):
"""
A Filter producing True for values where this Factor has complete data.
Equivalent to ``~self.isnan()` when ``self.dtype`` is float64.
Otherwise equivalent to ``(self != self.missing_value)``.
Returns
-------
filter : zipline.pipeline.Filt... |
A Filter producing True for values where this Factor has complete data.
Equivalent to ``~self.isnan()` when ``self.dtype`` is float64.
Otherwise equivalent to ``(self != self.missing_value)``.
Returns
-------
filter : zipline.pipeline.Filter
| notnull | python | quantopian/zipline | zipline/pipeline/term.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/term.py | Apache-2.0 |
def fillna(self, fill_value):
"""
Create a new term that fills missing values of this term's output with
``fill_value``.
Parameters
----------
fill_value : zipline.pipeline.ComputableTerm, or object.
Object to use as replacement for missing values.
... |
Create a new term that fills missing values of this term's output with
``fill_value``.
Parameters
----------
fill_value : zipline.pipeline.ComputableTerm, or object.
Object to use as replacement for missing values.
If a ComputableTerm (e.g. a Factor) is... | fillna | python | quantopian/zipline | zipline/pipeline/term.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/term.py | Apache-2.0 |
def validate_dtype(termname, dtype, missing_value):
"""
Validate a `dtype` and `missing_value` passed to Term.__new__.
Ensures that we know how to represent ``dtype``, and that missing_value
is specified for types without default missing values.
Returns
-------
validated_dtype, validated_m... |
Validate a `dtype` and `missing_value` passed to Term.__new__.
Ensures that we know how to represent ``dtype``, and that missing_value
is specified for types without default missing values.
Returns
-------
validated_dtype, validated_missing_value : np.dtype, any
The dtype and missing_... | validate_dtype | python | quantopian/zipline | zipline/pipeline/term.py | https://github.com/quantopian/zipline/blob/master/zipline/pipeline/term.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.