partition stringclasses 3
values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1
value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
train | rolling_window | Restride an array of shape
(X_0, ... X_N)
into an array of shape
(length, X_0 - length + 1, ... X_N)
where each slice at index i along the first axis is equivalent to
result[i] = array[length * i:length * (i + 1)]
Parameters
----------
array : np.ndarray
The bas... | zipline/utils/numpy_utils.py | def rolling_window(array, length):
"""
Restride an array of shape
(X_0, ... X_N)
into an array of shape
(length, X_0 - length + 1, ... X_N)
where each slice at index i along the first axis is equivalent to
result[i] = array[length * i:length * (i + 1)]
Parameters
--... | def rolling_window(array, length):
"""
Restride an array of shape
(X_0, ... X_N)
into an array of shape
(length, X_0 - length + 1, ... X_N)
where each slice at index i along the first axis is equivalent to
result[i] = array[length * i:length * (i + 1)]
Parameters
--... | [
"Restride",
"an",
"array",
"of",
"shape"
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/numpy_utils.py#L259-L325 | [
"def",
"rolling_window",
"(",
"array",
",",
"length",
")",
":",
"orig_shape",
"=",
"array",
".",
"shape",
"if",
"not",
"orig_shape",
":",
"raise",
"IndexError",
"(",
"\"Can't restride a scalar.\"",
")",
"elif",
"orig_shape",
"[",
"0",
"]",
"<=",
"length",
":... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | isnat | Check if a value is np.NaT. | zipline/utils/numpy_utils.py | def isnat(obj):
"""
Check if a value is np.NaT.
"""
if obj.dtype.kind not in ('m', 'M'):
raise ValueError("%s is not a numpy datetime or timedelta")
return obj.view(int64_dtype) == iNaT | def isnat(obj):
"""
Check if a value is np.NaT.
"""
if obj.dtype.kind not in ('m', 'M'):
raise ValueError("%s is not a numpy datetime or timedelta")
return obj.view(int64_dtype) == iNaT | [
"Check",
"if",
"a",
"value",
"is",
"np",
".",
"NaT",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/numpy_utils.py#L334-L340 | [
"def",
"isnat",
"(",
"obj",
")",
":",
"if",
"obj",
".",
"dtype",
".",
"kind",
"not",
"in",
"(",
"'m'",
",",
"'M'",
")",
":",
"raise",
"ValueError",
"(",
"\"%s is not a numpy datetime or timedelta\"",
")",
"return",
"obj",
".",
"view",
"(",
"int64_dtype",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | is_missing | Generic is_missing function that handles NaN and NaT. | zipline/utils/numpy_utils.py | def is_missing(data, missing_value):
"""
Generic is_missing function that handles NaN and NaT.
"""
if is_float(data) and isnan(missing_value):
return isnan(data)
elif is_datetime(data) and isnat(missing_value):
return isnat(data)
return (data == missing_value) | def is_missing(data, missing_value):
"""
Generic is_missing function that handles NaN and NaT.
"""
if is_float(data) and isnan(missing_value):
return isnan(data)
elif is_datetime(data) and isnat(missing_value):
return isnat(data)
return (data == missing_value) | [
"Generic",
"is_missing",
"function",
"that",
"handles",
"NaN",
"and",
"NaT",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/numpy_utils.py#L343-L351 | [
"def",
"is_missing",
"(",
"data",
",",
"missing_value",
")",
":",
"if",
"is_float",
"(",
"data",
")",
"and",
"isnan",
"(",
"missing_value",
")",
":",
"return",
"isnan",
"(",
"data",
")",
"elif",
"is_datetime",
"(",
"data",
")",
"and",
"isnat",
"(",
"mi... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | busday_count_mask_NaT | Simple of numpy.busday_count that returns `float` arrays rather than int
arrays, and handles `NaT`s by returning `NaN`s where the inputs were `NaT`.
Doesn't support custom weekdays or calendars, but probably should in the
future.
See Also
--------
np.busday_count | zipline/utils/numpy_utils.py | def busday_count_mask_NaT(begindates, enddates, out=None):
"""
Simple of numpy.busday_count that returns `float` arrays rather than int
arrays, and handles `NaT`s by returning `NaN`s where the inputs were `NaT`.
Doesn't support custom weekdays or calendars, but probably should in the
future.
S... | def busday_count_mask_NaT(begindates, enddates, out=None):
"""
Simple of numpy.busday_count that returns `float` arrays rather than int
arrays, and handles `NaT`s by returning `NaN`s where the inputs were `NaT`.
Doesn't support custom weekdays or calendars, but probably should in the
future.
S... | [
"Simple",
"of",
"numpy",
".",
"busday_count",
"that",
"returns",
"float",
"arrays",
"rather",
"than",
"int",
"arrays",
"and",
"handles",
"NaT",
"s",
"by",
"returning",
"NaN",
"s",
"where",
"the",
"inputs",
"were",
"NaT",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/numpy_utils.py#L354-L381 | [
"def",
"busday_count_mask_NaT",
"(",
"begindates",
",",
"enddates",
",",
"out",
"=",
"None",
")",
":",
"if",
"out",
"is",
"None",
":",
"out",
"=",
"empty",
"(",
"broadcast",
"(",
"begindates",
",",
"enddates",
")",
".",
"shape",
",",
"dtype",
"=",
"flo... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | changed_locations | Compute indices of values in ``a`` that differ from the previous value.
Parameters
----------
a : np.ndarray
The array on which to indices of change.
include_first : bool
Whether or not to consider the first index of the array as "changed".
Example
-------
>>> import numpy ... | zipline/utils/numpy_utils.py | def changed_locations(a, include_first):
"""
Compute indices of values in ``a`` that differ from the previous value.
Parameters
----------
a : np.ndarray
The array on which to indices of change.
include_first : bool
Whether or not to consider the first index of the array as "cha... | def changed_locations(a, include_first):
"""
Compute indices of values in ``a`` that differ from the previous value.
Parameters
----------
a : np.ndarray
The array on which to indices of change.
include_first : bool
Whether or not to consider the first index of the array as "cha... | [
"Compute",
"indices",
"of",
"values",
"in",
"a",
"that",
"differ",
"from",
"the",
"previous",
"value",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/numpy_utils.py#L469-L496 | [
"def",
"changed_locations",
"(",
"a",
",",
"include_first",
")",
":",
"if",
"a",
".",
"ndim",
">",
"1",
":",
"raise",
"ValueError",
"(",
"\"indices_of_changed_values only supports 1D arrays.\"",
")",
"indices",
"=",
"flatnonzero",
"(",
"diff",
"(",
"a",
")",
"... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | compute_date_range_chunks | Compute the start and end dates to run a pipeline for.
Parameters
----------
sessions : DatetimeIndex
The available dates.
start_date : pd.Timestamp
The first date in the pipeline.
end_date : pd.Timestamp
The last date in the pipeline.
chunksize : int or None
The... | zipline/utils/date_utils.py | def compute_date_range_chunks(sessions, start_date, end_date, chunksize):
"""Compute the start and end dates to run a pipeline for.
Parameters
----------
sessions : DatetimeIndex
The available dates.
start_date : pd.Timestamp
The first date in the pipeline.
end_date : pd.Timesta... | def compute_date_range_chunks(sessions, start_date, end_date, chunksize):
"""Compute the start and end dates to run a pipeline for.
Parameters
----------
sessions : DatetimeIndex
The available dates.
start_date : pd.Timestamp
The first date in the pipeline.
end_date : pd.Timesta... | [
"Compute",
"the",
"start",
"and",
"end",
"dates",
"to",
"run",
"a",
"pipeline",
"for",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/date_utils.py#L4-L42 | [
"def",
"compute_date_range_chunks",
"(",
"sessions",
",",
"start_date",
",",
"end_date",
",",
"chunksize",
")",
":",
"if",
"start_date",
"not",
"in",
"sessions",
":",
"raise",
"KeyError",
"(",
"\"Start date %s is not found in calendar.\"",
"%",
"(",
"start_date",
".... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | SimplePipelineEngine.run_pipeline | Compute a pipeline.
Parameters
----------
pipeline : zipline.pipeline.Pipeline
The pipeline to run.
start_date : pd.Timestamp
Start date of the computed matrix.
end_date : pd.Timestamp
End date of the computed matrix.
Returns
... | zipline/pipeline/engine.py | def run_pipeline(self, pipeline, start_date, end_date):
"""
Compute a pipeline.
Parameters
----------
pipeline : zipline.pipeline.Pipeline
The pipeline to run.
start_date : pd.Timestamp
Start date of the computed matrix.
end_date : pd.Time... | def run_pipeline(self, pipeline, start_date, end_date):
"""
Compute a pipeline.
Parameters
----------
pipeline : zipline.pipeline.Pipeline
The pipeline to run.
start_date : pd.Timestamp
Start date of the computed matrix.
end_date : pd.Time... | [
"Compute",
"a",
"pipeline",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/engine.py#L265-L336 | [
"def",
"run_pipeline",
"(",
"self",
",",
"pipeline",
",",
"start_date",
",",
"end_date",
")",
":",
"# See notes at the top of this module for a description of the",
"# algorithm implemented here.",
"if",
"end_date",
"<",
"start_date",
":",
"raise",
"ValueError",
"(",
"\"s... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | SimplePipelineEngine._compute_root_mask | 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
Base s... | zipline/pipeline/engine.py | 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... | 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",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/engine.py#L356-L439 | [
"def",
"_compute_root_mask",
"(",
"self",
",",
"domain",
",",
"start_date",
",",
"end_date",
",",
"extra_rows",
")",
":",
"sessions",
"=",
"domain",
".",
"all_sessions",
"(",
")",
"if",
"start_date",
"not",
"in",
"sessions",
":",
"raise",
"ValueError",
"(",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | SimplePipelineEngine.compute_chunk | 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.
dates :... | zipline/pipeline/engine.py | def compute_chunk(self, graph, dates, sids, initial_workspace):
"""
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.Exe... | def compute_chunk(self, graph, dates, sids, initial_workspace):
"""
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.Exe... | [
"Compute",
"the",
"Pipeline",
"terms",
"in",
"the",
"graph",
"for",
"the",
"requested",
"start",
"and",
"end",
"dates",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/engine.py#L484-L606 | [
"def",
"compute_chunk",
"(",
"self",
",",
"graph",
",",
"dates",
",",
"sids",
",",
"initial_workspace",
")",
":",
"self",
".",
"_validate_compute_chunk_params",
"(",
"graph",
",",
"dates",
",",
"sids",
",",
"initial_workspace",
",",
")",
"get_loader",
"=",
"... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | SimplePipelineEngine._to_narrow | 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.
... | zipline/pipeline/engine.py | 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]]
... | 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",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/engine.py#L608-L672 | [
"def",
"_to_narrow",
"(",
"self",
",",
"terms",
",",
"data",
",",
"mask",
",",
"dates",
",",
"assets",
")",
":",
"if",
"not",
"mask",
".",
"any",
"(",
")",
":",
"# Manually handle the empty DataFrame case. This is a workaround",
"# to pandas failing to tz_localize a... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | SimplePipelineEngine._validate_compute_chunk_params | Verify that the values passed to compute_chunk are well-formed. | zipline/pipeline/engine.py | def _validate_compute_chunk_params(self,
graph,
dates,
sids,
initial_workspace):
"""
Verify that the values passed to compute_chunk are well-formed.... | 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",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/engine.py#L674-L752 | [
"def",
"_validate_compute_chunk_params",
"(",
"self",
",",
"graph",
",",
"dates",
",",
"sids",
",",
"initial_workspace",
")",
":",
"root",
"=",
"self",
".",
"_root_mask_term",
"clsname",
"=",
"type",
"(",
"self",
")",
".",
"__name__",
"# Writing this out explici... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | SimplePipelineEngine.resolve_domain | Resolve a concrete domain for ``pipeline``. | zipline/pipeline/engine.py | def resolve_domain(self, pipeline):
"""Resolve a concrete domain for ``pipeline``.
"""
domain = pipeline.domain(default=self._default_domain)
if domain is GENERIC:
raise ValueError(
"Unable to determine domain for Pipeline.\n"
"Pass domain=<des... | def resolve_domain(self, pipeline):
"""Resolve a concrete domain for ``pipeline``.
"""
domain = pipeline.domain(default=self._default_domain)
if domain is GENERIC:
raise ValueError(
"Unable to determine domain for Pipeline.\n"
"Pass domain=<des... | [
"Resolve",
"a",
"concrete",
"domain",
"for",
"pipeline",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/engine.py#L754-L764 | [
"def",
"resolve_domain",
"(",
"self",
",",
"pipeline",
")",
":",
"domain",
"=",
"pipeline",
".",
"domain",
"(",
"default",
"=",
"self",
".",
"_default_domain",
")",
"if",
"domain",
"is",
"GENERIC",
":",
"raise",
"ValueError",
"(",
"\"Unable to determine domain... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | require_initialized | Decorator for API methods that should only be called after
TradingAlgorithm.initialize. `exception` will be raised if the method is
called before initialize has completed.
Examples
--------
@require_initialized(SomeException("Don't do that!"))
def method(self):
# Do stuff that should o... | zipline/utils/api_support.py | def require_initialized(exception):
"""
Decorator for API methods that should only be called after
TradingAlgorithm.initialize. `exception` will be raised if the method is
called before initialize has completed.
Examples
--------
@require_initialized(SomeException("Don't do that!"))
de... | def require_initialized(exception):
"""
Decorator for API methods that should only be called after
TradingAlgorithm.initialize. `exception` will be raised if the method is
called before initialize has completed.
Examples
--------
@require_initialized(SomeException("Don't do that!"))
de... | [
"Decorator",
"for",
"API",
"methods",
"that",
"should",
"only",
"be",
"called",
"after",
"TradingAlgorithm",
".",
"initialize",
".",
"exception",
"will",
"be",
"raised",
"if",
"the",
"method",
"is",
"called",
"before",
"initialize",
"has",
"completed",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/api_support.py#L86-L105 | [
"def",
"require_initialized",
"(",
"exception",
")",
":",
"def",
"decorator",
"(",
"method",
")",
":",
"@",
"wraps",
"(",
"method",
")",
"def",
"wrapped_method",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
"... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | disallowed_in_before_trading_start | Decorator for API methods that cannot be called from within
TradingAlgorithm.before_trading_start. `exception` will be raised if the
method is called inside `before_trading_start`.
Examples
--------
@disallowed_in_before_trading_start(SomeException("Don't do that!"))
def method(self):
... | zipline/utils/api_support.py | def disallowed_in_before_trading_start(exception):
"""
Decorator for API methods that cannot be called from within
TradingAlgorithm.before_trading_start. `exception` will be raised if the
method is called inside `before_trading_start`.
Examples
--------
@disallowed_in_before_trading_start(... | def disallowed_in_before_trading_start(exception):
"""
Decorator for API methods that cannot be called from within
TradingAlgorithm.before_trading_start. `exception` will be raised if the
method is called inside `before_trading_start`.
Examples
--------
@disallowed_in_before_trading_start(... | [
"Decorator",
"for",
"API",
"methods",
"that",
"cannot",
"be",
"called",
"from",
"within",
"TradingAlgorithm",
".",
"before_trading_start",
".",
"exception",
"will",
"be",
"raised",
"if",
"the",
"method",
"is",
"called",
"inside",
"before_trading_start",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/api_support.py#L108-L127 | [
"def",
"disallowed_in_before_trading_start",
"(",
"exception",
")",
":",
"def",
"decorator",
"(",
"method",
")",
":",
"@",
"wraps",
"(",
"method",
")",
"def",
"wrapped_method",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | naive_grouped_rowwise_apply | 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 as arr... | zipline/lib/normalize.py | def naive_grouped_rowwise_apply(data,
group_labels,
func,
func_args=(),
out=None):
"""
Simple implementation of grouped row-wise function application.
Parameters
----------
... | 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",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/lib/normalize.py#L4-L51 | [
"def",
"naive_grouped_rowwise_apply",
"(",
"data",
",",
"group_labels",
",",
"func",
",",
"func_args",
"=",
"(",
")",
",",
"out",
"=",
"None",
")",
":",
"if",
"out",
"is",
"None",
":",
"out",
"=",
"np",
".",
"empty_like",
"(",
"data",
")",
"for",
"("... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | bulleted_list | Format a bulleted list of values.
Parameters
----------
items : sequence
The items to make a list.
indent : int, optional
The number of spaces to add before each bullet.
bullet_type : str, optional
The bullet type to use.
Returns
-------
formatted_list : str
... | zipline/utils/formatting.py | def bulleted_list(items, indent=0, bullet_type='-'):
"""Format a bulleted list of values.
Parameters
----------
items : sequence
The items to make a list.
indent : int, optional
The number of spaces to add before each bullet.
bullet_type : str, optional
The bullet type t... | def bulleted_list(items, indent=0, bullet_type='-'):
"""Format a bulleted list of values.
Parameters
----------
items : sequence
The items to make a list.
indent : int, optional
The number of spaces to add before each bullet.
bullet_type : str, optional
The bullet type t... | [
"Format",
"a",
"bulleted",
"list",
"of",
"values",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/formatting.py#L48-L66 | [
"def",
"bulleted_list",
"(",
"items",
",",
"indent",
"=",
"0",
",",
"bullet_type",
"=",
"'-'",
")",
":",
"format_string",
"=",
"' '",
"*",
"indent",
"+",
"bullet_type",
"+",
"' {}'",
"return",
"\"\\n\"",
".",
"join",
"(",
"map",
"(",
"format_string",
"."... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | make_rotating_equity_info | Create a DataFrame representing lifetimes of assets that are constantly
rotating in and out of existence.
Parameters
----------
num_assets : int
How many assets to create.
first_start : pd.Timestamp
The start date for the first asset.
frequency : str or pd.tseries.offsets.Offset... | zipline/assets/synthetic.py | def make_rotating_equity_info(num_assets,
first_start,
frequency,
periods_between_starts,
asset_lifetime,
exchange='TEST'):
"""
Create a DataFrame representing li... | def make_rotating_equity_info(num_assets,
first_start,
frequency,
periods_between_starts,
asset_lifetime,
exchange='TEST'):
"""
Create a DataFrame representing li... | [
"Create",
"a",
"DataFrame",
"representing",
"lifetimes",
"of",
"assets",
"that",
"are",
"constantly",
"rotating",
"in",
"and",
"out",
"of",
"existence",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/synthetic.py#L11-L59 | [
"def",
"make_rotating_equity_info",
"(",
"num_assets",
",",
"first_start",
",",
"frequency",
",",
"periods_between_starts",
",",
"asset_lifetime",
",",
"exchange",
"=",
"'TEST'",
")",
":",
"return",
"pd",
".",
"DataFrame",
"(",
"{",
"'symbol'",
":",
"[",
"chr",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | make_simple_equity_info | Create a DataFrame representing assets that exist for the full duration
between `start_date` and `end_date`.
Parameters
----------
sids : array-like of int
start_date : pd.Timestamp, optional
end_date : pd.Timestamp, optional
symbols : list, optional
Symbols to use for the assets.
... | zipline/assets/synthetic.py | def make_simple_equity_info(sids,
start_date,
end_date,
symbols=None,
names=None,
exchange='TEST'):
"""
Create a DataFrame representing assets that exist for the full durat... | def make_simple_equity_info(sids,
start_date,
end_date,
symbols=None,
names=None,
exchange='TEST'):
"""
Create a DataFrame representing assets that exist for the full durat... | [
"Create",
"a",
"DataFrame",
"representing",
"assets",
"that",
"exist",
"for",
"the",
"full",
"duration",
"between",
"start_date",
"and",
"end_date",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/synthetic.py#L62-L117 | [
"def",
"make_simple_equity_info",
"(",
"sids",
",",
"start_date",
",",
"end_date",
",",
"symbols",
"=",
"None",
",",
"names",
"=",
"None",
",",
"exchange",
"=",
"'TEST'",
")",
":",
"num_assets",
"=",
"len",
"(",
"sids",
")",
"if",
"symbols",
"is",
"None"... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | make_simple_multi_country_equity_info | Create a DataFrame representing assets that exist for the full duration
between `start_date` and `end_date`, from multiple countries. | zipline/assets/synthetic.py | def make_simple_multi_country_equity_info(countries_to_sids,
countries_to_exchanges,
start_date,
end_date):
"""Create a DataFrame representing assets that exist for the full duration
bet... | def make_simple_multi_country_equity_info(countries_to_sids,
countries_to_exchanges,
start_date,
end_date):
"""Create a DataFrame representing assets that exist for the full duration
bet... | [
"Create",
"a",
"DataFrame",
"representing",
"assets",
"that",
"exist",
"for",
"the",
"full",
"duration",
"between",
"start_date",
"and",
"end_date",
"from",
"multiple",
"countries",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/synthetic.py#L120-L154 | [
"def",
"make_simple_multi_country_equity_info",
"(",
"countries_to_sids",
",",
"countries_to_exchanges",
",",
"start_date",
",",
"end_date",
")",
":",
"sids",
"=",
"[",
"]",
"symbols",
"=",
"[",
"]",
"exchanges",
"=",
"[",
"]",
"for",
"country",
",",
"country_si... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | make_jagged_equity_info | Create a DataFrame representing assets that all begin at the same start
date, but have cascading end dates.
Parameters
----------
num_assets : int
How many assets to create.
start_date : pd.Timestamp
The start date for all the assets.
first_end : pd.Timestamp
The date at... | zipline/assets/synthetic.py | def make_jagged_equity_info(num_assets,
start_date,
first_end,
frequency,
periods_between_ends,
auto_close_delta):
"""
Create a DataFrame representing assets that all begin... | def make_jagged_equity_info(num_assets,
start_date,
first_end,
frequency,
periods_between_ends,
auto_close_delta):
"""
Create a DataFrame representing assets that all begin... | [
"Create",
"a",
"DataFrame",
"representing",
"assets",
"that",
"all",
"begin",
"at",
"the",
"same",
"start",
"date",
"but",
"have",
"cascading",
"end",
"dates",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/synthetic.py#L157-L204 | [
"def",
"make_jagged_equity_info",
"(",
"num_assets",
",",
"start_date",
",",
"first_end",
",",
"frequency",
",",
"periods_between_ends",
",",
"auto_close_delta",
")",
":",
"frame",
"=",
"pd",
".",
"DataFrame",
"(",
"{",
"'symbol'",
":",
"[",
"chr",
"(",
"ord",... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | make_future_info | Create a DataFrame representing futures for `root_symbols` during `year`.
Generates a contract per triple of (symbol, year, month) supplied to
`root_symbols`, `years`, and `month_codes`.
Parameters
----------
first_sid : int
The first sid to use for assigning sids to the created contracts.... | zipline/assets/synthetic.py | def make_future_info(first_sid,
root_symbols,
years,
notice_date_func,
expiration_date_func,
start_date_func,
month_codes=None,
multiplier=500):
"""
Create a DataFra... | def make_future_info(first_sid,
root_symbols,
years,
notice_date_func,
expiration_date_func,
start_date_func,
month_codes=None,
multiplier=500):
"""
Create a DataFra... | [
"Create",
"a",
"DataFrame",
"representing",
"futures",
"for",
"root_symbols",
"during",
"year",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/synthetic.py#L207-L281 | [
"def",
"make_future_info",
"(",
"first_sid",
",",
"root_symbols",
",",
"years",
",",
"notice_date_func",
",",
"expiration_date_func",
",",
"start_date_func",
",",
"month_codes",
"=",
"None",
",",
"multiplier",
"=",
"500",
")",
":",
"if",
"month_codes",
"is",
"No... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | make_commodity_future_info | Make futures testing data that simulates the notice/expiration date
behavior of physical commodities like oil.
Parameters
----------
first_sid : int
The first sid to use for assigning sids to the created contracts.
root_symbols : list[str]
A list of root symbols for which to create ... | zipline/assets/synthetic.py | def make_commodity_future_info(first_sid,
root_symbols,
years,
month_codes=None,
multiplier=500):
"""
Make futures testing data that simulates the notice/expiration date
behavior of ph... | def make_commodity_future_info(first_sid,
root_symbols,
years,
month_codes=None,
multiplier=500):
"""
Make futures testing data that simulates the notice/expiration date
behavior of ph... | [
"Make",
"futures",
"testing",
"data",
"that",
"simulates",
"the",
"notice",
"/",
"expiration",
"date",
"behavior",
"of",
"physical",
"commodities",
"like",
"oil",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/synthetic.py#L284-L327 | [
"def",
"make_commodity_future_info",
"(",
"first_sid",
",",
"root_symbols",
",",
"years",
",",
"month_codes",
"=",
"None",
",",
"multiplier",
"=",
"500",
")",
":",
"nineteen_days",
"=",
"pd",
".",
"Timedelta",
"(",
"days",
"=",
"19",
")",
"one_year",
"=",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | Classifier.eq | Construct a Filter returning True for asset/date pairs where the output
of ``self`` matches ``other``. | zipline/pipeline/classifiers/classifier.py | 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... | 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",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/classifiers/classifier.py#L83-L116 | [
"def",
"eq",
"(",
"self",
",",
"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 almost",
"# certainly not what the user wants.",
"if",
"other",
"==",
"self",
".",
"missing_val... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | Classifier.startswith | 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 pairs for ... | zipline/pipeline/classifiers/classifier.py | 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
... | 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",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/classifiers/classifier.py#L150-L169 | [
"def",
"startswith",
"(",
"self",
",",
"prefix",
")",
":",
"return",
"ArrayPredicate",
"(",
"term",
"=",
"self",
",",
"op",
"=",
"LabelArray",
".",
"startswith",
",",
"opargs",
"=",
"(",
"prefix",
",",
")",
",",
")"
] | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | Classifier.endswith | 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 pairs for wh... | zipline/pipeline/classifiers/classifier.py | 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... | 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",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/classifiers/classifier.py#L173-L192 | [
"def",
"endswith",
"(",
"self",
",",
"suffix",
")",
":",
"return",
"ArrayPredicate",
"(",
"term",
"=",
"self",
",",
"op",
"=",
"LabelArray",
".",
"endswith",
",",
"opargs",
"=",
"(",
"suffix",
",",
")",
",",
")"
] | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | Classifier.has_substring | 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 pairs for ... | zipline/pipeline/classifiers/classifier.py | 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
... | 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",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/classifiers/classifier.py#L196-L215 | [
"def",
"has_substring",
"(",
"self",
",",
"substring",
")",
":",
"return",
"ArrayPredicate",
"(",
"term",
"=",
"self",
",",
"op",
"=",
"LabelArray",
".",
"has_substring",
",",
"opargs",
"=",
"(",
"substring",
",",
")",
",",
")"
] | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | Classifier.matches | 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/date pair... | zipline/pipeline/classifiers/classifier.py | 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
... | 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",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/classifiers/classifier.py#L219-L242 | [
"def",
"matches",
"(",
"self",
",",
"pattern",
")",
":",
"return",
"ArrayPredicate",
"(",
"term",
"=",
"self",
",",
"op",
"=",
"LabelArray",
".",
"matches",
",",
"opargs",
"=",
"(",
"pattern",
",",
")",
",",
")"
] | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | Classifier.element_of | 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``
... | zipline/pipeline/classifiers/classifier.py | 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... | 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",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/classifiers/classifier.py#L264-L336 | [
"def",
"element_of",
"(",
"self",
",",
"choices",
")",
":",
"try",
":",
"choices",
"=",
"frozenset",
"(",
"choices",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"TypeError",
"(",
"\"Expected `choices` to be an iterable of hashable values,\"",
"\" but got {}... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | Classifier.to_workspace_value | 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`. | zipline/pipeline/classifiers/classifier.py | 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.... | 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",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/classifiers/classifier.py#L345-L371 | [
"def",
"to_workspace_value",
"(",
"self",
",",
"result",
",",
"assets",
")",
":",
"if",
"self",
".",
"dtype",
"==",
"int64_dtype",
":",
"return",
"super",
"(",
"Classifier",
",",
"self",
")",
".",
"to_workspace_value",
"(",
"result",
",",
"assets",
")",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | Classifier._to_integral | Convert an array produced by this classifier into an array of integer
labels and a missing value label. | zipline/pipeline/classifiers/classifier.py | 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... | 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",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/classifiers/classifier.py#L381-L399 | [
"def",
"_to_integral",
"(",
"self",
",",
"output_array",
")",
":",
"if",
"self",
".",
"dtype",
"==",
"int64_dtype",
":",
"group_labels",
"=",
"output_array",
"null_label",
"=",
"self",
".",
"missing_value",
"elif",
"self",
".",
"dtype",
"==",
"categorical_dtyp... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | CustomClassifier._allocate_output | Override the default array allocation to produce a LabelArray when we
have a string-like dtype. | zipline/pipeline/classifiers/classifier.py | 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,
... | 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",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/classifiers/classifier.py#L517-L531 | [
"def",
"_allocate_output",
"(",
"self",
",",
"windows",
",",
"shape",
")",
":",
"if",
"self",
".",
"dtype",
"==",
"int64_dtype",
":",
"return",
"super",
"(",
"CustomClassifier",
",",
"self",
")",
".",
"_allocate_output",
"(",
"windows",
",",
"shape",
",",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | verify_indices_all_unique | Check that all axes of a pandas object are unique.
Parameters
----------
obj : pd.Series / pd.DataFrame / pd.Panel
The object to validate.
Returns
-------
obj : pd.Series / pd.DataFrame / pd.Panel
The validated object, unchanged.
Raises
------
ValueError
If... | zipline/utils/input_validation.py | def verify_indices_all_unique(obj):
"""
Check that all axes of a pandas object are unique.
Parameters
----------
obj : pd.Series / pd.DataFrame / pd.Panel
The object to validate.
Returns
-------
obj : pd.Series / pd.DataFrame / pd.Panel
The validated object, unchanged.
... | def verify_indices_all_unique(obj):
"""
Check that all axes of a pandas object are unique.
Parameters
----------
obj : pd.Series / pd.DataFrame / pd.Panel
The object to validate.
Returns
-------
obj : pd.Series / pd.DataFrame / pd.Panel
The validated object, unchanged.
... | [
"Check",
"that",
"all",
"axes",
"of",
"a",
"pandas",
"object",
"are",
"unique",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/input_validation.py#L50-L86 | [
"def",
"verify_indices_all_unique",
"(",
"obj",
")",
":",
"axis_names",
"=",
"[",
"(",
"'index'",
",",
")",
",",
"# Series",
"(",
"'index'",
",",
"'columns'",
")",
",",
"# DataFrame",
"(",
"'items'",
",",
"'major_axis'",
",",
"'minor_axis'",
")",
"# Panel",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | optionally | Modify a preprocessor to explicitly allow `None`.
Parameters
----------
preprocessor : callable[callable, str, any -> any]
A preprocessor to delegate to when `arg is not None`.
Returns
-------
optional_preprocessor : callable[callable, str, any -> any]
A preprocessor that deleg... | zipline/utils/input_validation.py | def optionally(preprocessor):
"""Modify a preprocessor to explicitly allow `None`.
Parameters
----------
preprocessor : callable[callable, str, any -> any]
A preprocessor to delegate to when `arg is not None`.
Returns
-------
optional_preprocessor : callable[callable, str, any -> a... | def optionally(preprocessor):
"""Modify a preprocessor to explicitly allow `None`.
Parameters
----------
preprocessor : callable[callable, str, any -> any]
A preprocessor to delegate to when `arg is not None`.
Returns
-------
optional_preprocessor : callable[callable, str, any -> a... | [
"Modify",
"a",
"preprocessor",
"to",
"explicitly",
"allow",
"None",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/input_validation.py#L89-L126 | [
"def",
"optionally",
"(",
"preprocessor",
")",
":",
"@",
"wraps",
"(",
"preprocessor",
")",
"def",
"wrapper",
"(",
"func",
",",
"argname",
",",
"arg",
")",
":",
"return",
"arg",
"if",
"arg",
"is",
"None",
"else",
"preprocessor",
"(",
"func",
",",
"argn... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | ensure_dtype | Argument preprocessor that converts the input into a numpy dtype.
Examples
--------
>>> import numpy as np
>>> from zipline.utils.preprocess import preprocess
>>> @preprocess(dtype=ensure_dtype)
... def foo(dtype):
... return dtype
...
>>> foo(float)
dtype('float64') | zipline/utils/input_validation.py | def ensure_dtype(func, argname, arg):
"""
Argument preprocessor that converts the input into a numpy dtype.
Examples
--------
>>> import numpy as np
>>> from zipline.utils.preprocess import preprocess
>>> @preprocess(dtype=ensure_dtype)
... def foo(dtype):
... return dtype
.... | def ensure_dtype(func, argname, arg):
"""
Argument preprocessor that converts the input into a numpy dtype.
Examples
--------
>>> import numpy as np
>>> from zipline.utils.preprocess import preprocess
>>> @preprocess(dtype=ensure_dtype)
... def foo(dtype):
... return dtype
.... | [
"Argument",
"preprocessor",
"that",
"converts",
"the",
"input",
"into",
"a",
"numpy",
"dtype",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/input_validation.py#L143-L168 | [
"def",
"ensure_dtype",
"(",
"func",
",",
"argname",
",",
"arg",
")",
":",
"try",
":",
"return",
"dtype",
"(",
"arg",
")",
"except",
"TypeError",
":",
"raise",
"TypeError",
"(",
"\"{func}() couldn't convert argument \"",
"\"{argname}={arg!r} to a numpy dtype.\"",
"."... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | ensure_timezone | Argument preprocessor that converts the input into a tzinfo object.
Examples
--------
>>> from zipline.utils.preprocess import preprocess
>>> @preprocess(tz=ensure_timezone)
... def foo(tz):
... return tz
>>> foo('utc')
<UTC> | zipline/utils/input_validation.py | def ensure_timezone(func, argname, arg):
"""Argument preprocessor that converts the input into a tzinfo object.
Examples
--------
>>> from zipline.utils.preprocess import preprocess
>>> @preprocess(tz=ensure_timezone)
... def foo(tz):
... return tz
>>> foo('utc')
<UTC>
"""
... | def ensure_timezone(func, argname, arg):
"""Argument preprocessor that converts the input into a tzinfo object.
Examples
--------
>>> from zipline.utils.preprocess import preprocess
>>> @preprocess(tz=ensure_timezone)
... def foo(tz):
... return tz
>>> foo('utc')
<UTC>
"""
... | [
"Argument",
"preprocessor",
"that",
"converts",
"the",
"input",
"into",
"a",
"tzinfo",
"object",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/input_validation.py#L171-L195 | [
"def",
"ensure_timezone",
"(",
"func",
",",
"argname",
",",
"arg",
")",
":",
"if",
"isinstance",
"(",
"arg",
",",
"tzinfo",
")",
":",
"return",
"arg",
"if",
"isinstance",
"(",
"arg",
",",
"string_types",
")",
":",
"return",
"timezone",
"(",
"arg",
")",... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | ensure_timestamp | Argument preprocessor that converts the input into a pandas Timestamp
object.
Examples
--------
>>> from zipline.utils.preprocess import preprocess
>>> @preprocess(ts=ensure_timestamp)
... def foo(ts):
... return ts
>>> foo('2014-01-01')
Timestamp('2014-01-01 00:00:00') | zipline/utils/input_validation.py | def ensure_timestamp(func, argname, arg):
"""Argument preprocessor that converts the input into a pandas Timestamp
object.
Examples
--------
>>> from zipline.utils.preprocess import preprocess
>>> @preprocess(ts=ensure_timestamp)
... def foo(ts):
... return ts
>>> foo('2014-01-0... | def ensure_timestamp(func, argname, arg):
"""Argument preprocessor that converts the input into a pandas Timestamp
object.
Examples
--------
>>> from zipline.utils.preprocess import preprocess
>>> @preprocess(ts=ensure_timestamp)
... def foo(ts):
... return ts
>>> foo('2014-01-0... | [
"Argument",
"preprocessor",
"that",
"converts",
"the",
"input",
"into",
"a",
"pandas",
"Timestamp",
"object",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/input_validation.py#L198-L224 | [
"def",
"ensure_timestamp",
"(",
"func",
",",
"argname",
",",
"arg",
")",
":",
"try",
":",
"return",
"pd",
".",
"Timestamp",
"(",
"arg",
")",
"except",
"ValueError",
"as",
"e",
":",
"raise",
"TypeError",
"(",
"\"{func}() couldn't convert argument \"",
"\"{argna... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | expect_dtypes | Preprocessing decorator that verifies inputs have expected numpy dtypes.
Examples
--------
>>> from numpy import dtype, arange, int8, float64
>>> @expect_dtypes(x=dtype(int8))
... def foo(x, y):
... return x, y
...
>>> foo(arange(3, dtype=int8), 'foo')
(array([0, 1, 2], dtype=int... | zipline/utils/input_validation.py | def expect_dtypes(__funcname=_qualified_name, **named):
"""
Preprocessing decorator that verifies inputs have expected numpy dtypes.
Examples
--------
>>> from numpy import dtype, arange, int8, float64
>>> @expect_dtypes(x=dtype(int8))
... def foo(x, y):
... return x, y
...
>... | def expect_dtypes(__funcname=_qualified_name, **named):
"""
Preprocessing decorator that verifies inputs have expected numpy dtypes.
Examples
--------
>>> from numpy import dtype, arange, int8, float64
>>> @expect_dtypes(x=dtype(int8))
... def foo(x, y):
... return x, y
...
>... | [
"Preprocessing",
"decorator",
"that",
"verifies",
"inputs",
"have",
"expected",
"numpy",
"dtypes",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/input_validation.py#L227-L292 | [
"def",
"expect_dtypes",
"(",
"__funcname",
"=",
"_qualified_name",
",",
"*",
"*",
"named",
")",
":",
"for",
"name",
",",
"type_",
"in",
"iteritems",
"(",
"named",
")",
":",
"if",
"not",
"isinstance",
"(",
"type_",
",",
"(",
"dtype",
",",
"tuple",
")",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | expect_kinds | Preprocessing decorator that verifies inputs have expected dtype kinds.
Examples
--------
>>> from numpy import int64, int32, float32
>>> @expect_kinds(x='i')
... def foo(x):
... return x
...
>>> foo(int64(2))
2
>>> foo(int32(2))
2
>>> foo(float32(2)) # doctest: +NOR... | zipline/utils/input_validation.py | def expect_kinds(**named):
"""
Preprocessing decorator that verifies inputs have expected dtype kinds.
Examples
--------
>>> from numpy import int64, int32, float32
>>> @expect_kinds(x='i')
... def foo(x):
... return x
...
>>> foo(int64(2))
2
>>> foo(int32(2))
2
... | def expect_kinds(**named):
"""
Preprocessing decorator that verifies inputs have expected dtype kinds.
Examples
--------
>>> from numpy import int64, int32, float32
>>> @expect_kinds(x='i')
... def foo(x):
... return x
...
>>> foo(int64(2))
2
>>> foo(int32(2))
2
... | [
"Preprocessing",
"decorator",
"that",
"verifies",
"inputs",
"have",
"expected",
"dtype",
"kinds",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/input_validation.py#L295-L355 | [
"def",
"expect_kinds",
"(",
"*",
"*",
"named",
")",
":",
"for",
"name",
",",
"kind",
"in",
"iteritems",
"(",
"named",
")",
":",
"if",
"not",
"isinstance",
"(",
"kind",
",",
"(",
"str",
",",
"tuple",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"expe... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | expect_types | Preprocessing decorator that verifies inputs have expected types.
Examples
--------
>>> @expect_types(x=int, y=str)
... def foo(x, y):
... return x, y
...
>>> foo(2, '3')
(2, '3')
>>> foo(2.0, '3') # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS
Traceback (most recent call last):... | zipline/utils/input_validation.py | def expect_types(__funcname=_qualified_name, **named):
"""
Preprocessing decorator that verifies inputs have expected types.
Examples
--------
>>> @expect_types(x=int, y=str)
... def foo(x, y):
... return x, y
...
>>> foo(2, '3')
(2, '3')
>>> foo(2.0, '3') # doctest: +NO... | def expect_types(__funcname=_qualified_name, **named):
"""
Preprocessing decorator that verifies inputs have expected types.
Examples
--------
>>> @expect_types(x=int, y=str)
... def foo(x, y):
... return x, y
...
>>> foo(2, '3')
(2, '3')
>>> foo(2.0, '3') # doctest: +NO... | [
"Preprocessing",
"decorator",
"that",
"verifies",
"inputs",
"have",
"expected",
"types",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/input_validation.py#L358-L413 | [
"def",
"expect_types",
"(",
"__funcname",
"=",
"_qualified_name",
",",
"*",
"*",
"named",
")",
":",
"for",
"name",
",",
"type_",
"in",
"iteritems",
"(",
"named",
")",
":",
"if",
"not",
"isinstance",
"(",
"type_",
",",
"(",
"type",
",",
"tuple",
")",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | make_check | Factory for making preprocessing functions that check a predicate on the
input value.
Parameters
----------
exc_type : Exception
The exception type to raise if the predicate fails.
template : str
A template string to use to create error messages.
Should have %-style named te... | zipline/utils/input_validation.py | def make_check(exc_type, template, pred, actual, funcname):
"""
Factory for making preprocessing functions that check a predicate on the
input value.
Parameters
----------
exc_type : Exception
The exception type to raise if the predicate fails.
template : str
A template stri... | def make_check(exc_type, template, pred, actual, funcname):
"""
Factory for making preprocessing functions that check a predicate on the
input value.
Parameters
----------
exc_type : Exception
The exception type to raise if the predicate fails.
template : str
A template stri... | [
"Factory",
"for",
"making",
"preprocessing",
"functions",
"that",
"check",
"a",
"predicate",
"on",
"the",
"input",
"value",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/input_validation.py#L416-L457 | [
"def",
"make_check",
"(",
"exc_type",
",",
"template",
",",
"pred",
",",
"actual",
",",
"funcname",
")",
":",
"if",
"isinstance",
"(",
"funcname",
",",
"str",
")",
":",
"def",
"get_funcname",
"(",
"_",
")",
":",
"return",
"funcname",
"else",
":",
"get_... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | expect_element | Preprocessing decorator that verifies inputs are elements of some
expected collection.
Examples
--------
>>> @expect_element(x=('a', 'b'))
... def foo(x):
... return x.upper()
...
>>> foo('a')
'A'
>>> foo('b')
'B'
>>> foo('c') # doctest: +NORMALIZE_WHITESPACE +ELLIPS... | zipline/utils/input_validation.py | def expect_element(__funcname=_qualified_name, **named):
"""
Preprocessing decorator that verifies inputs are elements of some
expected collection.
Examples
--------
>>> @expect_element(x=('a', 'b'))
... def foo(x):
... return x.upper()
...
>>> foo('a')
'A'
>>> foo('b... | def expect_element(__funcname=_qualified_name, **named):
"""
Preprocessing decorator that verifies inputs are elements of some
expected collection.
Examples
--------
>>> @expect_element(x=('a', 'b'))
... def foo(x):
... return x.upper()
...
>>> foo('a')
'A'
>>> foo('b... | [
"Preprocessing",
"decorator",
"that",
"verifies",
"inputs",
"are",
"elements",
"of",
"some",
"expected",
"collection",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/input_validation.py#L484-L535 | [
"def",
"expect_element",
"(",
"__funcname",
"=",
"_qualified_name",
",",
"*",
"*",
"named",
")",
":",
"def",
"_expect_element",
"(",
"collection",
")",
":",
"if",
"isinstance",
"(",
"collection",
",",
"(",
"set",
",",
"frozenset",
")",
")",
":",
"# Special... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | expect_bounded | Preprocessing decorator verifying that inputs fall INCLUSIVELY between
bounds.
Bounds should be passed as a pair of ``(min_value, max_value)``.
``None`` may be passed as ``min_value`` or ``max_value`` to signify that
the input is only bounded above or below.
Examples
--------
>>> @expect_... | zipline/utils/input_validation.py | def expect_bounded(__funcname=_qualified_name, **named):
"""
Preprocessing decorator verifying that inputs fall INCLUSIVELY between
bounds.
Bounds should be passed as a pair of ``(min_value, max_value)``.
``None`` may be passed as ``min_value`` or ``max_value`` to signify that
the input is onl... | def expect_bounded(__funcname=_qualified_name, **named):
"""
Preprocessing decorator verifying that inputs fall INCLUSIVELY between
bounds.
Bounds should be passed as a pair of ``(min_value, max_value)``.
``None`` may be passed as ``min_value`` or ``max_value`` to signify that
the input is onl... | [
"Preprocessing",
"decorator",
"verifying",
"that",
"inputs",
"fall",
"INCLUSIVELY",
"between",
"bounds",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/input_validation.py#L538-L614 | [
"def",
"expect_bounded",
"(",
"__funcname",
"=",
"_qualified_name",
",",
"*",
"*",
"named",
")",
":",
"def",
"_make_bounded_check",
"(",
"bounds",
")",
":",
"(",
"lower",
",",
"upper",
")",
"=",
"bounds",
"if",
"lower",
"is",
"None",
":",
"def",
"should_... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | expect_dimensions | Preprocessing decorator that verifies inputs are numpy arrays with a
specific dimensionality.
Examples
--------
>>> from numpy import array
>>> @expect_dimensions(x=1, y=2)
... def foo(x, y):
... return x[0] + y[0, 0]
...
>>> foo(array([1, 1]), array([[1, 1], [2, 2]]))
2
... | zipline/utils/input_validation.py | def expect_dimensions(__funcname=_qualified_name, **dimensions):
"""
Preprocessing decorator that verifies inputs are numpy arrays with a
specific dimensionality.
Examples
--------
>>> from numpy import array
>>> @expect_dimensions(x=1, y=2)
... def foo(x, y):
... return x[0] + y... | def expect_dimensions(__funcname=_qualified_name, **dimensions):
"""
Preprocessing decorator that verifies inputs are numpy arrays with a
specific dimensionality.
Examples
--------
>>> from numpy import array
>>> @expect_dimensions(x=1, y=2)
... def foo(x, y):
... return x[0] + y... | [
"Preprocessing",
"decorator",
"that",
"verifies",
"inputs",
"are",
"numpy",
"arrays",
"with",
"a",
"specific",
"dimensionality",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/input_validation.py#L717-L764 | [
"def",
"expect_dimensions",
"(",
"__funcname",
"=",
"_qualified_name",
",",
"*",
"*",
"dimensions",
")",
":",
"if",
"isinstance",
"(",
"__funcname",
",",
"str",
")",
":",
"def",
"get_funcname",
"(",
"_",
")",
":",
"return",
"__funcname",
"else",
":",
"get_... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | coerce | A preprocessing decorator that coerces inputs of a given type by passing
them to a callable.
Parameters
----------
from : type or tuple or types
Inputs types on which to call ``to``.
to : function
Coercion function to call on inputs.
**to_kwargs
Additional keywords to fo... | zipline/utils/input_validation.py | def coerce(from_, to, **to_kwargs):
"""
A preprocessing decorator that coerces inputs of a given type by passing
them to a callable.
Parameters
----------
from : type or tuple or types
Inputs types on which to call ``to``.
to : function
Coercion function to call on inputs.
... | def coerce(from_, to, **to_kwargs):
"""
A preprocessing decorator that coerces inputs of a given type by passing
them to a callable.
Parameters
----------
from : type or tuple or types
Inputs types on which to call ``to``.
to : function
Coercion function to call on inputs.
... | [
"A",
"preprocessing",
"decorator",
"that",
"coerces",
"inputs",
"of",
"a",
"given",
"type",
"by",
"passing",
"them",
"to",
"a",
"callable",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/input_validation.py#L767-L801 | [
"def",
"coerce",
"(",
"from_",
",",
"to",
",",
"*",
"*",
"to_kwargs",
")",
":",
"def",
"preprocessor",
"(",
"func",
",",
"argname",
",",
"arg",
")",
":",
"if",
"isinstance",
"(",
"arg",
",",
"from_",
")",
":",
"return",
"to",
"(",
"arg",
",",
"*"... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | coerce_types | Preprocessing decorator that applies type coercions.
Parameters
----------
**kwargs : dict[str -> (type, callable)]
Keyword arguments mapping function parameter names to pairs of
(from_type, to_type).
Examples
--------
>>> @coerce_types(x=(float, int), y=(int, str))
... d... | zipline/utils/input_validation.py | def coerce_types(**kwargs):
"""
Preprocessing decorator that applies type coercions.
Parameters
----------
**kwargs : dict[str -> (type, callable)]
Keyword arguments mapping function parameter names to pairs of
(from_type, to_type).
Examples
--------
>>> @coerce_types... | def coerce_types(**kwargs):
"""
Preprocessing decorator that applies type coercions.
Parameters
----------
**kwargs : dict[str -> (type, callable)]
Keyword arguments mapping function parameter names to pairs of
(from_type, to_type).
Examples
--------
>>> @coerce_types... | [
"Preprocessing",
"decorator",
"that",
"applies",
"type",
"coercions",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/input_validation.py#L804-L826 | [
"def",
"coerce_types",
"(",
"*",
"*",
"kwargs",
")",
":",
"def",
"_coerce",
"(",
"types",
")",
":",
"return",
"coerce",
"(",
"*",
"types",
")",
"return",
"preprocess",
"(",
"*",
"*",
"valmap",
"(",
"_coerce",
",",
"kwargs",
")",
")"
] | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | validate_keys | Validate that a dictionary has an expected set of keys. | zipline/utils/input_validation.py | def validate_keys(dict_, expected, funcname):
"""Validate that a dictionary has an expected set of keys.
"""
expected = set(expected)
received = set(dict_)
missing = expected - received
if missing:
raise ValueError(
"Missing keys in {}:\n"
"Expected Keys: {}\n"
... | def validate_keys(dict_, expected, funcname):
"""Validate that a dictionary has an expected set of keys.
"""
expected = set(expected)
received = set(dict_)
missing = expected - received
if missing:
raise ValueError(
"Missing keys in {}:\n"
"Expected Keys: {}\n"
... | [
"Validate",
"that",
"a",
"dictionary",
"has",
"an",
"expected",
"set",
"of",
"keys",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/input_validation.py#L847-L875 | [
"def",
"validate_keys",
"(",
"dict_",
",",
"expected",
",",
"funcname",
")",
":",
"expected",
"=",
"set",
"(",
"expected",
")",
"received",
"=",
"set",
"(",
"dict_",
")",
"missing",
"=",
"expected",
"-",
"received",
"if",
"missing",
":",
"raise",
"ValueE... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | enum | Construct a new enum object.
Parameters
----------
*options : iterable of str
The names of the fields for the enum.
Returns
-------
enum
A new enum collection.
Examples
--------
>>> e = enum('a', 'b', 'c')
>>> e
<enum: ('a', 'b', 'c')>
>>> e.a
0
... | zipline/utils/enum.py | def enum(option, *options):
"""
Construct a new enum object.
Parameters
----------
*options : iterable of str
The names of the fields for the enum.
Returns
-------
enum
A new enum collection.
Examples
--------
>>> e = enum('a', 'b', 'c')
>>> e
<enum... | def enum(option, *options):
"""
Construct a new enum object.
Parameters
----------
*options : iterable of str
The names of the fields for the enum.
Returns
-------
enum
A new enum collection.
Examples
--------
>>> e = enum('a', 'b', 'c')
>>> e
<enum... | [
"Construct",
"a",
"new",
"enum",
"object",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/enum.py#L48-L114 | [
"def",
"enum",
"(",
"option",
",",
"*",
"options",
")",
":",
"options",
"=",
"(",
"option",
",",
")",
"+",
"options",
"rangeob",
"=",
"range",
"(",
"len",
"(",
"options",
")",
")",
"try",
":",
"inttype",
"=",
"_inttypes",
"[",
"int",
"(",
"np",
"... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | RollingPanel.oldest_frame | Get the oldest frame in the panel. | zipline/utils/data.py | def oldest_frame(self, raw=False):
"""
Get the oldest frame in the panel.
"""
if raw:
return self.buffer.values[:, self._start_index, :]
return self.buffer.iloc[:, self._start_index, :] | def oldest_frame(self, raw=False):
"""
Get the oldest frame in the panel.
"""
if raw:
return self.buffer.values[:, self._start_index, :]
return self.buffer.iloc[:, self._start_index, :] | [
"Get",
"the",
"oldest",
"frame",
"in",
"the",
"panel",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/data.py#L82-L88 | [
"def",
"oldest_frame",
"(",
"self",
",",
"raw",
"=",
"False",
")",
":",
"if",
"raw",
":",
"return",
"self",
".",
"buffer",
".",
"values",
"[",
":",
",",
"self",
".",
"_start_index",
",",
":",
"]",
"return",
"self",
".",
"buffer",
".",
"iloc",
"[",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | RollingPanel.extend_back | Resizes the buffer to hold a new window with a new cap_multiple.
If cap_multiple is None, then the old cap_multiple is used. | zipline/utils/data.py | def extend_back(self, missing_dts):
"""
Resizes the buffer to hold a new window with a new cap_multiple.
If cap_multiple is None, then the old cap_multiple is used.
"""
delta = len(missing_dts)
if not delta:
raise ValueError(
'missing_dts must... | def extend_back(self, missing_dts):
"""
Resizes the buffer to hold a new window with a new cap_multiple.
If cap_multiple is None, then the old cap_multiple is used.
"""
delta = len(missing_dts)
if not delta:
raise ValueError(
'missing_dts must... | [
"Resizes",
"the",
"buffer",
"to",
"hold",
"a",
"new",
"window",
"with",
"a",
"new",
"cap_multiple",
".",
"If",
"cap_multiple",
"is",
"None",
"then",
"the",
"old",
"cap_multiple",
"is",
"used",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/data.py#L107-L148 | [
"def",
"extend_back",
"(",
"self",
",",
"missing_dts",
")",
":",
"delta",
"=",
"len",
"(",
"missing_dts",
")",
"if",
"not",
"delta",
":",
"raise",
"ValueError",
"(",
"'missing_dts must be a non-empty index'",
",",
")",
"self",
".",
"_window",
"+=",
"delta",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | RollingPanel.get_current | Get a Panel that is the current data in view. It is not safe to persist
these objects because internal data might change | zipline/utils/data.py | def get_current(self, item=None, raw=False, start=None, end=None):
"""
Get a Panel that is the current data in view. It is not safe to persist
these objects because internal data might change
"""
item_indexer = slice(None)
if item:
item_indexer = self.items.ge... | def get_current(self, item=None, raw=False, start=None, end=None):
"""
Get a Panel that is the current data in view. It is not safe to persist
these objects because internal data might change
"""
item_indexer = slice(None)
if item:
item_indexer = self.items.ge... | [
"Get",
"a",
"Panel",
"that",
"is",
"the",
"current",
"data",
"in",
"view",
".",
"It",
"is",
"not",
"safe",
"to",
"persist",
"these",
"objects",
"because",
"internal",
"data",
"might",
"change"
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/data.py#L165-L214 | [
"def",
"get_current",
"(",
"self",
",",
"item",
"=",
"None",
",",
"raw",
"=",
"False",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"item_indexer",
"=",
"slice",
"(",
"None",
")",
"if",
"item",
":",
"item_indexer",
"=",
"self",
"."... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | RollingPanel.set_current | Set the values stored in our current in-view data to be values of the
passed panel. The passed panel must have the same indices as the panel
that would be returned by self.get_current. | zipline/utils/data.py | def set_current(self, panel):
"""
Set the values stored in our current in-view data to be values of the
passed panel. The passed panel must have the same indices as the panel
that would be returned by self.get_current.
"""
where = slice(self._start_index, self._pos)
... | def set_current(self, panel):
"""
Set the values stored in our current in-view data to be values of the
passed panel. The passed panel must have the same indices as the panel
that would be returned by self.get_current.
"""
where = slice(self._start_index, self._pos)
... | [
"Set",
"the",
"values",
"stored",
"in",
"our",
"current",
"in",
"-",
"view",
"data",
"to",
"be",
"values",
"of",
"the",
"passed",
"panel",
".",
"The",
"passed",
"panel",
"must",
"have",
"the",
"same",
"indices",
"as",
"the",
"panel",
"that",
"would",
"... | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/data.py#L216-L223 | [
"def",
"set_current",
"(",
"self",
",",
"panel",
")",
":",
"where",
"=",
"slice",
"(",
"self",
".",
"_start_index",
",",
"self",
".",
"_pos",
")",
"self",
".",
"buffer",
".",
"values",
"[",
":",
",",
"where",
",",
":",
"]",
"=",
"panel",
".",
"va... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | RollingPanel._roll_data | Roll window worth of data up to position zero.
Save the effort of having to expensively roll at each iteration | zipline/utils/data.py | def _roll_data(self):
"""
Roll window worth of data up to position zero.
Save the effort of having to expensively roll at each iteration
"""
self.buffer.values[:, :self._window, :] = \
self.buffer.values[:, -self._window:, :]
self.date_buf[:self._window] = se... | def _roll_data(self):
"""
Roll window worth of data up to position zero.
Save the effort of having to expensively roll at each iteration
"""
self.buffer.values[:, :self._window, :] = \
self.buffer.values[:, -self._window:, :]
self.date_buf[:self._window] = se... | [
"Roll",
"window",
"worth",
"of",
"data",
"up",
"to",
"position",
"zero",
".",
"Save",
"the",
"effort",
"of",
"having",
"to",
"expensively",
"roll",
"at",
"each",
"iteration"
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/data.py#L229-L238 | [
"def",
"_roll_data",
"(",
"self",
")",
":",
"self",
".",
"buffer",
".",
"values",
"[",
":",
",",
":",
"self",
".",
"_window",
",",
":",
"]",
"=",
"self",
".",
"buffer",
".",
"values",
"[",
":",
",",
"-",
"self",
".",
"_window",
":",
",",
":",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | MutableIndexRollingPanel.oldest_frame | Get the oldest frame in the panel. | zipline/utils/data.py | def oldest_frame(self, raw=False):
"""
Get the oldest frame in the panel.
"""
if raw:
return self.buffer.values[:, self._oldest_frame_idx(), :]
return self.buffer.iloc[:, self._oldest_frame_idx(), :] | def oldest_frame(self, raw=False):
"""
Get the oldest frame in the panel.
"""
if raw:
return self.buffer.values[:, self._oldest_frame_idx(), :]
return self.buffer.iloc[:, self._oldest_frame_idx(), :] | [
"Get",
"the",
"oldest",
"frame",
"in",
"the",
"panel",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/data.py#L273-L279 | [
"def",
"oldest_frame",
"(",
"self",
",",
"raw",
"=",
"False",
")",
":",
"if",
"raw",
":",
"return",
"self",
".",
"buffer",
".",
"values",
"[",
":",
",",
"self",
".",
"_oldest_frame_idx",
"(",
")",
",",
":",
"]",
"return",
"self",
".",
"buffer",
"."... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | MutableIndexRollingPanel.get_current | Get a Panel that is the current data in view. It is not safe to persist
these objects because internal data might change | zipline/utils/data.py | def get_current(self):
"""
Get a Panel that is the current data in view. It is not safe to persist
these objects because internal data might change
"""
where = slice(self._oldest_frame_idx(), self._pos)
major_axis = pd.DatetimeIndex(deepcopy(self.date_buf[where]), tz='ut... | def get_current(self):
"""
Get a Panel that is the current data in view. It is not safe to persist
these objects because internal data might change
"""
where = slice(self._oldest_frame_idx(), self._pos)
major_axis = pd.DatetimeIndex(deepcopy(self.date_buf[where]), tz='ut... | [
"Get",
"a",
"Panel",
"that",
"is",
"the",
"current",
"data",
"in",
"view",
".",
"It",
"is",
"not",
"safe",
"to",
"persist",
"these",
"objects",
"because",
"internal",
"data",
"might",
"change"
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/data.py#L294-L303 | [
"def",
"get_current",
"(",
"self",
")",
":",
"where",
"=",
"slice",
"(",
"self",
".",
"_oldest_frame_idx",
"(",
")",
",",
"self",
".",
"_pos",
")",
"major_axis",
"=",
"pd",
".",
"DatetimeIndex",
"(",
"deepcopy",
"(",
"self",
".",
"date_buf",
"[",
"wher... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | Order.check_triggers | Update internal state based on price triggers and the
trade event's price. | zipline/finance/order.py | def check_triggers(self, price, dt):
"""
Update internal state based on price triggers and the
trade event's price.
"""
stop_reached, limit_reached, sl_stop_reached = \
self.check_order_triggers(price)
if (stop_reached, limit_reached) \
!= (sel... | def check_triggers(self, price, dt):
"""
Update internal state based on price triggers and the
trade event's price.
"""
stop_reached, limit_reached, sl_stop_reached = \
self.check_order_triggers(price)
if (stop_reached, limit_reached) \
!= (sel... | [
"Update",
"internal",
"state",
"based",
"on",
"price",
"triggers",
"and",
"the",
"trade",
"event",
"s",
"price",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/order.py#L108-L122 | [
"def",
"check_triggers",
"(",
"self",
",",
"price",
",",
"dt",
")",
":",
"stop_reached",
",",
"limit_reached",
",",
"sl_stop_reached",
"=",
"self",
".",
"check_order_triggers",
"(",
"price",
")",
"if",
"(",
"stop_reached",
",",
"limit_reached",
")",
"!=",
"(... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | Order.check_order_triggers | Given an order and a trade event, return a tuple of
(stop_reached, limit_reached).
For market orders, will return (False, False).
For stop orders, limit_reached will always be False.
For limit orders, stop_reached will always be False.
For stop limit orders a Boolean is returned ... | zipline/finance/order.py | def check_order_triggers(self, current_price):
"""
Given an order and a trade event, return a tuple of
(stop_reached, limit_reached).
For market orders, will return (False, False).
For stop orders, limit_reached will always be False.
For limit orders, stop_reached will al... | def check_order_triggers(self, current_price):
"""
Given an order and a trade event, return a tuple of
(stop_reached, limit_reached).
For market orders, will return (False, False).
For stop orders, limit_reached will always be False.
For limit orders, stop_reached will al... | [
"Given",
"an",
"order",
"and",
"a",
"trade",
"event",
"return",
"a",
"tuple",
"of",
"(",
"stop_reached",
"limit_reached",
")",
".",
"For",
"market",
"orders",
"will",
"return",
"(",
"False",
"False",
")",
".",
"For",
"stop",
"orders",
"limit_reached",
"wil... | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/order.py#L124-L181 | [
"def",
"check_order_triggers",
"(",
"self",
",",
"current_price",
")",
":",
"if",
"self",
".",
"triggered",
":",
"return",
"(",
"self",
".",
"stop_reached",
",",
"self",
".",
"limit_reached",
",",
"False",
")",
"stop_reached",
"=",
"False",
"limit_reached",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | Order.triggered | For a market order, True.
For a stop order, True IFF stop_reached.
For a limit order, True IFF limit_reached. | zipline/finance/order.py | def triggered(self):
"""
For a market order, True.
For a stop order, True IFF stop_reached.
For a limit order, True IFF limit_reached.
"""
if self.stop is not None and not self.stop_reached:
return False
if self.limit is not None and not self.limit_re... | def triggered(self):
"""
For a market order, True.
For a stop order, True IFF stop_reached.
For a limit order, True IFF limit_reached.
"""
if self.stop is not None and not self.stop_reached:
return False
if self.limit is not None and not self.limit_re... | [
"For",
"a",
"market",
"order",
"True",
".",
"For",
"a",
"stop",
"order",
"True",
"IFF",
"stop_reached",
".",
"For",
"a",
"limit",
"order",
"True",
"IFF",
"limit_reached",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/order.py#L230-L242 | [
"def",
"triggered",
"(",
"self",
")",
":",
"if",
"self",
".",
"stop",
"is",
"not",
"None",
"and",
"not",
"self",
".",
"stop_reached",
":",
"return",
"False",
"if",
"self",
".",
"limit",
"is",
"not",
"None",
"and",
"not",
"self",
".",
"limit_reached",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | setup | Lives in zipline.__init__ for doctests. | zipline/__init__.py | def setup(self,
np=np,
numpy_version=numpy_version,
StrictVersion=StrictVersion,
new_pandas=new_pandas):
"""Lives in zipline.__init__ for doctests."""
if numpy_version >= StrictVersion('1.14'):
self.old_opts = np.get_printoptions()
np.set_printoptions(leg... | def setup(self,
np=np,
numpy_version=numpy_version,
StrictVersion=StrictVersion,
new_pandas=new_pandas):
"""Lives in zipline.__init__ for doctests."""
if numpy_version >= StrictVersion('1.14'):
self.old_opts = np.get_printoptions()
np.set_printoptions(leg... | [
"Lives",
"in",
"zipline",
".",
"__init__",
"for",
"doctests",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/__init__.py#L93-L111 | [
"def",
"setup",
"(",
"self",
",",
"np",
"=",
"np",
",",
"numpy_version",
"=",
"numpy_version",
",",
"StrictVersion",
"=",
"StrictVersion",
",",
"new_pandas",
"=",
"new_pandas",
")",
":",
"if",
"numpy_version",
">=",
"StrictVersion",
"(",
"'1.14'",
")",
":",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | teardown | Lives in zipline.__init__ for doctests. | zipline/__init__.py | def teardown(self, np=np):
"""Lives in zipline.__init__ for doctests."""
if self.old_err is not None:
np.seterr(**self.old_err)
if self.old_opts is not None:
np.set_printoptions(**self.old_opts) | def teardown(self, np=np):
"""Lives in zipline.__init__ for doctests."""
if self.old_err is not None:
np.seterr(**self.old_err)
if self.old_opts is not None:
np.set_printoptions(**self.old_opts) | [
"Lives",
"in",
"zipline",
".",
"__init__",
"for",
"doctests",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/__init__.py#L114-L121 | [
"def",
"teardown",
"(",
"self",
",",
"np",
"=",
"np",
")",
":",
"if",
"self",
".",
"old_err",
"is",
"not",
"None",
":",
"np",
".",
"seterr",
"(",
"*",
"*",
"self",
".",
"old_err",
")",
"if",
"self",
".",
"old_opts",
"is",
"not",
"None",
":",
"n... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | hash_args | Define a unique string for any set of representable args. | zipline/gens/utils.py | 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... | 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",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/gens/utils.py#L27-L36 | [
"def",
"hash_args",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"arg_string",
"=",
"'_'",
".",
"join",
"(",
"[",
"str",
"(",
"arg",
")",
"for",
"arg",
"in",
"args",
"]",
")",
"kwarg_string",
"=",
"'_'",
".",
"join",
"(",
"[",
"str",
"(... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | assert_datasource_protocol | Assert that an event meets the protocol for datasource outputs. | zipline/gens/utils.py | 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... | 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",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/gens/utils.py#L39-L47 | [
"def",
"assert_datasource_protocol",
"(",
"event",
")",
":",
"assert",
"event",
".",
"type",
"in",
"DATASOURCE_TYPE",
"# Done packets have no dt.",
"if",
"not",
"event",
".",
"type",
"==",
"DATASOURCE_TYPE",
".",
"DONE",
":",
"assert",
"isinstance",
"(",
"event",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | assert_trade_protocol | Assert that an event meets the protocol for datasource TRADE outputs. | zipline/gens/utils.py | 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... | 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",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/gens/utils.py#L50-L57 | [
"def",
"assert_trade_protocol",
"(",
"event",
")",
":",
"assert_datasource_protocol",
"(",
"event",
")",
"assert",
"event",
".",
"type",
"==",
"DATASOURCE_TYPE",
".",
"TRADE",
"assert",
"isinstance",
"(",
"event",
".",
"price",
",",
"numbers",
".",
"Real",
")"... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | date_sorted_sources | Takes an iterable of sources, generating namestrings and
piping their output into date_sort. | zipline/gens/composites.py | 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 | 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",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/gens/composites.py#L24-L33 | [
"def",
"date_sorted_sources",
"(",
"*",
"sources",
")",
":",
"sorted_stream",
"=",
"heapq",
".",
"merge",
"(",
"*",
"(",
"_decorate_source",
"(",
"s",
")",
"for",
"s",
"in",
"sources",
")",
")",
"# Strip out key decoration",
"for",
"_",
",",
"message",
"in... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | create_daily_trade_source | creates trade_count trades for each sid in sids list.
first trade will be on sim_params.start_session, and daily
thereafter for each sid. Thus, two sids should result in two trades per
day. | zipline/utils/factory.py | def create_daily_trade_source(sids,
sim_params,
asset_finder,
trading_calendar):
"""
creates trade_count trades for each sid in sids list.
first trade will be on sim_params.start_session, and daily
thereafter for e... | def create_daily_trade_source(sids,
sim_params,
asset_finder,
trading_calendar):
"""
creates trade_count trades for each sid in sids list.
first trade will be on sim_params.start_session, and daily
thereafter for e... | [
"creates",
"trade_count",
"trades",
"for",
"each",
"sid",
"in",
"sids",
"list",
".",
"first",
"trade",
"will",
"be",
"on",
"sim_params",
".",
"start_session",
"and",
"daily",
"thereafter",
"for",
"each",
"sid",
".",
"Thus",
"two",
"sids",
"should",
"result",... | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/factory.py#L115-L131 | [
"def",
"create_daily_trade_source",
"(",
"sids",
",",
"sim_params",
",",
"asset_finder",
",",
"trading_calendar",
")",
":",
"return",
"create_trade_source",
"(",
"sids",
",",
"timedelta",
"(",
"days",
"=",
"1",
")",
",",
"sim_params",
",",
"asset_finder",
",",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | load_data_table | Load data table from zip file provided by Quandl. | zipline/data/bundles/quandl.py | def load_data_table(file,
index_col,
show_progress=False):
""" Load data table from zip file provided by Quandl.
"""
with ZipFile(file) as zip_file:
file_names = zip_file.namelist()
assert len(file_names) == 1, "Expected a single file from Quandl."
... | def load_data_table(file,
index_col,
show_progress=False):
""" Load data table from zip file provided by Quandl.
"""
with ZipFile(file) as zip_file:
file_names = zip_file.namelist()
assert len(file_names) == 1, "Expected a single file from Quandl."
... | [
"Load",
"data",
"table",
"from",
"zip",
"file",
"provided",
"by",
"Quandl",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/bundles/quandl.py#L38-L75 | [
"def",
"load_data_table",
"(",
"file",
",",
"index_col",
",",
"show_progress",
"=",
"False",
")",
":",
"with",
"ZipFile",
"(",
"file",
")",
"as",
"zip_file",
":",
"file_names",
"=",
"zip_file",
".",
"namelist",
"(",
")",
"assert",
"len",
"(",
"file_names",... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | fetch_data_table | Fetch WIKI Prices data table from Quandl | zipline/data/bundles/quandl.py | def fetch_data_table(api_key,
show_progress,
retries):
""" Fetch WIKI Prices data table from Quandl
"""
for _ in range(retries):
try:
if show_progress:
log.info('Downloading WIKI metadata.')
metadata = pd.read_csv(
... | def fetch_data_table(api_key,
show_progress,
retries):
""" Fetch WIKI Prices data table from Quandl
"""
for _ in range(retries):
try:
if show_progress:
log.info('Downloading WIKI metadata.')
metadata = pd.read_csv(
... | [
"Fetch",
"WIKI",
"Prices",
"data",
"table",
"from",
"Quandl"
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/bundles/quandl.py#L78-L114 | [
"def",
"fetch_data_table",
"(",
"api_key",
",",
"show_progress",
",",
"retries",
")",
":",
"for",
"_",
"in",
"range",
"(",
"retries",
")",
":",
"try",
":",
"if",
"show_progress",
":",
"log",
".",
"info",
"(",
"'Downloading WIKI metadata.'",
")",
"metadata",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | quandl_bundle | quandl_bundle builds a daily dataset using Quandl's WIKI Prices dataset.
For more information on Quandl's API and how to obtain an API key,
please visit https://docs.quandl.com/docs#section-authentication | zipline/data/bundles/quandl.py | def quandl_bundle(environ,
asset_db_writer,
minute_bar_writer,
daily_bar_writer,
adjustment_writer,
calendar,
start_session,
end_session,
cache,
show_progress... | def quandl_bundle(environ,
asset_db_writer,
minute_bar_writer,
daily_bar_writer,
adjustment_writer,
calendar,
start_session,
end_session,
cache,
show_progress... | [
"quandl_bundle",
"builds",
"a",
"daily",
"dataset",
"using",
"Quandl",
"s",
"WIKI",
"Prices",
"dataset",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/bundles/quandl.py#L183-L250 | [
"def",
"quandl_bundle",
"(",
"environ",
",",
"asset_db_writer",
",",
"minute_bar_writer",
",",
"daily_bar_writer",
",",
"adjustment_writer",
",",
"calendar",
",",
"start_session",
",",
"end_session",
",",
"cache",
",",
"show_progress",
",",
"output_dir",
")",
":",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | download_with_progress | Download streaming data from a URL, printing progress information to the
terminal.
Parameters
----------
url : str
A URL that can be understood by ``requests.get``.
chunk_size : int
Number of bytes to read at a time from requests.
**progress_kwargs
Forwarded to click.pro... | zipline/data/bundles/quandl.py | def download_with_progress(url, chunk_size, **progress_kwargs):
"""
Download streaming data from a URL, printing progress information to the
terminal.
Parameters
----------
url : str
A URL that can be understood by ``requests.get``.
chunk_size : int
Number of bytes to read a... | def download_with_progress(url, chunk_size, **progress_kwargs):
"""
Download streaming data from a URL, printing progress information to the
terminal.
Parameters
----------
url : str
A URL that can be understood by ``requests.get``.
chunk_size : int
Number of bytes to read a... | [
"Download",
"streaming",
"data",
"from",
"a",
"URL",
"printing",
"progress",
"information",
"to",
"the",
"terminal",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/bundles/quandl.py#L253-L283 | [
"def",
"download_with_progress",
"(",
"url",
",",
"chunk_size",
",",
"*",
"*",
"progress_kwargs",
")",
":",
"resp",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"stream",
"=",
"True",
")",
"resp",
".",
"raise_for_status",
"(",
")",
"total_size",
"=",
"i... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | download_without_progress | Download data from a URL, returning a BytesIO containing the loaded data.
Parameters
----------
url : str
A URL that can be understood by ``requests.get``.
Returns
-------
data : BytesIO
A BytesIO containing the downloaded data. | zipline/data/bundles/quandl.py | def download_without_progress(url):
"""
Download data from a URL, returning a BytesIO containing the loaded data.
Parameters
----------
url : str
A URL that can be understood by ``requests.get``.
Returns
-------
data : BytesIO
A BytesIO containing the downloaded data.
... | def download_without_progress(url):
"""
Download data from a URL, returning a BytesIO containing the loaded data.
Parameters
----------
url : str
A URL that can be understood by ``requests.get``.
Returns
-------
data : BytesIO
A BytesIO containing the downloaded data.
... | [
"Download",
"data",
"from",
"a",
"URL",
"returning",
"a",
"BytesIO",
"containing",
"the",
"loaded",
"data",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/bundles/quandl.py#L286-L302 | [
"def",
"download_without_progress",
"(",
"url",
")",
":",
"resp",
"=",
"requests",
".",
"get",
"(",
"url",
")",
"resp",
".",
"raise_for_status",
"(",
")",
"return",
"BytesIO",
"(",
"resp",
".",
"content",
")"
] | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | minute_frame_to_session_frame | Resample a DataFrame with minute data into the frame expected by a
BcolzDailyBarWriter.
Parameters
----------
minute_frame : pd.DataFrame
A DataFrame with the columns `open`, `high`, `low`, `close`, `volume`,
and `dt` (minute dts)
calendar : trading_calendars.trading_calendar.Tradin... | zipline/data/resample.py | def minute_frame_to_session_frame(minute_frame, calendar):
"""
Resample a DataFrame with minute data into the frame expected by a
BcolzDailyBarWriter.
Parameters
----------
minute_frame : pd.DataFrame
A DataFrame with the columns `open`, `high`, `low`, `close`, `volume`,
and `d... | def minute_frame_to_session_frame(minute_frame, calendar):
"""
Resample a DataFrame with minute data into the frame expected by a
BcolzDailyBarWriter.
Parameters
----------
minute_frame : pd.DataFrame
A DataFrame with the columns `open`, `high`, `low`, `close`, `volume`,
and `d... | [
"Resample",
"a",
"DataFrame",
"with",
"minute",
"data",
"into",
"the",
"frame",
"expected",
"by",
"a",
"BcolzDailyBarWriter",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/resample.py#L42-L66 | [
"def",
"minute_frame_to_session_frame",
"(",
"minute_frame",
",",
"calendar",
")",
":",
"how",
"=",
"OrderedDict",
"(",
"(",
"c",
",",
"_MINUTE_TO_SESSION_OHCLV_HOW",
"[",
"c",
"]",
")",
"for",
"c",
"in",
"minute_frame",
".",
"columns",
")",
"labels",
"=",
"... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | minute_to_session | Resample an array with minute data into an array with session data.
This function assumes that the minute data is the exact length of all
minutes in the sessions in the output.
Parameters
----------
column : str
The `open`, `high`, `low`, `close`, or `volume` column.
close_locs : array... | zipline/data/resample.py | def minute_to_session(column, close_locs, data, out):
"""
Resample an array with minute data into an array with session data.
This function assumes that the minute data is the exact length of all
minutes in the sessions in the output.
Parameters
----------
column : str
The `open`, ... | def minute_to_session(column, close_locs, data, out):
"""
Resample an array with minute data into an array with session data.
This function assumes that the minute data is the exact length of all
minutes in the sessions in the output.
Parameters
----------
column : str
The `open`, ... | [
"Resample",
"an",
"array",
"with",
"minute",
"data",
"into",
"an",
"array",
"with",
"session",
"data",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/resample.py#L69-L100 | [
"def",
"minute_to_session",
"(",
"column",
",",
"close_locs",
",",
"data",
",",
"out",
")",
":",
"if",
"column",
"==",
"'open'",
":",
"_minute_to_session_open",
"(",
"close_locs",
",",
"data",
",",
"out",
")",
"elif",
"column",
"==",
"'high'",
":",
"_minut... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | DailyHistoryAggregator.opens | The open field's aggregation returns the first value that occurs
for the day, if there has been no data on or before the `dt` the open
is `nan`.
Once the first non-nan open is seen, that value remains constant per
asset for the remainder of the day.
Returns
-------
... | zipline/data/resample.py | def opens(self, assets, dt):
"""
The open field's aggregation returns the first value that occurs
for the day, if there has been no data on or before the `dt` the open
is `nan`.
Once the first non-nan open is seen, that value remains constant per
asset for the remainder ... | def opens(self, assets, dt):
"""
The open field's aggregation returns the first value that occurs
for the day, if there has been no data on or before the `dt` the open
is `nan`.
Once the first non-nan open is seen, that value remains constant per
asset for the remainder ... | [
"The",
"open",
"field",
"s",
"aggregation",
"returns",
"the",
"first",
"value",
"that",
"occurs",
"for",
"the",
"day",
"if",
"there",
"has",
"been",
"no",
"data",
"on",
"or",
"before",
"the",
"dt",
"the",
"open",
"is",
"nan",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/resample.py#L167-L237 | [
"def",
"opens",
"(",
"self",
",",
"assets",
",",
"dt",
")",
":",
"market_open",
",",
"prev_dt",
",",
"dt_value",
",",
"entries",
"=",
"self",
".",
"_prelude",
"(",
"dt",
",",
"'open'",
")",
"opens",
"=",
"[",
"]",
"session_label",
"=",
"self",
".",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | DailyHistoryAggregator.highs | The high field's aggregation returns the largest high seen between
the market open and the current dt.
If there has been no data on or before the `dt` the high is `nan`.
Returns
-------
np.array with dtype=float64, in order of assets parameter. | zipline/data/resample.py | def highs(self, assets, dt):
"""
The high field's aggregation returns the largest high seen between
the market open and the current dt.
If there has been no data on or before the `dt` the high is `nan`.
Returns
-------
np.array with dtype=float64, in order of ass... | def highs(self, assets, dt):
"""
The high field's aggregation returns the largest high seen between
the market open and the current dt.
If there has been no data on or before the `dt` the high is `nan`.
Returns
-------
np.array with dtype=float64, in order of ass... | [
"The",
"high",
"field",
"s",
"aggregation",
"returns",
"the",
"largest",
"high",
"seen",
"between",
"the",
"market",
"open",
"and",
"the",
"current",
"dt",
".",
"If",
"there",
"has",
"been",
"no",
"data",
"on",
"or",
"before",
"the",
"dt",
"the",
"high",... | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/resample.py#L239-L306 | [
"def",
"highs",
"(",
"self",
",",
"assets",
",",
"dt",
")",
":",
"market_open",
",",
"prev_dt",
",",
"dt_value",
",",
"entries",
"=",
"self",
".",
"_prelude",
"(",
"dt",
",",
"'high'",
")",
"highs",
"=",
"[",
"]",
"session_label",
"=",
"self",
".",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | DailyHistoryAggregator.lows | The low field's aggregation returns the smallest low seen between
the market open and the current dt.
If there has been no data on or before the `dt` the low is `nan`.
Returns
-------
np.array with dtype=float64, in order of assets parameter. | zipline/data/resample.py | def lows(self, assets, dt):
"""
The low field's aggregation returns the smallest low seen between
the market open and the current dt.
If there has been no data on or before the `dt` the low is `nan`.
Returns
-------
np.array with dtype=float64, in order of assets... | def lows(self, assets, dt):
"""
The low field's aggregation returns the smallest low seen between
the market open and the current dt.
If there has been no data on or before the `dt` the low is `nan`.
Returns
-------
np.array with dtype=float64, in order of assets... | [
"The",
"low",
"field",
"s",
"aggregation",
"returns",
"the",
"smallest",
"low",
"seen",
"between",
"the",
"market",
"open",
"and",
"the",
"current",
"dt",
".",
"If",
"there",
"has",
"been",
"no",
"data",
"on",
"or",
"before",
"the",
"dt",
"the",
"low",
... | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/resample.py#L308-L370 | [
"def",
"lows",
"(",
"self",
",",
"assets",
",",
"dt",
")",
":",
"market_open",
",",
"prev_dt",
",",
"dt_value",
",",
"entries",
"=",
"self",
".",
"_prelude",
"(",
"dt",
",",
"'low'",
")",
"lows",
"=",
"[",
"]",
"session_label",
"=",
"self",
".",
"_... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | DailyHistoryAggregator.closes | The close field's aggregation returns the latest close at the given
dt.
If the close for the given dt is `nan`, the most recent non-nan
`close` is used.
If there has been no data on or before the `dt` the close is `nan`.
Returns
-------
np.array with dtype=float6... | zipline/data/resample.py | def closes(self, assets, dt):
"""
The close field's aggregation returns the latest close at the given
dt.
If the close for the given dt is `nan`, the most recent non-nan
`close` is used.
If there has been no data on or before the `dt` the close is `nan`.
Returns
... | def closes(self, assets, dt):
"""
The close field's aggregation returns the latest close at the given
dt.
If the close for the given dt is `nan`, the most recent non-nan
`close` is used.
If there has been no data on or before the `dt` the close is `nan`.
Returns
... | [
"The",
"close",
"field",
"s",
"aggregation",
"returns",
"the",
"latest",
"close",
"at",
"the",
"given",
"dt",
".",
"If",
"the",
"close",
"for",
"the",
"given",
"dt",
"is",
"nan",
"the",
"most",
"recent",
"non",
"-",
"nan",
"close",
"is",
"used",
".",
... | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/resample.py#L372-L446 | [
"def",
"closes",
"(",
"self",
",",
"assets",
",",
"dt",
")",
":",
"market_open",
",",
"prev_dt",
",",
"dt_value",
",",
"entries",
"=",
"self",
".",
"_prelude",
"(",
"dt",
",",
"'close'",
")",
"closes",
"=",
"[",
"]",
"session_label",
"=",
"self",
"."... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | DailyHistoryAggregator.volumes | The volume field's aggregation returns the sum of all volumes
between the market open and the `dt`
If there has been no data on or before the `dt` the volume is 0.
Returns
-------
np.array with dtype=int64, in order of assets parameter. | zipline/data/resample.py | def volumes(self, assets, dt):
"""
The volume field's aggregation returns the sum of all volumes
between the market open and the `dt`
If there has been no data on or before the `dt` the volume is 0.
Returns
-------
np.array with dtype=int64, in order of assets pa... | def volumes(self, assets, dt):
"""
The volume field's aggregation returns the sum of all volumes
between the market open and the `dt`
If there has been no data on or before the `dt` the volume is 0.
Returns
-------
np.array with dtype=int64, in order of assets pa... | [
"The",
"volume",
"field",
"s",
"aggregation",
"returns",
"the",
"sum",
"of",
"all",
"volumes",
"between",
"the",
"market",
"open",
"and",
"the",
"dt",
"If",
"there",
"has",
"been",
"no",
"data",
"on",
"or",
"before",
"the",
"dt",
"the",
"volume",
"is",
... | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/resample.py#L448-L510 | [
"def",
"volumes",
"(",
"self",
",",
"assets",
",",
"dt",
")",
":",
"market_open",
",",
"prev_dt",
",",
"dt_value",
",",
"entries",
"=",
"self",
".",
"_prelude",
"(",
"dt",
",",
"'volume'",
")",
"volumes",
"=",
"[",
"]",
"session_label",
"=",
"self",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | infer_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 erro... | zipline/pipeline/domain.py | 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.
... | 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",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/domain.py#L274-L314 | [
"def",
"infer_domain",
"(",
"terms",
")",
":",
"domains",
"=",
"{",
"t",
".",
"domain",
"for",
"t",
"in",
"terms",
"}",
"num_domains",
"=",
"len",
"(",
"domains",
")",
"if",
"num_domains",
"==",
"0",
":",
"return",
"GENERIC",
"elif",
"num_domains",
"==... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | IDomain.roll_forward | Given a date, align it to the calendar of the pipeline's domain.
Parameters
----------
dt : pd.Timestamp
Returns
-------
pd.Timestamp | zipline/pipeline/domain.py | 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... | 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",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/domain.py#L77-L102 | [
"def",
"roll_forward",
"(",
"self",
",",
"dt",
")",
":",
"dt",
"=",
"pd",
".",
"Timestamp",
"(",
"dt",
",",
"tz",
"=",
"'UTC'",
")",
"trading_days",
"=",
"self",
".",
"all_sessions",
"(",
")",
"try",
":",
"return",
"trading_days",
"[",
"trading_days",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | days_and_sids_for_frames | Returns the date index and sid columns shared by a list of dataframes,
ensuring they all match.
Parameters
----------
frames : list[pd.DataFrame]
A list of dataframes indexed by day, with a column per sid.
Returns
-------
days : np.array[datetime64[ns]]
The days in these da... | zipline/data/hdf5_daily_bars.py | def days_and_sids_for_frames(frames):
"""
Returns the date index and sid columns shared by a list of dataframes,
ensuring they all match.
Parameters
----------
frames : list[pd.DataFrame]
A list of dataframes indexed by day, with a column per sid.
Returns
-------
days : np.... | def days_and_sids_for_frames(frames):
"""
Returns the date index and sid columns shared by a list of dataframes,
ensuring they all match.
Parameters
----------
frames : list[pd.DataFrame]
A list of dataframes indexed by day, with a column per sid.
Returns
-------
days : np.... | [
"Returns",
"the",
"date",
"index",
"and",
"sid",
"columns",
"shared",
"by",
"a",
"list",
"of",
"dataframes",
"ensuring",
"they",
"all",
"match",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/hdf5_daily_bars.py#L154-L192 | [
"def",
"days_and_sids_for_frames",
"(",
"frames",
")",
":",
"if",
"not",
"frames",
":",
"days",
"=",
"np",
".",
"array",
"(",
"[",
"]",
",",
"dtype",
"=",
"'datetime64[ns]'",
")",
"sids",
"=",
"np",
".",
"array",
"(",
"[",
"]",
",",
"dtype",
"=",
"... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | compute_asset_lifetimes | Parameters
----------
frames : dict[str, pd.DataFrame]
A dict mapping each OHLCV field to a dataframe with a row for
each date and a column for each sid, as passed to write().
Returns
-------
start_date_ixs : np.array[int64]
The index of the first date with non-nan values, f... | zipline/data/hdf5_daily_bars.py | def compute_asset_lifetimes(frames):
"""
Parameters
----------
frames : dict[str, pd.DataFrame]
A dict mapping each OHLCV field to a dataframe with a row for
each date and a column for each sid, as passed to write().
Returns
-------
start_date_ixs : np.array[int64]
T... | def compute_asset_lifetimes(frames):
"""
Parameters
----------
frames : dict[str, pd.DataFrame]
A dict mapping each OHLCV field to a dataframe with a row for
each date and a column for each sid, as passed to write().
Returns
-------
start_date_ixs : np.array[int64]
T... | [
"Parameters",
"----------",
"frames",
":",
"dict",
"[",
"str",
"pd",
".",
"DataFrame",
"]",
"A",
"dict",
"mapping",
"each",
"OHLCV",
"field",
"to",
"a",
"dataframe",
"with",
"a",
"row",
"for",
"each",
"date",
"and",
"a",
"column",
"for",
"each",
"sid",
... | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/hdf5_daily_bars.py#L360-L391 | [
"def",
"compute_asset_lifetimes",
"(",
"frames",
")",
":",
"# Build a 2D array (dates x sids), where an entry is True if all",
"# fields are nan for the given day and sid.",
"is_null_matrix",
"=",
"np",
".",
"logical_and",
".",
"reduce",
"(",
"[",
"frames",
"[",
"field",
"]",... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | HDF5DailyBarWriter.write | Write the OHLCV data for one country to the HDF5 file.
Parameters
----------
country_code : str
The ISO 3166 alpha-2 country code for this country.
frames : dict[str, pd.DataFrame]
A dict mapping each OHLCV field to a dataframe with a row
for each dat... | zipline/data/hdf5_daily_bars.py | def write(self, country_code, frames, scaling_factors=None):
"""Write the OHLCV data for one country to the HDF5 file.
Parameters
----------
country_code : str
The ISO 3166 alpha-2 country code for this country.
frames : dict[str, pd.DataFrame]
A dict map... | def write(self, country_code, frames, scaling_factors=None):
"""Write the OHLCV data for one country to the HDF5 file.
Parameters
----------
country_code : str
The ISO 3166 alpha-2 country code for this country.
frames : dict[str, pd.DataFrame]
A dict map... | [
"Write",
"the",
"OHLCV",
"data",
"for",
"one",
"country",
"to",
"the",
"HDF5",
"file",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/hdf5_daily_bars.py#L220-L307 | [
"def",
"write",
"(",
"self",
",",
"country_code",
",",
"frames",
",",
"scaling_factors",
"=",
"None",
")",
":",
"if",
"scaling_factors",
"is",
"None",
":",
"scaling_factors",
"=",
"DEFAULT_SCALING_FACTORS",
"with",
"self",
".",
"h5_file",
"(",
"mode",
"=",
"... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | HDF5DailyBarWriter.write_from_sid_df_pairs | Parameters
----------
country_code : str
The ISO 3166 alpha-2 country code for this country.
data : iterable[tuple[int, pandas.DataFrame]]
The data chunks to write. Each chunk should be a tuple of
sid and the data for that asset.
scaling_factors : dict... | zipline/data/hdf5_daily_bars.py | def write_from_sid_df_pairs(self,
country_code,
data,
scaling_factors=None):
"""
Parameters
----------
country_code : str
The ISO 3166 alpha-2 country code for this country.
... | def write_from_sid_df_pairs(self,
country_code,
data,
scaling_factors=None):
"""
Parameters
----------
country_code : str
The ISO 3166 alpha-2 country code for this country.
... | [
"Parameters",
"----------",
"country_code",
":",
"str",
"The",
"ISO",
"3166",
"alpha",
"-",
"2",
"country",
"code",
"for",
"this",
"country",
".",
"data",
":",
"iterable",
"[",
"tuple",
"[",
"int",
"pandas",
".",
"DataFrame",
"]]",
"The",
"data",
"chunks",... | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/hdf5_daily_bars.py#L309-L357 | [
"def",
"write_from_sid_df_pairs",
"(",
"self",
",",
"country_code",
",",
"data",
",",
"scaling_factors",
"=",
"None",
")",
":",
"data",
"=",
"list",
"(",
"data",
")",
"if",
"not",
"data",
":",
"empty_frame",
"=",
"pd",
".",
"DataFrame",
"(",
"data",
"=",... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | HDF5DailyBarReader.from_file | Construct from an h5py.File and a country code.
Parameters
----------
h5_file : h5py.File
An HDF5 daily pricing file.
country_code : str
The ISO 3166 alpha-2 country code for the country to read. | zipline/data/hdf5_daily_bars.py | def from_file(cls, h5_file, country_code):
"""
Construct from an h5py.File and a country code.
Parameters
----------
h5_file : h5py.File
An HDF5 daily pricing file.
country_code : str
The ISO 3166 alpha-2 country code for the country to read.
... | def from_file(cls, h5_file, country_code):
"""
Construct from an h5py.File and a country code.
Parameters
----------
h5_file : h5py.File
An HDF5 daily pricing file.
country_code : str
The ISO 3166 alpha-2 country code for the country to read.
... | [
"Construct",
"from",
"an",
"h5py",
".",
"File",
"and",
"a",
"country",
"code",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/hdf5_daily_bars.py#L424-L443 | [
"def",
"from_file",
"(",
"cls",
",",
"h5_file",
",",
"country_code",
")",
":",
"if",
"h5_file",
".",
"attrs",
"[",
"'version'",
"]",
"!=",
"VERSION",
":",
"raise",
"ValueError",
"(",
"'mismatched version: file is of version %s, expected %s'",
"%",
"(",
"h5_file",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | HDF5DailyBarReader.from_path | Construct from a file path and a country code.
Parameters
----------
path : str
The path to an HDF5 daily pricing file.
country_code : str
The ISO 3166 alpha-2 country code for the country to read. | zipline/data/hdf5_daily_bars.py | def from_path(cls, path, country_code):
"""
Construct from a file path and a country code.
Parameters
----------
path : str
The path to an HDF5 daily pricing file.
country_code : str
The ISO 3166 alpha-2 country code for the country to read.
... | def from_path(cls, path, country_code):
"""
Construct from a file path and a country code.
Parameters
----------
path : str
The path to an HDF5 daily pricing file.
country_code : str
The ISO 3166 alpha-2 country code for the country to read.
... | [
"Construct",
"from",
"a",
"file",
"path",
"and",
"a",
"country",
"code",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/hdf5_daily_bars.py#L446-L457 | [
"def",
"from_path",
"(",
"cls",
",",
"path",
",",
"country_code",
")",
":",
"return",
"cls",
".",
"from_file",
"(",
"h5py",
".",
"File",
"(",
"path",
")",
",",
"country_code",
")"
] | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | HDF5DailyBarReader.load_raw_arrays | Parameters
----------
columns : list of str
'open', 'high', 'low', 'close', or 'volume'
start_date: Timestamp
Beginning of the window range.
end_date: Timestamp
End of the window range.
assets : list of int
The asset identifiers in the ... | zipline/data/hdf5_daily_bars.py | def load_raw_arrays(self,
columns,
start_date,
end_date,
assets):
"""
Parameters
----------
columns : list of str
'open', 'high', 'low', 'close', or 'volume'
start_date: Tim... | def load_raw_arrays(self,
columns,
start_date,
end_date,
assets):
"""
Parameters
----------
columns : list of str
'open', 'high', 'low', 'close', or 'volume'
start_date: Tim... | [
"Parameters",
"----------",
"columns",
":",
"list",
"of",
"str",
"open",
"high",
"low",
"close",
"or",
"volume",
"start_date",
":",
"Timestamp",
"Beginning",
"of",
"the",
"window",
"range",
".",
"end_date",
":",
"Timestamp",
"End",
"of",
"the",
"window",
"ra... | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/hdf5_daily_bars.py#L462-L528 | [
"def",
"load_raw_arrays",
"(",
"self",
",",
"columns",
",",
"start_date",
",",
"end_date",
",",
"assets",
")",
":",
"self",
".",
"_validate_timestamp",
"(",
"start_date",
")",
"self",
".",
"_validate_timestamp",
"(",
"end_date",
")",
"start",
"=",
"start_date"... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | HDF5DailyBarReader._make_sid_selector | Build an indexer mapping ``self.sids`` to ``assets``.
Parameters
----------
assets : list[int]
List of assets requested by a caller of ``load_raw_arrays``.
Returns
-------
index : np.array[int64]
Index array containing the index in ``self.sids`` ... | zipline/data/hdf5_daily_bars.py | def _make_sid_selector(self, assets):
"""
Build an indexer mapping ``self.sids`` to ``assets``.
Parameters
----------
assets : list[int]
List of assets requested by a caller of ``load_raw_arrays``.
Returns
-------
index : np.array[int64]
... | def _make_sid_selector(self, assets):
"""
Build an indexer mapping ``self.sids`` to ``assets``.
Parameters
----------
assets : list[int]
List of assets requested by a caller of ``load_raw_arrays``.
Returns
-------
index : np.array[int64]
... | [
"Build",
"an",
"indexer",
"mapping",
"self",
".",
"sids",
"to",
"assets",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/hdf5_daily_bars.py#L530-L551 | [
"def",
"_make_sid_selector",
"(",
"self",
",",
"assets",
")",
":",
"assets",
"=",
"np",
".",
"array",
"(",
"assets",
")",
"sid_selector",
"=",
"self",
".",
"sids",
".",
"searchsorted",
"(",
"assets",
")",
"unknown",
"=",
"np",
".",
"in1d",
"(",
"assets... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | HDF5DailyBarReader._validate_assets | Validate that asset identifiers are contained in the daily bars.
Parameters
----------
assets : array-like[int]
The asset identifiers to validate.
Raises
------
NoDataForSid
If one or more of the provided asset identifiers are not
cont... | zipline/data/hdf5_daily_bars.py | def _validate_assets(self, assets):
"""Validate that asset identifiers are contained in the daily bars.
Parameters
----------
assets : array-like[int]
The asset identifiers to validate.
Raises
------
NoDataForSid
If one or more of the prov... | def _validate_assets(self, assets):
"""Validate that asset identifiers are contained in the daily bars.
Parameters
----------
assets : array-like[int]
The asset identifiers to validate.
Raises
------
NoDataForSid
If one or more of the prov... | [
"Validate",
"that",
"asset",
"identifiers",
"are",
"contained",
"in",
"the",
"daily",
"bars",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/hdf5_daily_bars.py#L562-L583 | [
"def",
"_validate_assets",
"(",
"self",
",",
"assets",
")",
":",
"missing_sids",
"=",
"np",
".",
"setdiff1d",
"(",
"assets",
",",
"self",
".",
"sids",
")",
"if",
"len",
"(",
"missing_sids",
")",
":",
"raise",
"NoDataForSid",
"(",
"'Assets not contained in da... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | HDF5DailyBarReader.get_value | Retrieve the value at the given coordinates.
Parameters
----------
sid : int
The asset identifier.
dt : pd.Timestamp
The timestamp for the desired data point.
field : string
The OHLVC name for the desired data point.
Returns
-... | zipline/data/hdf5_daily_bars.py | def get_value(self, sid, dt, field):
"""
Retrieve the value at the given coordinates.
Parameters
----------
sid : int
The asset identifier.
dt : pd.Timestamp
The timestamp for the desired data point.
field : string
The OHLVC na... | def get_value(self, sid, dt, field):
"""
Retrieve the value at the given coordinates.
Parameters
----------
sid : int
The asset identifier.
dt : pd.Timestamp
The timestamp for the desired data point.
field : string
The OHLVC na... | [
"Retrieve",
"the",
"value",
"at",
"the",
"given",
"coordinates",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/hdf5_daily_bars.py#L647-L693 | [
"def",
"get_value",
"(",
"self",
",",
"sid",
",",
"dt",
",",
"field",
")",
":",
"self",
".",
"_validate_assets",
"(",
"[",
"sid",
"]",
")",
"self",
".",
"_validate_timestamp",
"(",
"dt",
")",
"sid_ix",
"=",
"self",
".",
"sids",
".",
"searchsorted",
"... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | HDF5DailyBarReader.get_last_traded_dt | Get the latest day on or before ``dt`` in which ``asset`` traded.
If there are no trades on or before ``dt``, returns ``pd.NaT``.
Parameters
----------
asset : zipline.asset.Asset
The asset for which to get the last traded day.
dt : pd.Timestamp
The dt a... | zipline/data/hdf5_daily_bars.py | def get_last_traded_dt(self, asset, dt):
"""
Get the latest day on or before ``dt`` in which ``asset`` traded.
If there are no trades on or before ``dt``, returns ``pd.NaT``.
Parameters
----------
asset : zipline.asset.Asset
The asset for which to get the la... | def get_last_traded_dt(self, asset, dt):
"""
Get the latest day on or before ``dt`` in which ``asset`` traded.
If there are no trades on or before ``dt``, returns ``pd.NaT``.
Parameters
----------
asset : zipline.asset.Asset
The asset for which to get the la... | [
"Get",
"the",
"latest",
"day",
"on",
"or",
"before",
"dt",
"in",
"which",
"asset",
"traded",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/hdf5_daily_bars.py#L695-L726 | [
"def",
"get_last_traded_dt",
"(",
"self",
",",
"asset",
",",
"dt",
")",
":",
"sid_ix",
"=",
"self",
".",
"sids",
".",
"searchsorted",
"(",
"asset",
".",
"sid",
")",
"# Used to get a slice of all dates up to and including ``dt``.",
"dt_limit_ix",
"=",
"self",
".",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | MultiCountryDailyBarReader.from_file | Construct from an h5py.File.
Parameters
----------
h5_file : h5py.File
An HDF5 daily pricing file. | zipline/data/hdf5_daily_bars.py | def from_file(cls, h5_file):
"""
Construct from an h5py.File.
Parameters
----------
h5_file : h5py.File
An HDF5 daily pricing file.
"""
return cls({
country: HDF5DailyBarReader.from_file(h5_file, country)
for country in h5_file... | def from_file(cls, h5_file):
"""
Construct from an h5py.File.
Parameters
----------
h5_file : h5py.File
An HDF5 daily pricing file.
"""
return cls({
country: HDF5DailyBarReader.from_file(h5_file, country)
for country in h5_file... | [
"Construct",
"from",
"an",
"h5py",
".",
"File",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/hdf5_daily_bars.py#L745-L757 | [
"def",
"from_file",
"(",
"cls",
",",
"h5_file",
")",
":",
"return",
"cls",
"(",
"{",
"country",
":",
"HDF5DailyBarReader",
".",
"from_file",
"(",
"h5_file",
",",
"country",
")",
"for",
"country",
"in",
"h5_file",
".",
"keys",
"(",
")",
"}",
")"
] | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | MultiCountryDailyBarReader.load_raw_arrays | Parameters
----------
columns : list of str
'open', 'high', 'low', 'close', or 'volume'
start_date: Timestamp
Beginning of the window range.
end_date: Timestamp
End of the window range.
assets : list of int
The asset identifiers in the ... | zipline/data/hdf5_daily_bars.py | def load_raw_arrays(self,
columns,
start_date,
end_date,
assets):
"""
Parameters
----------
columns : list of str
'open', 'high', 'low', 'close', or 'volume'
start_date: Tim... | def load_raw_arrays(self,
columns,
start_date,
end_date,
assets):
"""
Parameters
----------
columns : list of str
'open', 'high', 'low', 'close', or 'volume'
start_date: Tim... | [
"Parameters",
"----------",
"columns",
":",
"list",
"of",
"str",
"open",
"high",
"low",
"close",
"or",
"volume",
"start_date",
":",
"Timestamp",
"Beginning",
"of",
"the",
"window",
"range",
".",
"end_date",
":",
"Timestamp",
"End",
"of",
"the",
"window",
"ra... | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/hdf5_daily_bars.py#L800-L831 | [
"def",
"load_raw_arrays",
"(",
"self",
",",
"columns",
",",
"start_date",
",",
"end_date",
",",
"assets",
")",
":",
"country_code",
"=",
"self",
".",
"_country_code_for_assets",
"(",
"assets",
")",
"return",
"self",
".",
"_readers",
"[",
"country_code",
"]",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | MultiCountryDailyBarReader.sessions | Returns
-------
sessions : DatetimeIndex
All session labels (unioning the range for all assets) which the
reader can provide. | zipline/data/hdf5_daily_bars.py | def sessions(self):
"""
Returns
-------
sessions : DatetimeIndex
All session labels (unioning the range for all assets) which the
reader can provide.
"""
return pd.to_datetime(
reduce(
np.union1d,
(reader.d... | def sessions(self):
"""
Returns
-------
sessions : DatetimeIndex
All session labels (unioning the range for all assets) which the
reader can provide.
"""
return pd.to_datetime(
reduce(
np.union1d,
(reader.d... | [
"Returns",
"-------",
"sessions",
":",
"DatetimeIndex",
"All",
"session",
"labels",
"(",
"unioning",
"the",
"range",
"for",
"all",
"assets",
")",
"which",
"the",
"reader",
"can",
"provide",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/hdf5_daily_bars.py#L869-L883 | [
"def",
"sessions",
"(",
"self",
")",
":",
"return",
"pd",
".",
"to_datetime",
"(",
"reduce",
"(",
"np",
".",
"union1d",
",",
"(",
"reader",
".",
"dates",
"for",
"reader",
"in",
"self",
".",
"_readers",
".",
"values",
"(",
")",
")",
",",
")",
",",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | MultiCountryDailyBarReader.get_value | Retrieve the value at the given coordinates.
Parameters
----------
sid : int
The asset identifier.
dt : pd.Timestamp
The timestamp for the desired data point.
field : string
The OHLVC name for the desired data point.
Returns
-... | zipline/data/hdf5_daily_bars.py | def get_value(self, sid, dt, field):
"""
Retrieve the value at the given coordinates.
Parameters
----------
sid : int
The asset identifier.
dt : pd.Timestamp
The timestamp for the desired data point.
field : string
The OHLVC na... | def get_value(self, sid, dt, field):
"""
Retrieve the value at the given coordinates.
Parameters
----------
sid : int
The asset identifier.
dt : pd.Timestamp
The timestamp for the desired data point.
field : string
The OHLVC na... | [
"Retrieve",
"the",
"value",
"at",
"the",
"given",
"coordinates",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/hdf5_daily_bars.py#L885-L921 | [
"def",
"get_value",
"(",
"self",
",",
"sid",
",",
"dt",
",",
"field",
")",
":",
"try",
":",
"country_code",
"=",
"self",
".",
"_country_code_for_assets",
"(",
"[",
"sid",
"]",
")",
"except",
"ValueError",
"as",
"exc",
":",
"raise_from",
"(",
"NoDataForSi... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | MultiCountryDailyBarReader.get_last_traded_dt | Get the latest day on or before ``dt`` in which ``asset`` traded.
If there are no trades on or before ``dt``, returns ``pd.NaT``.
Parameters
----------
asset : zipline.asset.Asset
The asset for which to get the last traded day.
dt : pd.Timestamp
The dt a... | zipline/data/hdf5_daily_bars.py | def get_last_traded_dt(self, asset, dt):
"""
Get the latest day on or before ``dt`` in which ``asset`` traded.
If there are no trades on or before ``dt``, returns ``pd.NaT``.
Parameters
----------
asset : zipline.asset.Asset
The asset for which to get the la... | def get_last_traded_dt(self, asset, dt):
"""
Get the latest day on or before ``dt`` in which ``asset`` traded.
If there are no trades on or before ``dt``, returns ``pd.NaT``.
Parameters
----------
asset : zipline.asset.Asset
The asset for which to get the la... | [
"Get",
"the",
"latest",
"day",
"on",
"or",
"before",
"dt",
"in",
"which",
"asset",
"traded",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/hdf5_daily_bars.py#L923-L943 | [
"def",
"get_last_traded_dt",
"(",
"self",
",",
"asset",
",",
"dt",
")",
":",
"country_code",
"=",
"self",
".",
"_country_code_for_assets",
"(",
"[",
"asset",
".",
"sid",
"]",
")",
"return",
"self",
".",
"_readers",
"[",
"country_code",
"]",
".",
"get_last_... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | _normalize_index_columns_in_place | Update dataframes in place to set indentifier columns as indices.
For each input frame, if the frame has a column with the same name as its
associated index column, set that column as the index.
Otherwise, assume the index already contains identifiers.
If frames are passed as None, they're ignored. | zipline/assets/asset_writer.py | def _normalize_index_columns_in_place(equities,
equity_supplementary_mappings,
futures,
exchanges,
root_symbols):
"""
Update dataframes in place to set indentif... | def _normalize_index_columns_in_place(equities,
equity_supplementary_mappings,
futures,
exchanges,
root_symbols):
"""
Update dataframes in place to set indentif... | [
"Update",
"dataframes",
"in",
"place",
"to",
"set",
"indentifier",
"columns",
"as",
"indices",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/asset_writer.py#L74-L95 | [
"def",
"_normalize_index_columns_in_place",
"(",
"equities",
",",
"equity_supplementary_mappings",
",",
"futures",
",",
"exchanges",
",",
"root_symbols",
")",
":",
"for",
"frame",
",",
"column_name",
"in",
"(",
"(",
"equities",
",",
"'sid'",
")",
",",
"(",
"equi... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | split_delimited_symbol | Takes in a symbol that may be delimited and splits it in to a company
symbol and share class symbol. Also returns the fuzzy symbol, which is the
symbol without any fuzzy characters at all.
Parameters
----------
symbol : str
The possibly-delimited symbol to be split
Returns
-------
... | zipline/assets/asset_writer.py | def split_delimited_symbol(symbol):
"""
Takes in a symbol that may be delimited and splits it in to a company
symbol and share class symbol. Also returns the fuzzy symbol, which is the
symbol without any fuzzy characters at all.
Parameters
----------
symbol : str
The possibly-delimi... | def split_delimited_symbol(symbol):
"""
Takes in a symbol that may be delimited and splits it in to a company
symbol and share class symbol. Also returns the fuzzy symbol, which is the
symbol without any fuzzy characters at all.
Parameters
----------
symbol : str
The possibly-delimi... | [
"Takes",
"in",
"a",
"symbol",
"that",
"may",
"be",
"delimited",
"and",
"splits",
"it",
"in",
"to",
"a",
"company",
"symbol",
"and",
"share",
"class",
"symbol",
".",
"Also",
"returns",
"the",
"fuzzy",
"symbol",
"which",
"is",
"the",
"symbol",
"without",
"... | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/asset_writer.py#L175-L213 | [
"def",
"split_delimited_symbol",
"(",
"symbol",
")",
":",
"# return blank strings for any bad fuzzy symbols, like NaN or None",
"if",
"symbol",
"in",
"_delimited_symbol_default_triggers",
":",
"return",
"''",
",",
"''",
"symbol",
"=",
"symbol",
".",
"upper",
"(",
")",
"... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | _generate_output_dataframe | Generates an output dataframe from the given subset of user-provided
data, the given column names, and the given default values.
Parameters
----------
data_subset : DataFrame
A DataFrame, usually from an AssetData object,
that contains the user's input metadata for the asset type being
... | zipline/assets/asset_writer.py | def _generate_output_dataframe(data_subset, defaults):
"""
Generates an output dataframe from the given subset of user-provided
data, the given column names, and the given default values.
Parameters
----------
data_subset : DataFrame
A DataFrame, usually from an AssetData object,
... | def _generate_output_dataframe(data_subset, defaults):
"""
Generates an output dataframe from the given subset of user-provided
data, the given column names, and the given default values.
Parameters
----------
data_subset : DataFrame
A DataFrame, usually from an AssetData object,
... | [
"Generates",
"an",
"output",
"dataframe",
"from",
"the",
"given",
"subset",
"of",
"user",
"-",
"provided",
"data",
"the",
"given",
"column",
"names",
"and",
"the",
"given",
"default",
"values",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/asset_writer.py#L216-L254 | [
"def",
"_generate_output_dataframe",
"(",
"data_subset",
",",
"defaults",
")",
":",
"# The columns provided.",
"cols",
"=",
"set",
"(",
"data_subset",
".",
"columns",
")",
"desired_cols",
"=",
"set",
"(",
"defaults",
")",
"# Drop columns with unrecognised headers.",
"... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | _check_symbol_mappings | Check that there are no cases where multiple symbols resolve to the same
asset at the same time in the same country.
Parameters
----------
df : pd.DataFrame
The equity symbol mappings table.
exchanges : pd.DataFrame
The exchanges table.
asset_exchange : pd.Series
A serie... | zipline/assets/asset_writer.py | def _check_symbol_mappings(df, exchanges, asset_exchange):
"""Check that there are no cases where multiple symbols resolve to the same
asset at the same time in the same country.
Parameters
----------
df : pd.DataFrame
The equity symbol mappings table.
exchanges : pd.DataFrame
T... | def _check_symbol_mappings(df, exchanges, asset_exchange):
"""Check that there are no cases where multiple symbols resolve to the same
asset at the same time in the same country.
Parameters
----------
df : pd.DataFrame
The equity symbol mappings table.
exchanges : pd.DataFrame
T... | [
"Check",
"that",
"there",
"are",
"no",
"cases",
"where",
"multiple",
"symbols",
"resolve",
"to",
"the",
"same",
"asset",
"at",
"the",
"same",
"time",
"in",
"the",
"same",
"country",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/asset_writer.py#L272-L332 | [
"def",
"_check_symbol_mappings",
"(",
"df",
",",
"exchanges",
",",
"asset_exchange",
")",
":",
"mappings",
"=",
"df",
".",
"set_index",
"(",
"'sid'",
")",
"[",
"list",
"(",
"mapping_columns",
")",
"]",
".",
"copy",
"(",
")",
"mappings",
"[",
"'country_code... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | _split_symbol_mappings | Split out the symbol: sid mappings from the raw data.
Parameters
----------
df : pd.DataFrame
The dataframe with multiple rows for each symbol: sid pair.
exchanges : pd.DataFrame
The exchanges table.
Returns
-------
asset_info : pd.DataFrame
The asset info with one ... | zipline/assets/asset_writer.py | def _split_symbol_mappings(df, exchanges):
"""Split out the symbol: sid mappings from the raw data.
Parameters
----------
df : pd.DataFrame
The dataframe with multiple rows for each symbol: sid pair.
exchanges : pd.DataFrame
The exchanges table.
Returns
-------
asset_in... | def _split_symbol_mappings(df, exchanges):
"""Split out the symbol: sid mappings from the raw data.
Parameters
----------
df : pd.DataFrame
The dataframe with multiple rows for each symbol: sid pair.
exchanges : pd.DataFrame
The exchanges table.
Returns
-------
asset_in... | [
"Split",
"out",
"the",
"symbol",
":",
"sid",
"mappings",
"from",
"the",
"raw",
"data",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/asset_writer.py#L335-L368 | [
"def",
"_split_symbol_mappings",
"(",
"df",
",",
"exchanges",
")",
":",
"mappings",
"=",
"df",
"[",
"list",
"(",
"mapping_columns",
")",
"]",
"with",
"pd",
".",
"option_context",
"(",
"'mode.chained_assignment'",
",",
"None",
")",
":",
"mappings",
"[",
"'sid... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | _dt_to_epoch_ns | Convert a timeseries into an Int64Index of nanoseconds since the epoch.
Parameters
----------
dt_series : pd.Series
The timeseries to convert.
Returns
-------
idx : pd.Int64Index
The index converted to nanoseconds since the epoch. | zipline/assets/asset_writer.py | def _dt_to_epoch_ns(dt_series):
"""Convert a timeseries into an Int64Index of nanoseconds since the epoch.
Parameters
----------
dt_series : pd.Series
The timeseries to convert.
Returns
-------
idx : pd.Int64Index
The index converted to nanoseconds since the epoch.
"""
... | def _dt_to_epoch_ns(dt_series):
"""Convert a timeseries into an Int64Index of nanoseconds since the epoch.
Parameters
----------
dt_series : pd.Series
The timeseries to convert.
Returns
-------
idx : pd.Int64Index
The index converted to nanoseconds since the epoch.
"""
... | [
"Convert",
"a",
"timeseries",
"into",
"an",
"Int64Index",
"of",
"nanoseconds",
"since",
"the",
"epoch",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/asset_writer.py#L371-L389 | [
"def",
"_dt_to_epoch_ns",
"(",
"dt_series",
")",
":",
"index",
"=",
"pd",
".",
"to_datetime",
"(",
"dt_series",
".",
"values",
")",
"if",
"index",
".",
"tzinfo",
"is",
"None",
":",
"index",
"=",
"index",
".",
"tz_localize",
"(",
"'UTC'",
")",
"else",
"... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.