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
alter_columns
Alter columns from a table. Parameters ---------- name : str The name of the table. *columns The new columns to have. selection_string : str, optional The string to use in the selection. If not provided, it will select all of the new columns from the old table. ...
zipline/assets/asset_db_migrations.py
def alter_columns(op, name, *columns, **kwargs): """Alter columns from a table. Parameters ---------- name : str The name of the table. *columns The new columns to have. selection_string : str, optional The string to use in the selection. If not provided, it will select ...
def alter_columns(op, name, *columns, **kwargs): """Alter columns from a table. Parameters ---------- name : str The name of the table. *columns The new columns to have. selection_string : str, optional The string to use in the selection. If not provided, it will select ...
[ "Alter", "columns", "from", "a", "table", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/asset_db_migrations.py#L13-L61
[ "def", "alter_columns", "(", "op", ",", "name", ",", "*", "columns", ",", "*", "*", "kwargs", ")", ":", "selection_string", "=", "kwargs", ".", "pop", "(", "'selection_string'", ",", "None", ")", "if", "kwargs", ":", "raise", "TypeError", "(", "'alter_co...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
downgrade
Downgrades the assets db at the given engine to the desired version. Parameters ---------- engine : Engine An SQLAlchemy engine to the assets database. desired_version : int The desired resulting version for the assets database.
zipline/assets/asset_db_migrations.py
def downgrade(engine, desired_version): """Downgrades the assets db at the given engine to the desired version. Parameters ---------- engine : Engine An SQLAlchemy engine to the assets database. desired_version : int The desired resulting version for the assets database. """ ...
def downgrade(engine, desired_version): """Downgrades the assets db at the given engine to the desired version. Parameters ---------- engine : Engine An SQLAlchemy engine to the assets database. desired_version : int The desired resulting version for the assets database. """ ...
[ "Downgrades", "the", "assets", "db", "at", "the", "given", "engine", "to", "the", "desired", "version", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/asset_db_migrations.py#L65-L109
[ "def", "downgrade", "(", "engine", ",", "desired_version", ")", ":", "# Check the version of the db at the engine", "with", "engine", ".", "begin", "(", ")", "as", "conn", ":", "metadata", "=", "sa", ".", "MetaData", "(", "conn", ")", "metadata", ".", "reflect...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
downgrades
Decorator for marking that a method is a downgrade to a version to the previous version. Parameters ---------- src : int The version this downgrades from. Returns ------- decorator : callable[(callable) -> callable] The decorator to apply.
zipline/assets/asset_db_migrations.py
def downgrades(src): """Decorator for marking that a method is a downgrade to a version to the previous version. Parameters ---------- src : int The version this downgrades from. Returns ------- decorator : callable[(callable) -> callable] The decorator to apply. ""...
def downgrades(src): """Decorator for marking that a method is a downgrade to a version to the previous version. Parameters ---------- src : int The version this downgrades from. Returns ------- decorator : callable[(callable) -> callable] The decorator to apply. ""...
[ "Decorator", "for", "marking", "that", "a", "method", "is", "a", "downgrade", "to", "a", "version", "to", "the", "previous", "version", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/asset_db_migrations.py#L133-L158
[ "def", "downgrades", "(", "src", ")", ":", "def", "_", "(", "f", ")", ":", "destination", "=", "src", "-", "1", "@", "do", "(", "operator", ".", "setitem", "(", "_downgrade_methods", ",", "destination", ")", ")", "@", "wraps", "(", "f", ")", "def",...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
_downgrade_v1
Downgrade assets db by removing the 'tick_size' column and renaming the 'multiplier' column.
zipline/assets/asset_db_migrations.py
def _downgrade_v1(op): """ Downgrade assets db by removing the 'tick_size' column and renaming the 'multiplier' column. """ # Drop indices before batch # This is to prevent index collision when creating the temp table op.drop_index('ix_futures_contracts_root_symbol') op.drop_index('ix_fu...
def _downgrade_v1(op): """ Downgrade assets db by removing the 'tick_size' column and renaming the 'multiplier' column. """ # Drop indices before batch # This is to prevent index collision when creating the temp table op.drop_index('ix_futures_contracts_root_symbol') op.drop_index('ix_fu...
[ "Downgrade", "assets", "db", "by", "removing", "the", "tick_size", "column", "and", "renaming", "the", "multiplier", "column", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/asset_db_migrations.py#L162-L189
[ "def", "_downgrade_v1", "(", "op", ")", ":", "# Drop indices before batch", "# This is to prevent index collision when creating the temp table", "op", ".", "drop_index", "(", "'ix_futures_contracts_root_symbol'", ")", "op", ".", "drop_index", "(", "'ix_futures_contracts_symbol'",...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
_downgrade_v2
Downgrade assets db by removing the 'auto_close_date' column.
zipline/assets/asset_db_migrations.py
def _downgrade_v2(op): """ Downgrade assets db by removing the 'auto_close_date' column. """ # Drop indices before batch # This is to prevent index collision when creating the temp table op.drop_index('ix_equities_fuzzy_symbol') op.drop_index('ix_equities_company_symbol') # Execute batc...
def _downgrade_v2(op): """ Downgrade assets db by removing the 'auto_close_date' column. """ # Drop indices before batch # This is to prevent index collision when creating the temp table op.drop_index('ix_equities_fuzzy_symbol') op.drop_index('ix_equities_company_symbol') # Execute batc...
[ "Downgrade", "assets", "db", "by", "removing", "the", "auto_close_date", "column", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/asset_db_migrations.py#L193-L212
[ "def", "_downgrade_v2", "(", "op", ")", ":", "# Drop indices before batch", "# This is to prevent index collision when creating the temp table", "op", ".", "drop_index", "(", "'ix_equities_fuzzy_symbol'", ")", "op", ".", "drop_index", "(", "'ix_equities_company_symbol'", ")", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
_downgrade_v3
Downgrade assets db by adding a not null constraint on ``equities.first_traded``
zipline/assets/asset_db_migrations.py
def _downgrade_v3(op): """ Downgrade assets db by adding a not null constraint on ``equities.first_traded`` """ op.create_table( '_new_equities', sa.Column( 'sid', sa.Integer, unique=True, nullable=False, primary_key=True, ...
def _downgrade_v3(op): """ Downgrade assets db by adding a not null constraint on ``equities.first_traded`` """ op.create_table( '_new_equities', sa.Column( 'sid', sa.Integer, unique=True, nullable=False, primary_key=True, ...
[ "Downgrade", "assets", "db", "by", "adding", "a", "not", "null", "constraint", "on", "equities", ".", "first_traded" ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/asset_db_migrations.py#L216-L260
[ "def", "_downgrade_v3", "(", "op", ")", ":", "op", ".", "create_table", "(", "'_new_equities'", ",", "sa", ".", "Column", "(", "'sid'", ",", "sa", ".", "Integer", ",", "unique", "=", "True", ",", "nullable", "=", "False", ",", "primary_key", "=", "True...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
_downgrade_v4
Downgrades assets db by copying the `exchange_full` column to `exchange`, then dropping the `exchange_full` column.
zipline/assets/asset_db_migrations.py
def _downgrade_v4(op): """ Downgrades assets db by copying the `exchange_full` column to `exchange`, then dropping the `exchange_full` column. """ op.drop_index('ix_equities_fuzzy_symbol') op.drop_index('ix_equities_company_symbol') op.execute("UPDATE equities SET exchange = exchange_full")...
def _downgrade_v4(op): """ Downgrades assets db by copying the `exchange_full` column to `exchange`, then dropping the `exchange_full` column. """ op.drop_index('ix_equities_fuzzy_symbol') op.drop_index('ix_equities_company_symbol') op.execute("UPDATE equities SET exchange = exchange_full")...
[ "Downgrades", "assets", "db", "by", "copying", "the", "exchange_full", "column", "to", "exchange", "then", "dropping", "the", "exchange_full", "column", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/asset_db_migrations.py#L264-L282
[ "def", "_downgrade_v4", "(", "op", ")", ":", "op", ".", "drop_index", "(", "'ix_equities_fuzzy_symbol'", ")", "op", ".", "drop_index", "(", "'ix_equities_company_symbol'", ")", "op", ".", "execute", "(", "\"UPDATE equities SET exchange = exchange_full\"", ")", "with",...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
_make_metrics_set_core
Create a family of metrics sets functions that read from the same metrics set mapping. Returns ------- metrics_sets : mappingproxy The mapping of metrics sets to load functions. register : callable The function which registers new metrics sets in the ``metrics_sets`` mapping...
zipline/finance/metrics/core.py
def _make_metrics_set_core(): """Create a family of metrics sets functions that read from the same metrics set mapping. Returns ------- metrics_sets : mappingproxy The mapping of metrics sets to load functions. register : callable The function which registers new metrics sets in...
def _make_metrics_set_core(): """Create a family of metrics sets functions that read from the same metrics set mapping. Returns ------- metrics_sets : mappingproxy The mapping of metrics sets to load functions. register : callable The function which registers new metrics sets in...
[ "Create", "a", "family", "of", "metrics", "sets", "functions", "that", "read", "from", "the", "same", "metrics", "set", "mapping", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/metrics/core.py#L6-L103
[ "def", "_make_metrics_set_core", "(", ")", ":", "_metrics_sets", "=", "{", "}", "# Expose _metrics_sets through a proxy so that users cannot mutate this", "# accidentally. Users may go through `register` to update this which will", "# warn when trampling another metrics set.", "metrics_sets"...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
validate_column_specs
Verify that the columns of ``events`` can be used by a EarningsEstimatesLoader to serve the BoundColumns described by `columns`.
zipline/pipeline/loaders/earnings_estimates.py
def validate_column_specs(events, columns): """ Verify that the columns of ``events`` can be used by a EarningsEstimatesLoader to serve the BoundColumns described by `columns`. """ required = required_estimates_fields(columns) received = set(events.columns) missing = required - received ...
def validate_column_specs(events, columns): """ Verify that the columns of ``events`` can be used by a EarningsEstimatesLoader to serve the BoundColumns described by `columns`. """ required = required_estimates_fields(columns) received = set(events.columns) missing = required - received ...
[ "Verify", "that", "the", "columns", "of", "events", "can", "be", "used", "by", "a", "EarningsEstimatesLoader", "to", "serve", "the", "BoundColumns", "described", "by", "columns", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/earnings_estimates.py#L74-L92
[ "def", "validate_column_specs", "(", "events", ",", "columns", ")", ":", "required", "=", "required_estimates_fields", "(", "columns", ")", "received", "=", "set", "(", "events", ".", "columns", ")", "missing", "=", "required", "-", "received", "if", "missing"...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
EarningsEstimatesLoader.get_requested_quarter_data
Selects the requested data for each date. Parameters ---------- zero_qtr_data : pd.DataFrame The 'time zero' data for each calendar date per sid. zeroth_quarter_idx : pd.Index An index of calendar dates, sid, and normalized quarters, for only the rows...
zipline/pipeline/loaders/earnings_estimates.py
def get_requested_quarter_data(self, zero_qtr_data, zeroth_quarter_idx, stacked_last_per_qtr, num_announcements, dates): """ Sele...
def get_requested_quarter_data(self, zero_qtr_data, zeroth_quarter_idx, stacked_last_per_qtr, num_announcements, dates): """ Sele...
[ "Selects", "the", "requested", "data", "for", "each", "date", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/earnings_estimates.py#L190-L253
[ "def", "get_requested_quarter_data", "(", "self", ",", "zero_qtr_data", ",", "zeroth_quarter_idx", ",", "stacked_last_per_qtr", ",", "num_announcements", ",", "dates", ")", ":", "zero_qtr_data_idx", "=", "zero_qtr_data", ".", "index", "requested_qtr_idx", "=", "pd", "...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
EarningsEstimatesLoader.get_split_adjusted_asof_idx
Compute the index in `dates` where the split-adjusted-asof-date falls. This is the date up to which, and including which, we will need to unapply all adjustments for and then re-apply them as they come in. After this date, adjustments are applied as normal. Parameters ----------...
zipline/pipeline/loaders/earnings_estimates.py
def get_split_adjusted_asof_idx(self, dates): """ Compute the index in `dates` where the split-adjusted-asof-date falls. This is the date up to which, and including which, we will need to unapply all adjustments for and then re-apply them as they come in. After this date, adjustm...
def get_split_adjusted_asof_idx(self, dates): """ Compute the index in `dates` where the split-adjusted-asof-date falls. This is the date up to which, and including which, we will need to unapply all adjustments for and then re-apply them as they come in. After this date, adjustm...
[ "Compute", "the", "index", "in", "dates", "where", "the", "split", "-", "adjusted", "-", "asof", "-", "date", "falls", ".", "This", "is", "the", "date", "up", "to", "which", "and", "including", "which", "we", "will", "need", "to", "unapply", "all", "ad...
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/earnings_estimates.py#L255-L280
[ "def", "get_split_adjusted_asof_idx", "(", "self", ",", "dates", ")", ":", "split_adjusted_asof_idx", "=", "dates", ".", "searchsorted", "(", "self", ".", "_split_adjusted_asof", ")", "# The split-asof date is after the date index.", "if", "split_adjusted_asof_idx", "==", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
EarningsEstimatesLoader.collect_overwrites_for_sid
Given a sid, collect all overwrites that should be applied for this sid at each quarter boundary. Parameters ---------- group : pd.DataFrame The data for `sid`. dates : pd.DatetimeIndex The calendar dates for which estimates data is requested. req...
zipline/pipeline/loaders/earnings_estimates.py
def collect_overwrites_for_sid(self, group, dates, requested_qtr_data, last_per_qtr, sid_idx, columns, ...
def collect_overwrites_for_sid(self, group, dates, requested_qtr_data, last_per_qtr, sid_idx, columns, ...
[ "Given", "a", "sid", "collect", "all", "overwrites", "that", "should", "be", "applied", "for", "this", "sid", "at", "each", "quarter", "boundary", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/earnings_estimates.py#L282-L353
[ "def", "collect_overwrites_for_sid", "(", "self", ",", "group", ",", "dates", ",", "requested_qtr_data", ",", "last_per_qtr", ",", "sid_idx", ",", "columns", ",", "all_adjustments_for_sid", ",", "sid", ")", ":", "# If data was requested for only 1 date, there can never be...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
EarningsEstimatesLoader.merge_into_adjustments_for_all_sids
Merge adjustments for a particular sid into a dictionary containing adjustments for all sids. Parameters ---------- all_adjustments_for_sid : dict[int -> AdjustedArray] All adjustments for a particular sid. col_to_all_adjustments : dict[int -> AdjustedArray] ...
zipline/pipeline/loaders/earnings_estimates.py
def merge_into_adjustments_for_all_sids(self, all_adjustments_for_sid, col_to_all_adjustments): """ Merge adjustments for a particular sid into a dictionary containing adjustments for all sids. Param...
def merge_into_adjustments_for_all_sids(self, all_adjustments_for_sid, col_to_all_adjustments): """ Merge adjustments for a particular sid into a dictionary containing adjustments for all sids. Param...
[ "Merge", "adjustments", "for", "a", "particular", "sid", "into", "a", "dictionary", "containing", "adjustments", "for", "all", "sids", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/earnings_estimates.py#L406-L429
[ "def", "merge_into_adjustments_for_all_sids", "(", "self", ",", "all_adjustments_for_sid", ",", "col_to_all_adjustments", ")", ":", "for", "col_name", "in", "all_adjustments_for_sid", ":", "if", "col_name", "not", "in", "col_to_all_adjustments", ":", "col_to_all_adjustments...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
EarningsEstimatesLoader.get_adjustments
Creates an AdjustedArray from the given estimates data for the given dates. Parameters ---------- zero_qtr_data : pd.DataFrame The 'time zero' data for each calendar date per sid. requested_qtr_data : pd.DataFrame The requested quarter data for each calen...
zipline/pipeline/loaders/earnings_estimates.py
def get_adjustments(self, zero_qtr_data, requested_qtr_data, last_per_qtr, dates, assets, columns, **kwargs): """ Creates an AdjustedArr...
def get_adjustments(self, zero_qtr_data, requested_qtr_data, last_per_qtr, dates, assets, columns, **kwargs): """ Creates an AdjustedArr...
[ "Creates", "an", "AdjustedArray", "from", "the", "given", "estimates", "data", "for", "the", "given", "dates", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/earnings_estimates.py#L431-L490
[ "def", "get_adjustments", "(", "self", ",", "zero_qtr_data", ",", "requested_qtr_data", ",", "last_per_qtr", ",", "dates", ",", "assets", ",", "columns", ",", "*", "*", "kwargs", ")", ":", "zero_qtr_data", ".", "sort_index", "(", "inplace", "=", "True", ")",...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
EarningsEstimatesLoader.create_overwrites_for_quarter
Add entries to the dictionary of columns to adjustments for the given sid and the given quarter. Parameters ---------- col_to_overwrites : dict [column_name -> list of ArrayAdjustment] A dictionary mapping column names to all overwrites for those columns. ...
zipline/pipeline/loaders/earnings_estimates.py
def create_overwrites_for_quarter(self, col_to_overwrites, next_qtr_start_idx, last_per_qtr, quarters_with_estimates_for_sid, requ...
def create_overwrites_for_quarter(self, col_to_overwrites, next_qtr_start_idx, last_per_qtr, quarters_with_estimates_for_sid, requ...
[ "Add", "entries", "to", "the", "dictionary", "of", "columns", "to", "adjustments", "for", "the", "given", "sid", "and", "the", "given", "quarter", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/earnings_estimates.py#L492-L563
[ "def", "create_overwrites_for_quarter", "(", "self", ",", "col_to_overwrites", ",", "next_qtr_start_idx", ",", "last_per_qtr", ",", "quarters_with_estimates_for_sid", ",", "requested_quarter", ",", "sid", ",", "sid_idx", ",", "columns", ")", ":", "for", "col", "in", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
EarningsEstimatesLoader.get_last_data_per_qtr
Determine the last piece of information we know for each column on each date in the index for each sid and quarter. Parameters ---------- assets_with_data : pd.Index Index of all assets that appear in the raw data given to the loader. columns : iterable o...
zipline/pipeline/loaders/earnings_estimates.py
def get_last_data_per_qtr(self, assets_with_data, columns, dates, data_query_cutoff_times): """ Determine the last piece of information we know for each column on each date in ...
def get_last_data_per_qtr(self, assets_with_data, columns, dates, data_query_cutoff_times): """ Determine the last piece of information we know for each column on each date in ...
[ "Determine", "the", "last", "piece", "of", "information", "we", "know", "for", "each", "column", "on", "each", "date", "in", "the", "index", "for", "each", "sid", "and", "quarter", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/earnings_estimates.py#L667-L725
[ "def", "get_last_data_per_qtr", "(", "self", ",", "assets_with_data", ",", "columns", ",", "dates", ",", "data_query_cutoff_times", ")", ":", "# Get a DataFrame indexed by date with a MultiIndex of columns of", "# [self.estimates.columns, normalized_quarters, sid], where each cell", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
PreviousEarningsEstimatesLoader.get_zeroth_quarter_idx
Filters for releases that are on or after each simulation date and determines the previous quarter by picking out the most recent release relative to each date in the index. Parameters ---------- stacked_last_per_qtr : pd.DataFrame A DataFrame with index of calendar ...
zipline/pipeline/loaders/earnings_estimates.py
def get_zeroth_quarter_idx(self, stacked_last_per_qtr): """ Filters for releases that are on or after each simulation date and determines the previous quarter by picking out the most recent release relative to each date in the index. Parameters ---------- stacked...
def get_zeroth_quarter_idx(self, stacked_last_per_qtr): """ Filters for releases that are on or after each simulation date and determines the previous quarter by picking out the most recent release relative to each date in the index. Parameters ---------- stacked...
[ "Filters", "for", "releases", "that", "are", "on", "or", "after", "each", "simulation", "date", "and", "determines", "the", "previous", "quarter", "by", "picking", "out", "the", "most", "recent", "release", "relative", "to", "each", "date", "in", "the", "ind...
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/earnings_estimates.py#L810-L838
[ "def", "get_zeroth_quarter_idx", "(", "self", ",", "stacked_last_per_qtr", ")", ":", "previous_releases_per_date", "=", "stacked_last_per_qtr", ".", "loc", "[", "stacked_last_per_qtr", "[", "EVENT_DATE_FIELD_NAME", "]", "<=", "stacked_last_per_qtr", ".", "index", ".", "...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
SplitAdjustedEstimatesLoader.get_adjustments_for_sid
Collects both overwrites and adjustments for a particular sid. Parameters ---------- split_adjusted_asof_idx : int The integer index of the date on which the data was split-adjusted. split_adjusted_cols_for_group : list of str The names of requested columns that ...
zipline/pipeline/loaders/earnings_estimates.py
def get_adjustments_for_sid(self, group, dates, requested_qtr_data, last_per_qtr, sid_to_idx, columns, ...
def get_adjustments_for_sid(self, group, dates, requested_qtr_data, last_per_qtr, sid_to_idx, columns, ...
[ "Collects", "both", "overwrites", "and", "adjustments", "for", "a", "particular", "sid", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/earnings_estimates.py#L907-L965
[ "def", "get_adjustments_for_sid", "(", "self", ",", "group", ",", "dates", ",", "requested_qtr_data", ",", "last_per_qtr", ",", "sid_to_idx", ",", "columns", ",", "col_to_all_adjustments", ",", "split_adjusted_asof_idx", "=", "None", ",", "split_adjusted_cols_for_group"...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
SplitAdjustedEstimatesLoader.get_adjustments
Calculates both split adjustments and overwrites for all sids.
zipline/pipeline/loaders/earnings_estimates.py
def get_adjustments(self, zero_qtr_data, requested_qtr_data, last_per_qtr, dates, assets, columns, **kwargs): """ Calculates both split ...
def get_adjustments(self, zero_qtr_data, requested_qtr_data, last_per_qtr, dates, assets, columns, **kwargs): """ Calculates both split ...
[ "Calculates", "both", "split", "adjustments", "and", "overwrites", "for", "all", "sids", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/earnings_estimates.py#L967-L996
[ "def", "get_adjustments", "(", "self", ",", "zero_qtr_data", ",", "requested_qtr_data", ",", "last_per_qtr", ",", "dates", ",", "assets", ",", "columns", ",", "*", "*", "kwargs", ")", ":", "split_adjusted_cols_for_group", "=", "[", "self", ".", "name_map", "["...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
SplitAdjustedEstimatesLoader.determine_end_idx_for_adjustment
Determines the date until which the adjustment at the given date index should be applied for the given quarter. Parameters ---------- adjustment_ts : pd.Timestamp The timestamp at which the adjustment occurs. dates : pd.DatetimeIndex The calendar dates ov...
zipline/pipeline/loaders/earnings_estimates.py
def determine_end_idx_for_adjustment(self, adjustment_ts, dates, upper_bound, requested_quarter, sid_estimates): ...
def determine_end_idx_for_adjustment(self, adjustment_ts, dates, upper_bound, requested_quarter, sid_estimates): ...
[ "Determines", "the", "date", "until", "which", "the", "adjustment", "at", "the", "given", "date", "index", "should", "be", "applied", "for", "the", "given", "quarter", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/earnings_estimates.py#L998-L1051
[ "def", "determine_end_idx_for_adjustment", "(", "self", ",", "adjustment_ts", ",", "dates", ",", "upper_bound", ",", "requested_quarter", ",", "sid_estimates", ")", ":", "end_idx", "=", "upper_bound", "# Find the next newest kd that happens on or after", "# the date of this a...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
SplitAdjustedEstimatesLoader.collect_pre_split_asof_date_adjustments
Collect split adjustments that occur before the split-adjusted-asof-date. All those adjustments must first be UN-applied at the first date index and then re-applied on the appropriate dates in order to match point in time share pricing data. Parameters ---------- split_a...
zipline/pipeline/loaders/earnings_estimates.py
def collect_pre_split_asof_date_adjustments( self, split_adjusted_asof_date_idx, sid_idx, pre_adjustments, requested_split_adjusted_columns ): """ Collect split adjustments that occur before the split-adjusted-asof-date. All those a...
def collect_pre_split_asof_date_adjustments( self, split_adjusted_asof_date_idx, sid_idx, pre_adjustments, requested_split_adjusted_columns ): """ Collect split adjustments that occur before the split-adjusted-asof-date. All those a...
[ "Collect", "split", "adjustments", "that", "occur", "before", "the", "split", "-", "adjusted", "-", "asof", "-", "date", ".", "All", "those", "adjustments", "must", "first", "be", "UN", "-", "applied", "at", "the", "first", "date", "index", "and", "then", ...
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/earnings_estimates.py#L1053-L1115
[ "def", "collect_pre_split_asof_date_adjustments", "(", "self", ",", "split_adjusted_asof_date_idx", ",", "sid_idx", ",", "pre_adjustments", ",", "requested_split_adjusted_columns", ")", ":", "col_to_split_adjustments", "=", "{", "}", "if", "len", "(", "pre_adjustments", "...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
SplitAdjustedEstimatesLoader.collect_post_asof_split_adjustments
Collect split adjustments that occur after the split-adjusted-asof-date. Each adjustment needs to be applied to all dates on which knowledge for the requested quarter was older than the date of the adjustment. Parameters ---------- post_adjustments : tuple(list(float), l...
zipline/pipeline/loaders/earnings_estimates.py
def collect_post_asof_split_adjustments(self, post_adjustments, requested_qtr_data, sid, sid_idx, si...
def collect_post_asof_split_adjustments(self, post_adjustments, requested_qtr_data, sid, sid_idx, si...
[ "Collect", "split", "adjustments", "that", "occur", "after", "the", "split", "-", "adjusted", "-", "asof", "-", "date", ".", "Each", "adjustment", "needs", "to", "be", "applied", "to", "all", "dates", "on", "which", "knowledge", "for", "the", "requested", ...
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/earnings_estimates.py#L1117-L1215
[ "def", "collect_post_asof_split_adjustments", "(", "self", ",", "post_adjustments", ",", "requested_qtr_data", ",", "sid", ",", "sid_idx", ",", "sid_estimates", ",", "requested_split_adjusted_columns", ")", ":", "col_to_split_adjustments", "=", "{", "}", "if", "post_adj...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
SplitAdjustedEstimatesLoader.retrieve_split_adjustment_data_for_sid
dates : pd.DatetimeIndex The calendar dates. sid : int The sid for which we want to retrieve adjustments. split_adjusted_asof_idx : int The index in `dates` as-of which the data is split adjusted. Returns ------- pre_adjustments : tuple(list(f...
zipline/pipeline/loaders/earnings_estimates.py
def retrieve_split_adjustment_data_for_sid(self, dates, sid, split_adjusted_asof_idx): """ dates : pd.DatetimeIndex The calendar dates. sid : i...
def retrieve_split_adjustment_data_for_sid(self, dates, sid, split_adjusted_asof_idx): """ dates : pd.DatetimeIndex The calendar dates. sid : i...
[ "dates", ":", "pd", ".", "DatetimeIndex", "The", "calendar", "dates", ".", "sid", ":", "int", "The", "sid", "for", "which", "we", "want", "to", "retrieve", "adjustments", ".", "split_adjusted_asof_idx", ":", "int", "The", "index", "in", "dates", "as", "-",...
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/earnings_estimates.py#L1217-L1265
[ "def", "retrieve_split_adjustment_data_for_sid", "(", "self", ",", "dates", ",", "sid", ",", "split_adjusted_asof_idx", ")", ":", "adjustments", "=", "self", ".", "_split_adjustments", ".", "get_adjustments_for_sid", "(", "'splits'", ",", "sid", ")", "sorted", "(", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
SplitAdjustedEstimatesLoader.merge_split_adjustments_with_overwrites
Merge split adjustments with the dict containing overwrites. Parameters ---------- pre : dict[str -> dict[int -> list]] The adjustments that occur before the split-adjusted-asof-date. post : dict[str -> dict[int -> list]] The adjustments that occur after the spli...
zipline/pipeline/loaders/earnings_estimates.py
def merge_split_adjustments_with_overwrites( self, pre, post, overwrites, requested_split_adjusted_columns ): """ Merge split adjustments with the dict containing overwrites. Parameters ---------- pre : dict[str -> dict[int -> list]] ...
def merge_split_adjustments_with_overwrites( self, pre, post, overwrites, requested_split_adjusted_columns ): """ Merge split adjustments with the dict containing overwrites. Parameters ---------- pre : dict[str -> dict[int -> list]] ...
[ "Merge", "split", "adjustments", "with", "the", "dict", "containing", "overwrites", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/earnings_estimates.py#L1294-L1336
[ "def", "merge_split_adjustments_with_overwrites", "(", "self", ",", "pre", ",", "post", ",", "overwrites", ",", "requested_split_adjusted_columns", ")", ":", "for", "column_name", "in", "requested_split_adjusted_columns", ":", "# We can do a merge here because the timestamps in...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
PreviousSplitAdjustedEarningsEstimatesLoader.collect_split_adjustments
Collect split adjustments for previous quarters and apply them to the given dictionary of splits for the given sid. Since overwrites just replace all estimates before the new quarter with NaN, we don't need to worry about re-applying split adjustments. Parameters ---------- ...
zipline/pipeline/loaders/earnings_estimates.py
def collect_split_adjustments(self, adjustments_for_sid, requested_qtr_data, dates, sid, sid_idx, sid_estimates, ...
def collect_split_adjustments(self, adjustments_for_sid, requested_qtr_data, dates, sid, sid_idx, sid_estimates, ...
[ "Collect", "split", "adjustments", "for", "previous", "quarters", "and", "apply", "them", "to", "the", "given", "dictionary", "of", "splits", "for", "the", "given", "sid", ".", "Since", "overwrites", "just", "replace", "all", "estimates", "before", "the", "new...
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/earnings_estimates.py#L1342-L1401
[ "def", "collect_split_adjustments", "(", "self", ",", "adjustments_for_sid", ",", "requested_qtr_data", ",", "dates", ",", "sid", ",", "sid_idx", ",", "sid_estimates", ",", "split_adjusted_asof_idx", ",", "pre_adjustments", ",", "post_adjustments", ",", "requested_split...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
NextSplitAdjustedEarningsEstimatesLoader.collect_split_adjustments
Collect split adjustments for future quarters. Re-apply adjustments that would be overwritten by overwrites. Merge split adjustments with overwrites into the given dictionary of splits for the given sid. Parameters ---------- adjustments_for_sid : dict[str -> dict[int -> list]] ...
zipline/pipeline/loaders/earnings_estimates.py
def collect_split_adjustments(self, adjustments_for_sid, requested_qtr_data, dates, sid, sid_idx, sid_estimates, ...
def collect_split_adjustments(self, adjustments_for_sid, requested_qtr_data, dates, sid, sid_idx, sid_estimates, ...
[ "Collect", "split", "adjustments", "for", "future", "quarters", ".", "Re", "-", "apply", "adjustments", "that", "would", "be", "overwritten", "by", "overwrites", ".", "Merge", "split", "adjustments", "with", "overwrites", "into", "the", "given", "dictionary", "o...
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/earnings_estimates.py#L1407-L1534
[ "def", "collect_split_adjustments", "(", "self", ",", "adjustments_for_sid", ",", "requested_qtr_data", ",", "dates", ",", "sid", ",", "sid_idx", ",", "sid_estimates", ",", "split_adjusted_asof_idx", ",", "pre_adjustments", ",", "post_adjustments", ",", "requested_split...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
_ExponentialWeightedFactor.from_span
Convenience constructor for passing `decay_rate` in terms of `span`. Forwards `decay_rate` as `1 - (2.0 / (1 + span))`. This provides the behavior equivalent to passing `span` to pandas.ewma. Examples -------- .. code-block:: python # Equivalent to: # ...
zipline/pipeline/factors/basic.py
def from_span(cls, inputs, window_length, span, **kwargs): """ Convenience constructor for passing `decay_rate` in terms of `span`. Forwards `decay_rate` as `1 - (2.0 / (1 + span))`. This provides the behavior equivalent to passing `span` to pandas.ewma. Examples -----...
def from_span(cls, inputs, window_length, span, **kwargs): """ Convenience constructor for passing `decay_rate` in terms of `span`. Forwards `decay_rate` as `1 - (2.0 / (1 + span))`. This provides the behavior equivalent to passing `span` to pandas.ewma. Examples -----...
[ "Convenience", "constructor", "for", "passing", "decay_rate", "in", "terms", "of", "span", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/factors/basic.py#L198-L240
[ "def", "from_span", "(", "cls", ",", "inputs", ",", "window_length", ",", "span", ",", "*", "*", "kwargs", ")", ":", "if", "span", "<=", "1", ":", "raise", "ValueError", "(", "\"`span` must be a positive number. %s was passed.\"", "%", "span", ")", "decay_rate...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
_ExponentialWeightedFactor.from_halflife
Convenience constructor for passing ``decay_rate`` in terms of half life. Forwards ``decay_rate`` as ``exp(log(.5) / halflife)``. This provides the behavior equivalent to passing `halflife` to pandas.ewma. Examples -------- .. code-block:: python # Equival...
zipline/pipeline/factors/basic.py
def from_halflife(cls, inputs, window_length, halflife, **kwargs): """ Convenience constructor for passing ``decay_rate`` in terms of half life. Forwards ``decay_rate`` as ``exp(log(.5) / halflife)``. This provides the behavior equivalent to passing `halflife` to pandas.ewma. ...
def from_halflife(cls, inputs, window_length, halflife, **kwargs): """ Convenience constructor for passing ``decay_rate`` in terms of half life. Forwards ``decay_rate`` as ``exp(log(.5) / halflife)``. This provides the behavior equivalent to passing `halflife` to pandas.ewma. ...
[ "Convenience", "constructor", "for", "passing", "decay_rate", "in", "terms", "of", "half", "life", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/factors/basic.py#L244-L286
[ "def", "from_halflife", "(", "cls", ",", "inputs", ",", "window_length", ",", "halflife", ",", "*", "*", "kwargs", ")", ":", "if", "halflife", "<=", "0", ":", "raise", "ValueError", "(", "\"`span` must be a positive number. %s was passed.\"", "%", "halflife", ")...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
_ExponentialWeightedFactor.from_center_of_mass
Convenience constructor for passing `decay_rate` in terms of center of mass. Forwards `decay_rate` as `1 - (1 / 1 + center_of_mass)`. This provides behavior equivalent to passing `center_of_mass` to pandas.ewma. Examples -------- .. code-block:: python # E...
zipline/pipeline/factors/basic.py
def from_center_of_mass(cls, inputs, window_length, center_of_mass, **kwargs): """ Convenience constructor for passing `decay_rate` in terms of center of mass. Forwards `decay...
def from_center_of_mass(cls, inputs, window_length, center_of_mass, **kwargs): """ Convenience constructor for passing `decay_rate` in terms of center of mass. Forwards `decay...
[ "Convenience", "constructor", "for", "passing", "decay_rate", "in", "terms", "of", "center", "of", "mass", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/factors/basic.py#L289-L328
[ "def", "from_center_of_mass", "(", "cls", ",", "inputs", ",", "window_length", ",", "center_of_mass", ",", "*", "*", "kwargs", ")", ":", "return", "cls", "(", "inputs", "=", "inputs", ",", "window_length", "=", "window_length", ",", "decay_rate", "=", "(", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
tolerant_equals
Check if a and b are equal with some tolerance. Parameters ---------- a, b : float The floats to check for equality. atol : float, optional The absolute tolerance. rtol : float, optional The relative tolerance. equal_nan : bool, optional Should NaN compare equal?...
zipline/utils/math_utils.py
def tolerant_equals(a, b, atol=10e-7, rtol=10e-7, equal_nan=False): """Check if a and b are equal with some tolerance. Parameters ---------- a, b : float The floats to check for equality. atol : float, optional The absolute tolerance. rtol : float, optional The relative ...
def tolerant_equals(a, b, atol=10e-7, rtol=10e-7, equal_nan=False): """Check if a and b are equal with some tolerance. Parameters ---------- a, b : float The floats to check for equality. atol : float, optional The absolute tolerance. rtol : float, optional The relative ...
[ "Check", "if", "a", "and", "b", "are", "equal", "with", "some", "tolerance", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/math_utils.py#L21-L47
[ "def", "tolerant_equals", "(", "a", ",", "b", ",", "atol", "=", "10e-7", ",", "rtol", "=", "10e-7", ",", "equal_nan", "=", "False", ")", ":", "if", "equal_nan", "and", "isnan", "(", "a", ")", "and", "isnan", "(", "b", ")", ":", "return", "True", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
round_if_near_integer
Round a to the nearest integer if that integer is within an epsilon of a.
zipline/utils/math_utils.py
def round_if_near_integer(a, epsilon=1e-4): """ Round a to the nearest integer if that integer is within an epsilon of a. """ if abs(a - round(a)) <= epsilon: return round(a) else: return a
def round_if_near_integer(a, epsilon=1e-4): """ Round a to the nearest integer if that integer is within an epsilon of a. """ if abs(a - round(a)) <= epsilon: return round(a) else: return a
[ "Round", "a", "to", "the", "nearest", "integer", "if", "that", "integer", "is", "within", "an", "epsilon", "of", "a", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/math_utils.py#L72-L80
[ "def", "round_if_near_integer", "(", "a", ",", "epsilon", "=", "1e-4", ")", ":", "if", "abs", "(", "a", "-", "round", "(", "a", ")", ")", "<=", "epsilon", ":", "return", "round", "(", "a", ")", "else", ":", "return", "a" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
coerce_numbers_to_my_dtype
A decorator for methods whose signature is f(self, other) that coerces ``other`` to ``self.dtype``. This is used to make comparison operations between numbers and `Factor` instances work independently of whether the user supplies a float or integer literal. For example, if I write:: my_fi...
zipline/pipeline/factors/factor.py
def coerce_numbers_to_my_dtype(f): """ A decorator for methods whose signature is f(self, other) that coerces ``other`` to ``self.dtype``. This is used to make comparison operations between numbers and `Factor` instances work independently of whether the user supplies a float or integer literal...
def coerce_numbers_to_my_dtype(f): """ A decorator for methods whose signature is f(self, other) that coerces ``other`` to ``self.dtype``. This is used to make comparison operations between numbers and `Factor` instances work independently of whether the user supplies a float or integer literal...
[ "A", "decorator", "for", "methods", "whose", "signature", "is", "f", "(", "self", "other", ")", "that", "coerces", "other", "to", "self", ".", "dtype", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/factors/factor.py#L70-L91
[ "def", "coerce_numbers_to_my_dtype", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "method", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "Number", ")", ":", "other", "=", "coerce_to_dtype", "(", "self", ".", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
binop_return_dtype
Compute the expected return dtype for the given binary operator. Parameters ---------- op : str Operator symbol, (e.g. '+', '-', ...). left : numpy.dtype Dtype of left hand side. right : numpy.dtype Dtype of right hand side. Returns ------- outdtype : numpy.dtyp...
zipline/pipeline/factors/factor.py
def binop_return_dtype(op, left, right): """ Compute the expected return dtype for the given binary operator. Parameters ---------- op : str Operator symbol, (e.g. '+', '-', ...). left : numpy.dtype Dtype of left hand side. right : numpy.dtype Dtype of right hand sid...
def binop_return_dtype(op, left, right): """ Compute the expected return dtype for the given binary operator. Parameters ---------- op : str Operator symbol, (e.g. '+', '-', ...). left : numpy.dtype Dtype of left hand side. right : numpy.dtype Dtype of right hand sid...
[ "Compute", "the", "expected", "return", "dtype", "for", "the", "given", "binary", "operator", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/factors/factor.py#L101-L138
[ "def", "binop_return_dtype", "(", "op", ",", "left", ",", "right", ")", ":", "if", "is_comparison", "(", "op", ")", ":", "if", "left", "!=", "right", ":", "raise", "TypeError", "(", "\"Don't know how to compute {left} {op} {right}.\\n\"", "\"Comparisons are only sup...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
binary_operator
Factory function for making binary operator methods on a Factor subclass. Returns a function, "binary_operator" suitable for implementing functions like __add__.
zipline/pipeline/factors/factor.py
def binary_operator(op): """ Factory function for making binary operator methods on a Factor subclass. Returns a function, "binary_operator" suitable for implementing functions like __add__. """ # When combining a Factor with a NumericalExpression, we use this # attrgetter instance to defer...
def binary_operator(op): """ Factory function for making binary operator methods on a Factor subclass. Returns a function, "binary_operator" suitable for implementing functions like __add__. """ # When combining a Factor with a NumericalExpression, we use this # attrgetter instance to defer...
[ "Factory", "function", "for", "making", "binary", "operator", "methods", "on", "a", "Factor", "subclass", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/factors/factor.py#L141-L201
[ "def", "binary_operator", "(", "op", ")", ":", "# When combining a Factor with a NumericalExpression, we use this", "# attrgetter instance to defer to the commuted implementation of the", "# NumericalExpression operator.", "commuted_method_getter", "=", "attrgetter", "(", "method_name_for_...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
reflected_binary_operator
Factory function for making binary operator methods on a Factor. Returns a function, "reflected_binary_operator" suitable for implementing functions like __radd__.
zipline/pipeline/factors/factor.py
def reflected_binary_operator(op): """ Factory function for making binary operator methods on a Factor. Returns a function, "reflected_binary_operator" suitable for implementing functions like __radd__. """ assert not is_comparison(op) @with_name(method_name_for_op(op, commute=True)) @...
def reflected_binary_operator(op): """ Factory function for making binary operator methods on a Factor. Returns a function, "reflected_binary_operator" suitable for implementing functions like __radd__. """ assert not is_comparison(op) @with_name(method_name_for_op(op, commute=True)) @...
[ "Factory", "function", "for", "making", "binary", "operator", "methods", "on", "a", "Factor", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/factors/factor.py#L204-L240
[ "def", "reflected_binary_operator", "(", "op", ")", ":", "assert", "not", "is_comparison", "(", "op", ")", "@", "with_name", "(", "method_name_for_op", "(", "op", ",", "commute", "=", "True", ")", ")", "@", "coerce_numbers_to_my_dtype", "def", "reflected_binary_...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
unary_operator
Factory function for making unary operator methods for Factors.
zipline/pipeline/factors/factor.py
def unary_operator(op): """ Factory function for making unary operator methods for Factors. """ # Only negate is currently supported. valid_ops = {'-'} if op not in valid_ops: raise ValueError("Invalid unary operator %s." % op) @with_doc("Unary Operator: '%s'" % op) @with_name(u...
def unary_operator(op): """ Factory function for making unary operator methods for Factors. """ # Only negate is currently supported. valid_ops = {'-'} if op not in valid_ops: raise ValueError("Invalid unary operator %s." % op) @with_doc("Unary Operator: '%s'" % op) @with_name(u...
[ "Factory", "function", "for", "making", "unary", "operator", "methods", "for", "Factors", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/factors/factor.py#L243-L282
[ "def", "unary_operator", "(", "op", ")", ":", "# Only negate is currently supported.", "valid_ops", "=", "{", "'-'", "}", "if", "op", "not", "in", "valid_ops", ":", "raise", "ValueError", "(", "\"Invalid unary operator %s.\"", "%", "op", ")", "@", "with_doc", "(...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
function_application
Factory function for producing function application methods for Factor subclasses.
zipline/pipeline/factors/factor.py
def function_application(func): """ Factory function for producing function application methods for Factor subclasses. """ if func not in NUMEXPR_MATH_FUNCS: raise ValueError("Unsupported mathematical function '%s'" % func) @with_doc(func) @with_name(func) def mathfunc(self): ...
def function_application(func): """ Factory function for producing function application methods for Factor subclasses. """ if func not in NUMEXPR_MATH_FUNCS: raise ValueError("Unsupported mathematical function '%s'" % func) @with_doc(func) @with_name(func) def mathfunc(self): ...
[ "Factory", "function", "for", "producing", "function", "application", "methods", "for", "Factor", "subclasses", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/factors/factor.py#L285-L308
[ "def", "function_application", "(", "func", ")", ":", "if", "func", "not", "in", "NUMEXPR_MATH_FUNCS", ":", "raise", "ValueError", "(", "\"Unsupported mathematical function '%s'\"", "%", "func", ")", "@", "with_doc", "(", "func", ")", "@", "with_name", "(", "fun...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
winsorize
This implementation is based on scipy.stats.mstats.winsorize
zipline/pipeline/factors/factor.py
def winsorize(row, min_percentile, max_percentile): """ This implementation is based on scipy.stats.mstats.winsorize """ a = row.copy() nan_count = isnan(row).sum() nonnan_count = a.size - nan_count # NOTE: argsort() sorts nans to the end of the array. idx = a.argsort() # Set value...
def winsorize(row, min_percentile, max_percentile): """ This implementation is based on scipy.stats.mstats.winsorize """ a = row.copy() nan_count = isnan(row).sum() nonnan_count = a.size - nan_count # NOTE: argsort() sorts nans to the end of the array. idx = a.argsort() # Set value...
[ "This", "implementation", "is", "based", "on", "scipy", ".", "stats", ".", "mstats", ".", "winsorize" ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/factors/factor.py#L1671-L1698
[ "def", "winsorize", "(", "row", ",", "min_percentile", ",", "max_percentile", ")", ":", "a", "=", "row", ".", "copy", "(", ")", "nan_count", "=", "isnan", "(", "row", ")", ".", "sum", "(", ")", "nonnan_count", "=", "a", ".", "size", "-", "nan_count",...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
Factor.demean
Construct a Factor that computes ``self`` and subtracts the mean from row of the result. If ``mask`` is supplied, ignore values where ``mask`` returns False when computing row means, and output NaN anywhere the mask is False. If ``groupby`` is supplied, compute by partitioning each row...
zipline/pipeline/factors/factor.py
def demean(self, mask=NotSpecified, groupby=NotSpecified): """ Construct a Factor that computes ``self`` and subtracts the mean from row of the result. If ``mask`` is supplied, ignore values where ``mask`` returns False when computing row means, and output NaN anywhere the mask ...
def demean(self, mask=NotSpecified, groupby=NotSpecified): """ Construct a Factor that computes ``self`` and subtracts the mean from row of the result. If ``mask`` is supplied, ignore values where ``mask`` returns False when computing row means, and output NaN anywhere the mask ...
[ "Construct", "a", "Factor", "that", "computes", "self", "and", "subtracts", "the", "mean", "from", "row", "of", "the", "result", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/factors/factor.py#L402-L524
[ "def", "demean", "(", "self", ",", "mask", "=", "NotSpecified", ",", "groupby", "=", "NotSpecified", ")", ":", "return", "GroupedRowTransform", "(", "transform", "=", "demean", ",", "transform_args", "=", "(", ")", ",", "factor", "=", "self", ",", "groupby...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
Factor.zscore
Construct a Factor that Z-Scores each day's results. The Z-Score of a row is defined as:: (row - row.mean()) / row.stddev() If ``mask`` is supplied, ignore values where ``mask`` returns False when computing row means and standard deviations, and output NaN anywhere the mas...
zipline/pipeline/factors/factor.py
def zscore(self, mask=NotSpecified, groupby=NotSpecified): """ Construct a Factor that Z-Scores each day's results. The Z-Score of a row is defined as:: (row - row.mean()) / row.stddev() If ``mask`` is supplied, ignore values where ``mask`` returns False when compu...
def zscore(self, mask=NotSpecified, groupby=NotSpecified): """ Construct a Factor that Z-Scores each day's results. The Z-Score of a row is defined as:: (row - row.mean()) / row.stddev() If ``mask`` is supplied, ignore values where ``mask`` returns False when compu...
[ "Construct", "a", "Factor", "that", "Z", "-", "Scores", "each", "day", "s", "results", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/factors/factor.py#L531-L591
[ "def", "zscore", "(", "self", ",", "mask", "=", "NotSpecified", ",", "groupby", "=", "NotSpecified", ")", ":", "return", "GroupedRowTransform", "(", "transform", "=", "zscore", ",", "transform_args", "=", "(", ")", ",", "factor", "=", "self", ",", "groupby...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
Factor.rank
Construct a new Factor representing the sorted rank of each column within each row. Parameters ---------- method : str, {'ordinal', 'min', 'max', 'dense', 'average'} The method used to assign ranks to tied elements. See `scipy.stats.rankdata` for a full descripti...
zipline/pipeline/factors/factor.py
def rank(self, method='ordinal', ascending=True, mask=NotSpecified, groupby=NotSpecified): """ Construct a new Factor representing the sorted rank of each column within each row. Parameters ---------- method : str, {'or...
def rank(self, method='ordinal', ascending=True, mask=NotSpecified, groupby=NotSpecified): """ Construct a new Factor representing the sorted rank of each column within each row. Parameters ---------- method : str, {'or...
[ "Construct", "a", "new", "Factor", "representing", "the", "sorted", "rank", "of", "each", "column", "within", "each", "row", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/factors/factor.py#L593-L651
[ "def", "rank", "(", "self", ",", "method", "=", "'ordinal'", ",", "ascending", "=", "True", ",", "mask", "=", "NotSpecified", ",", "groupby", "=", "NotSpecified", ")", ":", "if", "groupby", "is", "NotSpecified", ":", "return", "Rank", "(", "self", ",", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
Factor.pearsonr
Construct a new Factor that computes rolling pearson correlation coefficients between `target` and the columns of `self`. This method can only be called on factors which are deemed safe for use as inputs to other factors. This includes `Returns` and any factors created from `Factor.rank...
zipline/pipeline/factors/factor.py
def pearsonr(self, target, correlation_length, mask=NotSpecified): """ Construct a new Factor that computes rolling pearson correlation coefficients between `target` and the columns of `self`. This method can only be called on factors which are deemed safe for use as inputs to o...
def pearsonr(self, target, correlation_length, mask=NotSpecified): """ Construct a new Factor that computes rolling pearson correlation coefficients between `target` and the columns of `self`. This method can only be called on factors which are deemed safe for use as inputs to o...
[ "Construct", "a", "new", "Factor", "that", "computes", "rolling", "pearson", "correlation", "coefficients", "between", "target", "and", "the", "columns", "of", "self", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/factors/factor.py#L656-L716
[ "def", "pearsonr", "(", "self", ",", "target", ",", "correlation_length", ",", "mask", "=", "NotSpecified", ")", ":", "from", ".", "statistical", "import", "RollingPearson", "return", "RollingPearson", "(", "base_factor", "=", "self", ",", "target", "=", "targ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
Factor.spearmanr
Construct a new Factor that computes rolling spearman rank correlation coefficients between `target` and the columns of `self`. This method can only be called on factors which are deemed safe for use as inputs to other factors. This includes `Returns` and any factors created from `Facto...
zipline/pipeline/factors/factor.py
def spearmanr(self, target, correlation_length, mask=NotSpecified): """ Construct a new Factor that computes rolling spearman rank correlation coefficients between `target` and the columns of `self`. This method can only be called on factors which are deemed safe for use as inpu...
def spearmanr(self, target, correlation_length, mask=NotSpecified): """ Construct a new Factor that computes rolling spearman rank correlation coefficients between `target` and the columns of `self`. This method can only be called on factors which are deemed safe for use as inpu...
[ "Construct", "a", "new", "Factor", "that", "computes", "rolling", "spearman", "rank", "correlation", "coefficients", "between", "target", "and", "the", "columns", "of", "self", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/factors/factor.py#L721-L781
[ "def", "spearmanr", "(", "self", ",", "target", ",", "correlation_length", ",", "mask", "=", "NotSpecified", ")", ":", "from", ".", "statistical", "import", "RollingSpearman", "return", "RollingSpearman", "(", "base_factor", "=", "self", ",", "target", "=", "t...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
Factor.linear_regression
Construct a new Factor that performs an ordinary least-squares regression predicting the columns of `self` from `target`. This method can only be called on factors which are deemed safe for use as inputs to other factors. This includes `Returns` and any factors created from `Factor.rank...
zipline/pipeline/factors/factor.py
def linear_regression(self, target, regression_length, mask=NotSpecified): """ Construct a new Factor that performs an ordinary least-squares regression predicting the columns of `self` from `target`. This method can only be called on factors which are deemed safe for use as inp...
def linear_regression(self, target, regression_length, mask=NotSpecified): """ Construct a new Factor that performs an ordinary least-squares regression predicting the columns of `self` from `target`. This method can only be called on factors which are deemed safe for use as inp...
[ "Construct", "a", "new", "Factor", "that", "performs", "an", "ordinary", "least", "-", "squares", "regression", "predicting", "the", "columns", "of", "self", "from", "target", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/factors/factor.py#L786-L843
[ "def", "linear_regression", "(", "self", ",", "target", ",", "regression_length", ",", "mask", "=", "NotSpecified", ")", ":", "from", ".", "statistical", "import", "RollingLinearRegression", "return", "RollingLinearRegression", "(", "dependent", "=", "self", ",", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
Factor.winsorize
Construct a new factor that winsorizes the result of this factor. Winsorizing changes values ranked less than the minimum percentile to the value at the minimum percentile. Similarly, values ranking above the maximum percentile are changed to the value at the maximum percentile. ...
zipline/pipeline/factors/factor.py
def winsorize(self, min_percentile, max_percentile, mask=NotSpecified, groupby=NotSpecified): """ Construct a new factor that winsorizes the result of this factor. Winsorizing changes values ranked less than the minimum per...
def winsorize(self, min_percentile, max_percentile, mask=NotSpecified, groupby=NotSpecified): """ Construct a new factor that winsorizes the result of this factor. Winsorizing changes values ranked less than the minimum per...
[ "Construct", "a", "new", "factor", "that", "winsorizes", "the", "result", "of", "this", "factor", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/factors/factor.py#L852-L947
[ "def", "winsorize", "(", "self", ",", "min_percentile", ",", "max_percentile", ",", "mask", "=", "NotSpecified", ",", "groupby", "=", "NotSpecified", ")", ":", "if", "not", "0.0", "<=", "min_percentile", "<", "max_percentile", "<=", "1.0", ":", "raise", "Bad...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
Factor.quantiles
Construct a Classifier computing quantiles of the output of ``self``. Every non-NaN data point the output is labelled with an integer value from 0 to (bins - 1). NaNs are labelled with -1. If ``mask`` is supplied, ignore data points in locations for which ``mask`` produces False, and ...
zipline/pipeline/factors/factor.py
def quantiles(self, bins, mask=NotSpecified): """ Construct a Classifier computing quantiles of the output of ``self``. Every non-NaN data point the output is labelled with an integer value from 0 to (bins - 1). NaNs are labelled with -1. If ``mask`` is supplied, ignore data p...
def quantiles(self, bins, mask=NotSpecified): """ Construct a Classifier computing quantiles of the output of ``self``. Every non-NaN data point the output is labelled with an integer value from 0 to (bins - 1). NaNs are labelled with -1. If ``mask`` is supplied, ignore data p...
[ "Construct", "a", "Classifier", "computing", "quantiles", "of", "the", "output", "of", "self", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/factors/factor.py#L950-L974
[ "def", "quantiles", "(", "self", ",", "bins", ",", "mask", "=", "NotSpecified", ")", ":", "if", "mask", "is", "NotSpecified", ":", "mask", "=", "self", ".", "mask", "return", "Quantiles", "(", "inputs", "=", "(", "self", ",", ")", ",", "bins", "=", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
Factor.top
Construct a Filter matching the top N asset values of self each day. If ``groupby`` is supplied, returns a Filter matching the top N asset values for each group. Parameters ---------- N : int Number of assets passing the returned filter each day. mask : zipl...
zipline/pipeline/factors/factor.py
def top(self, N, mask=NotSpecified, groupby=NotSpecified): """ Construct a Filter matching the top N asset values of self each day. If ``groupby`` is supplied, returns a Filter matching the top N asset values for each group. Parameters ---------- N : int ...
def top(self, N, mask=NotSpecified, groupby=NotSpecified): """ Construct a Filter matching the top N asset values of self each day. If ``groupby`` is supplied, returns a Filter matching the top N asset values for each group. Parameters ---------- N : int ...
[ "Construct", "a", "Filter", "matching", "the", "top", "N", "asset", "values", "of", "self", "each", "day", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/factors/factor.py#L1048-L1074
[ "def", "top", "(", "self", ",", "N", ",", "mask", "=", "NotSpecified", ",", "groupby", "=", "NotSpecified", ")", ":", "if", "N", "==", "1", ":", "# Special case: if N == 1, we can avoid doing a full sort on every", "# group, which is a big win.", "return", "self", "...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
Factor.bottom
Construct a Filter matching the bottom N asset values of self each day. If ``groupby`` is supplied, returns a Filter matching the bottom N asset values for each group. Parameters ---------- N : int Number of assets passing the returned filter each day. mask ...
zipline/pipeline/factors/factor.py
def bottom(self, N, mask=NotSpecified, groupby=NotSpecified): """ Construct a Filter matching the bottom N asset values of self each day. If ``groupby`` is supplied, returns a Filter matching the bottom N asset values for each group. Parameters ---------- N : in...
def bottom(self, N, mask=NotSpecified, groupby=NotSpecified): """ Construct a Filter matching the bottom N asset values of self each day. If ``groupby`` is supplied, returns a Filter matching the bottom N asset values for each group. Parameters ---------- N : in...
[ "Construct", "a", "Filter", "matching", "the", "bottom", "N", "asset", "values", "of", "self", "each", "day", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/factors/factor.py#L1076-L1098
[ "def", "bottom", "(", "self", ",", "N", ",", "mask", "=", "NotSpecified", ",", "groupby", "=", "NotSpecified", ")", ":", "return", "self", ".", "rank", "(", "ascending", "=", "True", ",", "mask", "=", "mask", ",", "groupby", "=", "groupby", ")", "<="...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
Factor.percentile_between
Construct a new Filter representing entries from the output of this Factor that fall within the percentile range defined by min_percentile and max_percentile. Parameters ---------- min_percentile : float [0.0, 100.0] Return True for assets falling above this percenti...
zipline/pipeline/factors/factor.py
def percentile_between(self, min_percentile, max_percentile, mask=NotSpecified): """ Construct a new Filter representing entries from the output of this Factor that fall within the percentile range defined by min_pe...
def percentile_between(self, min_percentile, max_percentile, mask=NotSpecified): """ Construct a new Filter representing entries from the output of this Factor that fall within the percentile range defined by min_pe...
[ "Construct", "a", "new", "Filter", "representing", "entries", "from", "the", "output", "of", "this", "Factor", "that", "fall", "within", "the", "percentile", "range", "defined", "by", "min_percentile", "and", "max_percentile", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/factors/factor.py#L1103-L1139
[ "def", "percentile_between", "(", "self", ",", "min_percentile", ",", "max_percentile", ",", "mask", "=", "NotSpecified", ")", ":", "return", "PercentileFilter", "(", "self", ",", "min_percentile", "=", "min_percentile", ",", "max_percentile", "=", "max_percentile",...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
Rank._validate
Verify that the stored rank method is valid.
zipline/pipeline/factors/factor.py
def _validate(self): """ Verify that the stored rank method is valid. """ if self._method not in _RANK_METHODS: raise UnknownRankMethod( method=self._method, choices=set(_RANK_METHODS), ) return super(Rank, self)._validate()
def _validate(self): """ Verify that the stored rank method is valid. """ if self._method not in _RANK_METHODS: raise UnknownRankMethod( method=self._method, choices=set(_RANK_METHODS), ) return super(Rank, self)._validate()
[ "Verify", "that", "the", "stored", "rank", "method", "is", "valid", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/factors/factor.py#L1382-L1391
[ "def", "_validate", "(", "self", ")", ":", "if", "self", ".", "_method", "not", "in", "_RANK_METHODS", ":", "raise", "UnknownRankMethod", "(", "method", "=", "self", ".", "_method", ",", "choices", "=", "set", "(", "_RANK_METHODS", ")", ",", ")", "return...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
Rank._compute
For each row in the input, compute a like-shaped array of per-row ranks.
zipline/pipeline/factors/factor.py
def _compute(self, arrays, dates, assets, mask): """ For each row in the input, compute a like-shaped array of per-row ranks. """ return masked_rankdata_2d( arrays[0], mask, self.inputs[0].missing_value, self._method, se...
def _compute(self, arrays, dates, assets, mask): """ For each row in the input, compute a like-shaped array of per-row ranks. """ return masked_rankdata_2d( arrays[0], mask, self.inputs[0].missing_value, self._method, se...
[ "For", "each", "row", "in", "the", "input", "compute", "a", "like", "-", "shaped", "array", "of", "per", "-", "row", "ranks", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/factors/factor.py#L1393-L1404
[ "def", "_compute", "(", "self", ",", "arrays", ",", "dates", ",", "assets", ",", "mask", ")", ":", "return", "masked_rankdata_2d", "(", "arrays", "[", "0", "]", ",", "mask", ",", "self", ".", "inputs", "[", "0", "]", ".", "missing_value", ",", "self"...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
_time_to_micros
Convert a time into microseconds since midnight. Parameters ---------- time : datetime.time The time to convert. Returns ------- us : int The number of microseconds since midnight. Notes ----- This does not account for leap seconds or daylight savings.
zipline/utils/pandas_utils.py
def _time_to_micros(time): """Convert a time into microseconds since midnight. Parameters ---------- time : datetime.time The time to convert. Returns ------- us : int The number of microseconds since midnight. Notes ----- This does not account for leap seconds or...
def _time_to_micros(time): """Convert a time into microseconds since midnight. Parameters ---------- time : datetime.time The time to convert. Returns ------- us : int The number of microseconds since midnight. Notes ----- This does not account for leap seconds or...
[ "Convert", "a", "time", "into", "microseconds", "since", "midnight", ".", "Parameters", "----------", "time", ":", "datetime", ".", "time", "The", "time", "to", "convert", ".", "Returns", "-------", "us", ":", "int", "The", "number", "of", "microseconds", "s...
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/pandas_utils.py#L48-L63
[ "def", "_time_to_micros", "(", "time", ")", ":", "seconds", "=", "time", ".", "hour", "*", "60", "*", "60", "+", "time", ".", "minute", "*", "60", "+", "time", ".", "second", "return", "1000000", "*", "seconds", "+", "time", ".", "microsecond" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
mask_between_time
Return a mask of all of the datetimes in ``dts`` that are between ``start`` and ``end``. Parameters ---------- dts : pd.DatetimeIndex The index to mask. start : time Mask away times less than the start. end : time Mask away times greater than the end. include_start : ...
zipline/utils/pandas_utils.py
def mask_between_time(dts, start, end, include_start=True, include_end=True): """Return a mask of all of the datetimes in ``dts`` that are between ``start`` and ``end``. Parameters ---------- dts : pd.DatetimeIndex The index to mask. start : time Mask away times less than the sta...
def mask_between_time(dts, start, end, include_start=True, include_end=True): """Return a mask of all of the datetimes in ``dts`` that are between ``start`` and ``end``. Parameters ---------- dts : pd.DatetimeIndex The index to mask. start : time Mask away times less than the sta...
[ "Return", "a", "mask", "of", "all", "of", "the", "datetimes", "in", "dts", "that", "are", "between", "start", "and", "end", ".", "Parameters", "----------", "dts", ":", "pd", ".", "DatetimeIndex", "The", "index", "to", "mask", ".", "start", ":", "time", ...
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/pandas_utils.py#L72-L111
[ "def", "mask_between_time", "(", "dts", ",", "start", ",", "end", ",", "include_start", "=", "True", ",", "include_end", "=", "True", ")", ":", "# This function is adapted from", "# `pandas.Datetime.Index.indexer_between_time` which was originally", "# written by Wes McKinney...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
find_in_sorted_index
Find the index of ``dt`` in ``dts``. This function should be used instead of `dts.get_loc(dt)` if the index is large enough that we don't want to initialize a hash table in ``dts``. In particular, this should always be used on minutely trading calendars. Parameters ---------- dts : pd.Datetime...
zipline/utils/pandas_utils.py
def find_in_sorted_index(dts, dt): """ Find the index of ``dt`` in ``dts``. This function should be used instead of `dts.get_loc(dt)` if the index is large enough that we don't want to initialize a hash table in ``dts``. In particular, this should always be used on minutely trading calendars. ...
def find_in_sorted_index(dts, dt): """ Find the index of ``dt`` in ``dts``. This function should be used instead of `dts.get_loc(dt)` if the index is large enough that we don't want to initialize a hash table in ``dts``. In particular, this should always be used on minutely trading calendars. ...
[ "Find", "the", "index", "of", "dt", "in", "dts", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/pandas_utils.py#L114-L142
[ "def", "find_in_sorted_index", "(", "dts", ",", "dt", ")", ":", "ix", "=", "dts", ".", "searchsorted", "(", "dt", ")", "if", "ix", "==", "len", "(", "dts", ")", "or", "dts", "[", "ix", "]", "!=", "dt", ":", "raise", "LookupError", "(", "\"{dt} is n...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
nearest_unequal_elements
Find values in ``dts`` closest but not equal to ``dt``. Returns a pair of (last_before, first_after). When ``dt`` is less than any element in ``dts``, ``last_before`` is None. When ``dt`` is greater any element in ``dts``, ``first_after`` is None. ``dts`` must be unique and sorted in increasing order...
zipline/utils/pandas_utils.py
def nearest_unequal_elements(dts, dt): """ Find values in ``dts`` closest but not equal to ``dt``. Returns a pair of (last_before, first_after). When ``dt`` is less than any element in ``dts``, ``last_before`` is None. When ``dt`` is greater any element in ``dts``, ``first_after`` is None. ``...
def nearest_unequal_elements(dts, dt): """ Find values in ``dts`` closest but not equal to ``dt``. Returns a pair of (last_before, first_after). When ``dt`` is less than any element in ``dts``, ``last_before`` is None. When ``dt`` is greater any element in ``dts``, ``first_after`` is None. ``...
[ "Find", "values", "in", "dts", "closest", "but", "not", "equal", "to", "dt", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/pandas_utils.py#L145-L192
[ "def", "nearest_unequal_elements", "(", "dts", ",", "dt", ")", ":", "if", "not", "dts", ".", "is_unique", ":", "raise", "ValueError", "(", "\"dts must be unique\"", ")", "if", "not", "dts", ".", "is_monotonic_increasing", ":", "raise", "ValueError", "(", "\"dt...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
categorical_df_concat
Prepare list of pandas DataFrames to be used as input to pd.concat. Ensure any columns of type 'category' have the same categories across each dataframe. Parameters ---------- df_list : list List of dataframes with same columns. inplace : bool True if input list can be modified....
zipline/utils/pandas_utils.py
def categorical_df_concat(df_list, inplace=False): """ Prepare list of pandas DataFrames to be used as input to pd.concat. Ensure any columns of type 'category' have the same categories across each dataframe. Parameters ---------- df_list : list List of dataframes with same columns....
def categorical_df_concat(df_list, inplace=False): """ Prepare list of pandas DataFrames to be used as input to pd.concat. Ensure any columns of type 'category' have the same categories across each dataframe. Parameters ---------- df_list : list List of dataframes with same columns....
[ "Prepare", "list", "of", "pandas", "DataFrames", "to", "be", "used", "as", "input", "to", "pd", ".", "concat", ".", "Ensure", "any", "columns", "of", "type", "category", "have", "the", "same", "categories", "across", "each", "dataframe", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/pandas_utils.py#L247-L287
[ "def", "categorical_df_concat", "(", "df_list", ",", "inplace", "=", "False", ")", ":", "if", "not", "inplace", ":", "df_list", "=", "deepcopy", "(", "df_list", ")", "# Assert each dataframe has the same columns/dtypes", "df", "=", "df_list", "[", "0", "]", "if"...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
check_indexes_all_same
Check that a list of Index objects are all equal. Parameters ---------- indexes : iterable[pd.Index] Iterable of indexes to check. Raises ------ ValueError If the indexes are not all the same.
zipline/utils/pandas_utils.py
def check_indexes_all_same(indexes, message="Indexes are not equal."): """Check that a list of Index objects are all equal. Parameters ---------- indexes : iterable[pd.Index] Iterable of indexes to check. Raises ------ ValueError If the indexes are not all the same. """...
def check_indexes_all_same(indexes, message="Indexes are not equal."): """Check that a list of Index objects are all equal. Parameters ---------- indexes : iterable[pd.Index] Iterable of indexes to check. Raises ------ ValueError If the indexes are not all the same. """...
[ "Check", "that", "a", "list", "of", "Index", "objects", "are", "all", "equal", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/pandas_utils.py#L325-L349
[ "def", "check_indexes_all_same", "(", "indexes", ",", "message", "=", "\"Indexes are not equal.\"", ")", ":", "iterator", "=", "iter", "(", "indexes", ")", "first", "=", "next", "(", "iterator", ")", "for", "other", "in", "iterator", ":", "same", "=", "(", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
required_event_fields
Compute the set of resource columns required to serve ``next_value_columns`` and ``previous_value_columns``.
zipline/pipeline/loaders/events.py
def required_event_fields(next_value_columns, previous_value_columns): """ Compute the set of resource columns required to serve ``next_value_columns`` and ``previous_value_columns``. """ # These metadata columns are used to align event indexers. return { TS_FIELD_NAME, SID_FIELD...
def required_event_fields(next_value_columns, previous_value_columns): """ Compute the set of resource columns required to serve ``next_value_columns`` and ``previous_value_columns``. """ # These metadata columns are used to align event indexers. return { TS_FIELD_NAME, SID_FIELD...
[ "Compute", "the", "set", "of", "resource", "columns", "required", "to", "serve", "next_value_columns", "and", "previous_value_columns", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/events.py#L21-L36
[ "def", "required_event_fields", "(", "next_value_columns", ",", "previous_value_columns", ")", ":", "# These metadata columns are used to align event indexers.", "return", "{", "TS_FIELD_NAME", ",", "SID_FIELD_NAME", ",", "EVENT_DATE_FIELD_NAME", ",", "}", ".", "union", "(", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
validate_column_specs
Verify that the columns of ``events`` can be used by an EventsLoader to serve the BoundColumns described by ``next_value_columns`` and ``previous_value_columns``.
zipline/pipeline/loaders/events.py
def validate_column_specs(events, next_value_columns, previous_value_columns): """ Verify that the columns of ``events`` can be used by an EventsLoader to serve the BoundColumns described by ``next_value_columns`` and ``previous_value_columns``. """ required = required_event_fields(next_value_co...
def validate_column_specs(events, next_value_columns, previous_value_columns): """ Verify that the columns of ``events`` can be used by an EventsLoader to serve the BoundColumns described by ``next_value_columns`` and ``previous_value_columns``. """ required = required_event_fields(next_value_co...
[ "Verify", "that", "the", "columns", "of", "events", "can", "be", "used", "by", "an", "EventsLoader", "to", "serve", "the", "BoundColumns", "described", "by", "next_value_columns", "and", "previous_value_columns", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/events.py#L39-L58
[ "def", "validate_column_specs", "(", "events", ",", "next_value_columns", ",", "previous_value_columns", ")", ":", "required", "=", "required_event_fields", "(", "next_value_columns", ",", "previous_value_columns", ")", "received", "=", "set", "(", "events", ".", "col...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
EventsLoader.split_next_and_previous_event_columns
Split requested columns into columns that should load the next known value and columns that should load the previous known value. Parameters ---------- requested_columns : iterable[BoundColumn] Returns ------- next_cols, previous_cols : iterable[BoundColumn], it...
zipline/pipeline/loaders/events.py
def split_next_and_previous_event_columns(self, requested_columns): """ Split requested columns into columns that should load the next known value and columns that should load the previous known value. Parameters ---------- requested_columns : iterable[BoundColumn] ...
def split_next_and_previous_event_columns(self, requested_columns): """ Split requested columns into columns that should load the next known value and columns that should load the previous known value. Parameters ---------- requested_columns : iterable[BoundColumn] ...
[ "Split", "requested", "columns", "into", "columns", "that", "should", "load", "the", "next", "known", "value", "and", "columns", "that", "should", "load", "the", "previous", "known", "value", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/events.py#L119-L146
[ "def", "split_next_and_previous_event_columns", "(", "self", ",", "requested_columns", ")", ":", "def", "next_or_previous", "(", "c", ")", ":", "if", "c", "in", "self", ".", "next_value_columns", ":", "return", "'next'", "elif", "c", "in", "self", ".", "previo...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
compare_arrays
Eq check with a short-circuit for identical objects.
zipline/lib/labelarray.py
def compare_arrays(left, right): "Eq check with a short-circuit for identical objects." return ( left is right or ((left.shape == right.shape) and (left == right).all()) )
def compare_arrays(left, right): "Eq check with a short-circuit for identical objects." return ( left is right or ((left.shape == right.shape) and (left == right).all()) )
[ "Eq", "check", "with", "a", "short", "-", "circuit", "for", "identical", "objects", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/lib/labelarray.py#L38-L43
[ "def", "compare_arrays", "(", "left", ",", "right", ")", ":", "return", "(", "left", "is", "right", "or", "(", "(", "left", ".", "shape", "==", "right", ".", "shape", ")", "and", "(", "left", "==", "right", ")", ".", "all", "(", ")", ")", ")" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
LabelArray.from_codes_and_metadata
Rehydrate a LabelArray from the codes and metadata. Parameters ---------- codes : np.ndarray[integral] The codes for the label array. categories : np.ndarray[object] The unique string categories. reverse_categories : dict[str, int] The mapping...
zipline/lib/labelarray.py
def from_codes_and_metadata(cls, codes, categories, reverse_categories, missing_value): """ Rehydrate a LabelArray from the codes and metadata. Parameters ----...
def from_codes_and_metadata(cls, codes, categories, reverse_categories, missing_value): """ Rehydrate a LabelArray from the codes and metadata. Parameters ----...
[ "Rehydrate", "a", "LabelArray", "from", "the", "codes", "and", "metadata", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/lib/labelarray.py#L194-L217
[ "def", "from_codes_and_metadata", "(", "cls", ",", "codes", ",", "categories", ",", "reverse_categories", ",", "missing_value", ")", ":", "ret", "=", "codes", ".", "view", "(", "type", "=", "cls", ",", "dtype", "=", "np", ".", "void", ")", "ret", ".", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
LabelArray.as_int_array
Convert self into a regular ndarray of ints. This is an O(1) operation. It does not copy the underlying data.
zipline/lib/labelarray.py
def as_int_array(self): """ Convert self into a regular ndarray of ints. This is an O(1) operation. It does not copy the underlying data. """ return self.view( type=ndarray, dtype=unsigned_int_dtype_with_size_in_bytes(self.itemsize), )
def as_int_array(self): """ Convert self into a regular ndarray of ints. This is an O(1) operation. It does not copy the underlying data. """ return self.view( type=ndarray, dtype=unsigned_int_dtype_with_size_in_bytes(self.itemsize), )
[ "Convert", "self", "into", "a", "regular", "ndarray", "of", "ints", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/lib/labelarray.py#L303-L312
[ "def", "as_int_array", "(", "self", ")", ":", "return", "self", ".", "view", "(", "type", "=", "ndarray", ",", "dtype", "=", "unsigned_int_dtype_with_size_in_bytes", "(", "self", ".", "itemsize", ")", ",", ")" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
LabelArray.as_categorical
Coerce self into a pandas categorical. This is only defined on 1D arrays, since that's all pandas supports.
zipline/lib/labelarray.py
def as_categorical(self): """ Coerce self into a pandas categorical. This is only defined on 1D arrays, since that's all pandas supports. """ if len(self.shape) > 1: raise ValueError("Can't convert a 2D array to a categorical.") with ignore_pandas_nan_catego...
def as_categorical(self): """ Coerce self into a pandas categorical. This is only defined on 1D arrays, since that's all pandas supports. """ if len(self.shape) > 1: raise ValueError("Can't convert a 2D array to a categorical.") with ignore_pandas_nan_catego...
[ "Coerce", "self", "into", "a", "pandas", "categorical", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/lib/labelarray.py#L322-L338
[ "def", "as_categorical", "(", "self", ")", ":", "if", "len", "(", "self", ".", "shape", ")", ">", "1", ":", "raise", "ValueError", "(", "\"Can't convert a 2D array to a categorical.\"", ")", "with", "ignore_pandas_nan_categorical_warning", "(", ")", ":", "return",...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
LabelArray.as_categorical_frame
Coerce self into a pandas DataFrame of Categoricals.
zipline/lib/labelarray.py
def as_categorical_frame(self, index, columns, name=None): """ Coerce self into a pandas DataFrame of Categoricals. """ if len(self.shape) != 2: raise ValueError( "Can't convert a non-2D LabelArray into a DataFrame." ) expected_shape = (le...
def as_categorical_frame(self, index, columns, name=None): """ Coerce self into a pandas DataFrame of Categoricals. """ if len(self.shape) != 2: raise ValueError( "Can't convert a non-2D LabelArray into a DataFrame." ) expected_shape = (le...
[ "Coerce", "self", "into", "a", "pandas", "DataFrame", "of", "Categoricals", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/lib/labelarray.py#L340-L364
[ "def", "as_categorical_frame", "(", "self", ",", "index", ",", "columns", ",", "name", "=", "None", ")", ":", "if", "len", "(", "self", ".", "shape", ")", "!=", "2", ":", "raise", "ValueError", "(", "\"Can't convert a non-2D LabelArray into a DataFrame.\"", ")...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
LabelArray.set_scalar
Set scalar value into the array. Parameters ---------- indexer : any The indexer to set the value at. value : str The value to assign at the given locations. Raises ------ ValueError Raised when ``value`` is not a value elemen...
zipline/lib/labelarray.py
def set_scalar(self, indexer, value): """ Set scalar value into the array. Parameters ---------- indexer : any The indexer to set the value at. value : str The value to assign at the given locations. Raises ------ ValueErr...
def set_scalar(self, indexer, value): """ Set scalar value into the array. Parameters ---------- indexer : any The indexer to set the value at. value : str The value to assign at the given locations. Raises ------ ValueErr...
[ "Set", "scalar", "value", "into", "the", "array", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/lib/labelarray.py#L400-L422
[ "def", "set_scalar", "(", "self", ",", "indexer", ",", "value", ")", ":", "try", ":", "value_code", "=", "self", ".", "reverse_categories", "[", "value", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "\"%r is not in LabelArray categories.\"", "%", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
LabelArray._equality_check
Shared code for __eq__ and __ne__, parameterized on the actual comparison operator to use.
zipline/lib/labelarray.py
def _equality_check(op): """ Shared code for __eq__ and __ne__, parameterized on the actual comparison operator to use. """ def method(self, other): if isinstance(other, LabelArray): self_mv = self.missing_value other_mv = other.missin...
def _equality_check(op): """ Shared code for __eq__ and __ne__, parameterized on the actual comparison operator to use. """ def method(self, other): if isinstance(other, LabelArray): self_mv = self.missing_value other_mv = other.missin...
[ "Shared", "code", "for", "__eq__", "and", "__ne__", "parameterized", "on", "the", "actual", "comparison", "operator", "to", "use", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/lib/labelarray.py#L462-L496
[ "def", "_equality_check", "(", "op", ")", ":", "def", "method", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "LabelArray", ")", ":", "self_mv", "=", "self", ".", "missing_value", "other_mv", "=", "other", ".", "missing_valu...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
LabelArray.empty_like
Make an empty LabelArray with the same categories as ``self``, filled with ``self.missing_value``.
zipline/lib/labelarray.py
def empty_like(self, shape): """ Make an empty LabelArray with the same categories as ``self``, filled with ``self.missing_value``. """ return type(self).from_codes_and_metadata( codes=np.full( shape, self.reverse_categories[self.missin...
def empty_like(self, shape): """ Make an empty LabelArray with the same categories as ``self``, filled with ``self.missing_value``. """ return type(self).from_codes_and_metadata( codes=np.full( shape, self.reverse_categories[self.missin...
[ "Make", "an", "empty", "LabelArray", "with", "the", "same", "categories", "as", "self", "filled", "with", "self", ".", "missing_value", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/lib/labelarray.py#L605-L619
[ "def", "empty_like", "(", "self", ",", "shape", ")", ":", "return", "type", "(", "self", ")", ".", "from_codes_and_metadata", "(", "codes", "=", "np", ".", "full", "(", "shape", ",", "self", ".", "reverse_categories", "[", "self", ".", "missing_value", "...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
LabelArray.map_predicate
Map a function from str -> bool element-wise over ``self``. ``f`` will be applied exactly once to each non-missing unique value in ``self``. Missing values will always return False.
zipline/lib/labelarray.py
def map_predicate(self, f): """ Map a function from str -> bool element-wise over ``self``. ``f`` will be applied exactly once to each non-missing unique value in ``self``. Missing values will always return False. """ # Functions passed to this are of type str -> bool. ...
def map_predicate(self, f): """ Map a function from str -> bool element-wise over ``self``. ``f`` will be applied exactly once to each non-missing unique value in ``self``. Missing values will always return False. """ # Functions passed to this are of type str -> bool. ...
[ "Map", "a", "function", "from", "str", "-", ">", "bool", "element", "-", "wise", "over", "self", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/lib/labelarray.py#L621-L645
[ "def", "map_predicate", "(", "self", ",", "f", ")", ":", "# Functions passed to this are of type str -> bool. Don't ever call", "# them on None, which is the only non-str value we ever store in", "# categories.", "if", "self", ".", "missing_value", "is", "None", ":", "def", "f...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
LabelArray.map
Map a function from str -> str element-wise over ``self``. ``f`` will be applied exactly once to each non-missing unique value in ``self``. Missing values will always map to ``self.missing_value``.
zipline/lib/labelarray.py
def map(self, f): """ Map a function from str -> str element-wise over ``self``. ``f`` will be applied exactly once to each non-missing unique value in ``self``. Missing values will always map to ``self.missing_value``. """ # f() should only return None if None is our mi...
def map(self, f): """ Map a function from str -> str element-wise over ``self``. ``f`` will be applied exactly once to each non-missing unique value in ``self``. Missing values will always map to ``self.missing_value``. """ # f() should only return None if None is our mi...
[ "Map", "a", "function", "from", "str", "-", ">", "str", "element", "-", "wise", "over", "self", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/lib/labelarray.py#L647-L722
[ "def", "map", "(", "self", ",", "f", ")", ":", "# f() should only return None if None is our missing value.", "if", "self", ".", "missing_value", "is", "None", ":", "allowed_outtypes", "=", "self", ".", "SUPPORTED_SCALAR_TYPES", "else", ":", "allowed_outtypes", "=", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
asymmetric_round_price
Asymmetric rounding function for adjusting prices to the specified number of places in a way that "improves" the price. For limit prices, this means preferring to round down on buys and preferring to round up on sells. For stop prices, it means the reverse. If prefer_round_down == True: When .0...
zipline/finance/execution.py
def asymmetric_round_price(price, prefer_round_down, tick_size, diff=0.95): """ Asymmetric rounding function for adjusting prices to the specified number of places in a way that "improves" the price. For limit prices, this means preferring to round down on buys and preferring to round up on sells. F...
def asymmetric_round_price(price, prefer_round_down, tick_size, diff=0.95): """ Asymmetric rounding function for adjusting prices to the specified number of places in a way that "improves" the price. For limit prices, this means preferring to round down on buys and preferring to round up on sells. F...
[ "Asymmetric", "rounding", "function", "for", "adjusting", "prices", "to", "the", "specified", "number", "of", "places", "in", "a", "way", "that", "improves", "the", "price", ".", "For", "limit", "prices", "this", "means", "preferring", "to", "round", "down", ...
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/execution.py#L159-L193
[ "def", "asymmetric_round_price", "(", "price", ",", "prefer_round_down", ",", "tick_size", ",", "diff", "=", "0.95", ")", ":", "precision", "=", "zp_math", ".", "number_of_decimal_places", "(", "tick_size", ")", "multiplier", "=", "int", "(", "tick_size", "*", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
check_stoplimit_prices
Check to make sure the stop/limit prices are reasonable and raise a BadOrderParameters exception if not.
zipline/finance/execution.py
def check_stoplimit_prices(price, label): """ Check to make sure the stop/limit prices are reasonable and raise a BadOrderParameters exception if not. """ try: if not isfinite(price): raise BadOrderParameters( msg="Attempted to place an order with a {} price " ...
def check_stoplimit_prices(price, label): """ Check to make sure the stop/limit prices are reasonable and raise a BadOrderParameters exception if not. """ try: if not isfinite(price): raise BadOrderParameters( msg="Attempted to place an order with a {} price " ...
[ "Check", "to", "make", "sure", "the", "stop", "/", "limit", "prices", "are", "reasonable", "and", "raise", "a", "BadOrderParameters", "exception", "if", "not", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/execution.py#L196-L217
[ "def", "check_stoplimit_prices", "(", "price", ",", "label", ")", ":", "try", ":", "if", "not", "isfinite", "(", "price", ")", ":", "raise", "BadOrderParameters", "(", "msg", "=", "\"Attempted to place an order with a {} price \"", "\"of {}.\"", ".", "format", "("...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
csvdir_bundle
Build a zipline data bundle from the directory with csv files.
zipline/data/bundles/csvdir.py
def csvdir_bundle(environ, asset_db_writer, minute_bar_writer, daily_bar_writer, adjustment_writer, calendar, start_session, end_session, cache, show_progress...
def csvdir_bundle(environ, asset_db_writer, minute_bar_writer, daily_bar_writer, adjustment_writer, calendar, start_session, end_session, cache, show_progress...
[ "Build", "a", "zipline", "data", "bundle", "from", "the", "directory", "with", "csv", "files", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/bundles/csvdir.py#L98-L168
[ "def", "csvdir_bundle", "(", "environ", ",", "asset_db_writer", ",", "minute_bar_writer", ",", "daily_bar_writer", ",", "adjustment_writer", ",", "calendar", ",", "start_session", ",", "end_session", ",", "cache", ",", "show_progress", ",", "output_dir", ",", "tfram...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
restrict_to_dtype
A factory for decorators that restrict Term methods to only be callable on Terms with a specific dtype. This is conceptually similar to zipline.utils.input_validation.expect_dtypes, but provides more flexibility for providing error messages that are specifically targeting Term methods. Parameters ...
zipline/pipeline/api_utils.py
def restrict_to_dtype(dtype, message_template): """ A factory for decorators that restrict Term methods to only be callable on Terms with a specific dtype. This is conceptually similar to zipline.utils.input_validation.expect_dtypes, but provides more flexibility for providing error messages th...
def restrict_to_dtype(dtype, message_template): """ A factory for decorators that restrict Term methods to only be callable on Terms with a specific dtype. This is conceptually similar to zipline.utils.input_validation.expect_dtypes, but provides more flexibility for providing error messages th...
[ "A", "factory", "for", "decorators", "that", "restrict", "Term", "methods", "to", "only", "be", "callable", "on", "Terms", "with", "a", "specific", "dtype", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/api_utils.py#L7-L49
[ "def", "restrict_to_dtype", "(", "dtype", ",", "message_template", ")", ":", "def", "processor", "(", "term_method", ",", "_", ",", "term_instance", ")", ":", "term_dtype", "=", "term_instance", ".", "dtype", "if", "term_dtype", "!=", "dtype", ":", "raise", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
BenchmarkSource.daily_returns
Returns the daily returns for the given period. Parameters ---------- start : datetime The inclusive starting session label. end : datetime, optional The inclusive ending session label. If not provided, treat ``start`` as a scalar key. Return...
zipline/sources/benchmark_source.py
def daily_returns(self, start, end=None): """Returns the daily returns for the given period. Parameters ---------- start : datetime The inclusive starting session label. end : datetime, optional The inclusive ending session label. If not provided, treat ...
def daily_returns(self, start, end=None): """Returns the daily returns for the given period. Parameters ---------- start : datetime The inclusive starting session label. end : datetime, optional The inclusive ending session label. If not provided, treat ...
[ "Returns", "the", "daily", "returns", "for", "the", "given", "period", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/sources/benchmark_source.py#L124-L145
[ "def", "daily_returns", "(", "self", ",", "start", ",", "end", "=", "None", ")", ":", "if", "end", "is", "None", ":", "return", "self", ".", "_daily_returns", "[", "start", "]", "return", "self", ".", "_daily_returns", "[", "start", ":", "end", "]" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
BenchmarkSource._initialize_precalculated_series
Internal method that pre-calculates the benchmark return series for use in the simulation. Parameters ---------- asset: Asset to use trading_calendar: TradingCalendar trading_days: pd.DateTimeIndex data_portal: DataPortal Notes ----- ...
zipline/sources/benchmark_source.py
def _initialize_precalculated_series(self, asset, trading_calendar, trading_days, data_portal): """ Internal method that pre-calculates the ...
def _initialize_precalculated_series(self, asset, trading_calendar, trading_days, data_portal): """ Internal method that pre-calculates the ...
[ "Internal", "method", "that", "pre", "-", "calculates", "the", "benchmark", "return", "series", "for", "use", "in", "the", "simulation", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/sources/benchmark_source.py#L196-L312
[ "def", "_initialize_precalculated_series", "(", "self", ",", "asset", ",", "trading_calendar", ",", "trading_days", ",", "data_portal", ")", ":", "if", "self", ".", "emission_rate", "==", "\"minute\"", ":", "minutes", "=", "trading_calendar", ".", "minutes_for_sessi...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
_run
Run a backtest for the given algorithm. This is shared between the cli and :func:`zipline.run_algo`.
zipline/utils/run_algo.py
def _run(handle_data, initialize, before_trading_start, analyze, algofile, algotext, defines, data_frequency, capital_base, bundle, bundle_timestamp, start, end, output, trading_calendar, ...
def _run(handle_data, initialize, before_trading_start, analyze, algofile, algotext, defines, data_frequency, capital_base, bundle, bundle_timestamp, start, end, output, trading_calendar, ...
[ "Run", "a", "backtest", "for", "the", "given", "algorithm", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/run_algo.py#L56-L213
[ "def", "_run", "(", "handle_data", ",", "initialize", ",", "before_trading_start", ",", "analyze", ",", "algofile", ",", "algotext", ",", "defines", ",", "data_frequency", ",", "capital_base", ",", "bundle", ",", "bundle_timestamp", ",", "start", ",", "end", "...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
load_extensions
Load all of the given extensions. This should be called by run_algo or the cli. Parameters ---------- default : bool Load the default exension (~/.zipline/extension.py)? extension : iterable[str] The paths to the extensions to load. If the path ends in ``.py`` it is treated ...
zipline/utils/run_algo.py
def load_extensions(default, extensions, strict, environ, reload=False): """Load all of the given extensions. This should be called by run_algo or the cli. Parameters ---------- default : bool Load the default exension (~/.zipline/extension.py)? extension : iterable[str] The pat...
def load_extensions(default, extensions, strict, environ, reload=False): """Load all of the given extensions. This should be called by run_algo or the cli. Parameters ---------- default : bool Load the default exension (~/.zipline/extension.py)? extension : iterable[str] The pat...
[ "Load", "all", "of", "the", "given", "extensions", ".", "This", "should", "be", "called", "by", "run_algo", "or", "the", "cli", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/run_algo.py#L220-L268
[ "def", "load_extensions", "(", "default", ",", "extensions", ",", "strict", ",", "environ", ",", "reload", "=", "False", ")", ":", "if", "default", ":", "default_extension_path", "=", "pth", ".", "default_extension", "(", "environ", "=", "environ", ")", "pth...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
run_algorithm
Run a trading algorithm. Parameters ---------- start : datetime The start date of the backtest. end : datetime The end date of the backtest.. initialize : callable[context -> None] The initialize function to use for the algorithm. This is called once at the very begi...
zipline/utils/run_algo.py
def run_algorithm(start, end, initialize, capital_base, handle_data=None, before_trading_start=None, analyze=None, data_frequency='daily', bundle='quantopian-quandl', ...
def run_algorithm(start, end, initialize, capital_base, handle_data=None, before_trading_start=None, analyze=None, data_frequency='daily', bundle='quantopian-quandl', ...
[ "Run", "a", "trading", "algorithm", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/run_algo.py#L271-L381
[ "def", "run_algorithm", "(", "start", ",", "end", ",", "initialize", ",", "capital_base", ",", "handle_data", "=", "None", ",", "before_trading_start", "=", "None", ",", "analyze", "=", "None", ",", "data_frequency", "=", "'daily'", ",", "bundle", "=", "'qua...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
DataPortal.handle_extra_source
Extra sources always have a sid column. We expand the given data (by forward filling) to the full range of the simulation dates, so that lookup is fast during simulation.
zipline/data/data_portal.py
def handle_extra_source(self, source_df, sim_params): """ Extra sources always have a sid column. We expand the given data (by forward filling) to the full range of the simulation dates, so that lookup is fast during simulation. """ if source_df is None: retu...
def handle_extra_source(self, source_df, sim_params): """ Extra sources always have a sid column. We expand the given data (by forward filling) to the full range of the simulation dates, so that lookup is fast during simulation. """ if source_df is None: retu...
[ "Extra", "sources", "always", "have", "a", "sid", "column", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/data_portal.py#L324-L394
[ "def", "handle_extra_source", "(", "self", ",", "source_df", ",", "sim_params", ")", ":", "if", "source_df", "is", "None", ":", "return", "# Normalize all the dates in the df", "source_df", ".", "index", "=", "source_df", ".", "index", ".", "normalize", "(", ")"...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
DataPortal.get_last_traded_dt
Given an asset and dt, returns the last traded dt from the viewpoint of the given dt. If there is a trade on the dt, the answer is dt provided.
zipline/data/data_portal.py
def get_last_traded_dt(self, asset, dt, data_frequency): """ Given an asset and dt, returns the last traded dt from the viewpoint of the given dt. If there is a trade on the dt, the answer is dt provided. """ return self._get_pricing_reader(data_frequency).get_last_trade...
def get_last_traded_dt(self, asset, dt, data_frequency): """ Given an asset and dt, returns the last traded dt from the viewpoint of the given dt. If there is a trade on the dt, the answer is dt provided. """ return self._get_pricing_reader(data_frequency).get_last_trade...
[ "Given", "an", "asset", "and", "dt", "returns", "the", "last", "traded", "dt", "from", "the", "viewpoint", "of", "the", "given", "dt", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/data_portal.py#L399-L407
[ "def", "get_last_traded_dt", "(", "self", ",", "asset", ",", "dt", ",", "data_frequency", ")", ":", "return", "self", ".", "_get_pricing_reader", "(", "data_frequency", ")", ".", "get_last_traded_dt", "(", "asset", ",", "dt", ")" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
DataPortal._is_extra_source
Internal method that determines if this asset/field combination represents a fetcher value or a regular OHLCVP lookup.
zipline/data/data_portal.py
def _is_extra_source(asset, field, map): """ Internal method that determines if this asset/field combination represents a fetcher value or a regular OHLCVP lookup. """ # If we have an extra source with a column called "price", only look # at it if it's on something like p...
def _is_extra_source(asset, field, map): """ Internal method that determines if this asset/field combination represents a fetcher value or a regular OHLCVP lookup. """ # If we have an extra source with a column called "price", only look # at it if it's on something like p...
[ "Internal", "method", "that", "determines", "if", "this", "asset", "/", "field", "combination", "represents", "a", "fetcher", "value", "or", "a", "regular", "OHLCVP", "lookup", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/data_portal.py#L410-L420
[ "def", "_is_extra_source", "(", "asset", ",", "field", ",", "map", ")", ":", "# If we have an extra source with a column called \"price\", only look", "# at it if it's on something like palladium and not AAPL (since our", "# own price data always wins when dealing with assets).", "return",...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
DataPortal.get_spot_value
Public API method that returns a scalar value representing the value of the desired asset's field at either the given dt. Parameters ---------- assets : Asset, ContinuousFuture, or iterable of same. The asset or assets whose data is desired. field : {'open', 'high', ...
zipline/data/data_portal.py
def get_spot_value(self, assets, field, dt, data_frequency): """ Public API method that returns a scalar value representing the value of the desired asset's field at either the given dt. Parameters ---------- assets : Asset, ContinuousFuture, or iterable of same. ...
def get_spot_value(self, assets, field, dt, data_frequency): """ Public API method that returns a scalar value representing the value of the desired asset's field at either the given dt. Parameters ---------- assets : Asset, ContinuousFuture, or iterable of same. ...
[ "Public", "API", "method", "that", "returns", "a", "scalar", "value", "representing", "the", "value", "of", "the", "desired", "asset", "s", "field", "at", "either", "the", "given", "dt", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/data_portal.py#L475-L537
[ "def", "get_spot_value", "(", "self", ",", "assets", ",", "field", ",", "dt", ",", "data_frequency", ")", ":", "assets_is_scalar", "=", "False", "if", "isinstance", "(", "assets", ",", "(", "AssetConvertible", ",", "PricingDataAssociable", ")", ")", ":", "as...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
DataPortal.get_scalar_asset_spot_value
Public API method that returns a scalar value representing the value of the desired asset's field at either the given dt. Parameters ---------- assets : Asset The asset or assets whose data is desired. This cannot be an arbitrary AssetConvertible. field :...
zipline/data/data_portal.py
def get_scalar_asset_spot_value(self, asset, field, dt, data_frequency): """ Public API method that returns a scalar value representing the value of the desired asset's field at either the given dt. Parameters ---------- assets : Asset The asset or assets who...
def get_scalar_asset_spot_value(self, asset, field, dt, data_frequency): """ Public API method that returns a scalar value representing the value of the desired asset's field at either the given dt. Parameters ---------- assets : Asset The asset or assets who...
[ "Public", "API", "method", "that", "returns", "a", "scalar", "value", "representing", "the", "value", "of", "the", "desired", "asset", "s", "field", "at", "either", "the", "given", "dt", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/data_portal.py#L539-L573
[ "def", "get_scalar_asset_spot_value", "(", "self", ",", "asset", ",", "field", ",", "dt", ",", "data_frequency", ")", ":", "return", "self", ".", "_get_single_asset_value", "(", "self", ".", "trading_calendar", ".", "minute_to_session_label", "(", "dt", ")", ","...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
DataPortal.get_adjustments
Returns a list of adjustments between the dt and perspective_dt for the given field and list of assets Parameters ---------- assets : list of type Asset, or Asset The asset, or assets whose adjustments are desired. field : {'open', 'high', 'low', 'close', 'volume', \...
zipline/data/data_portal.py
def get_adjustments(self, assets, field, dt, perspective_dt): """ Returns a list of adjustments between the dt and perspective_dt for the given field and list of assets Parameters ---------- assets : list of type Asset, or Asset The asset, or assets whose adj...
def get_adjustments(self, assets, field, dt, perspective_dt): """ Returns a list of adjustments between the dt and perspective_dt for the given field and list of assets Parameters ---------- assets : list of type Asset, or Asset The asset, or assets whose adj...
[ "Returns", "a", "list", "of", "adjustments", "between", "the", "dt", "and", "perspective_dt", "for", "the", "given", "field", "and", "list", "of", "assets" ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/data_portal.py#L575-L638
[ "def", "get_adjustments", "(", "self", ",", "assets", ",", "field", ",", "dt", ",", "perspective_dt", ")", ":", "if", "isinstance", "(", "assets", ",", "Asset", ")", ":", "assets", "=", "[", "assets", "]", "adjustment_ratios_per_asset", "=", "[", "]", "d...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
DataPortal.get_adjusted_value
Returns a scalar value representing the value of the desired asset's field at the given dt with adjustments applied. Parameters ---------- asset : Asset The asset whose data is desired. field : {'open', 'high', 'low', 'close', 'volume', \ 'price', 'l...
zipline/data/data_portal.py
def get_adjusted_value(self, asset, field, dt, perspective_dt, data_frequency, spot_value=None): """ Returns a scalar value representing the value of the desired asset's field at the given dt with adjustments applie...
def get_adjusted_value(self, asset, field, dt, perspective_dt, data_frequency, spot_value=None): """ Returns a scalar value representing the value of the desired asset's field at the given dt with adjustments applie...
[ "Returns", "a", "scalar", "value", "representing", "the", "value", "of", "the", "desired", "asset", "s", "field", "at", "the", "given", "dt", "with", "adjustments", "applied", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/data_portal.py#L640-L689
[ "def", "get_adjusted_value", "(", "self", ",", "asset", ",", "field", ",", "dt", ",", "perspective_dt", ",", "data_frequency", ",", "spot_value", "=", "None", ")", ":", "if", "spot_value", "is", "None", ":", "# if this a fetcher field, we want to use perspective_dt ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
DataPortal._get_history_daily_window
Internal method that returns a dataframe containing history bars of daily frequency for the given sids.
zipline/data/data_portal.py
def _get_history_daily_window(self, assets, end_dt, bar_count, field_to_use, data_frequency): """ Internal method that returns a dataf...
def _get_history_daily_window(self, assets, end_dt, bar_count, field_to_use, data_frequency): """ Internal method that returns a dataf...
[ "Internal", "method", "that", "returns", "a", "dataframe", "containing", "history", "bars", "of", "daily", "frequency", "for", "the", "given", "sids", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/data_portal.py#L787-L812
[ "def", "_get_history_daily_window", "(", "self", ",", "assets", ",", "end_dt", ",", "bar_count", ",", "field_to_use", ",", "data_frequency", ")", ":", "session", "=", "self", ".", "trading_calendar", ".", "minute_to_session_label", "(", "end_dt", ")", "days_for_wi...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
DataPortal._get_history_minute_window
Internal method that returns a dataframe containing history bars of minute frequency for the given sids.
zipline/data/data_portal.py
def _get_history_minute_window(self, assets, end_dt, bar_count, field_to_use): """ Internal method that returns a dataframe containing history bars of minute frequency for the given sids. """ # get all the minutes for this window try: ...
def _get_history_minute_window(self, assets, end_dt, bar_count, field_to_use): """ Internal method that returns a dataframe containing history bars of minute frequency for the given sids. """ # get all the minutes for this window try: ...
[ "Internal", "method", "that", "returns", "a", "dataframe", "containing", "history", "bars", "of", "minute", "frequency", "for", "the", "given", "sids", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/data_portal.py#L886-L913
[ "def", "_get_history_minute_window", "(", "self", ",", "assets", ",", "end_dt", ",", "bar_count", ",", "field_to_use", ")", ":", "# get all the minutes for this window", "try", ":", "minutes_for_window", "=", "self", ".", "trading_calendar", ".", "minutes_window", "("...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
DataPortal.get_history_window
Public API method that returns a dataframe containing the requested history window. Data is fully adjusted. Parameters ---------- assets : list of zipline.data.Asset objects The assets whose data is desired. bar_count: int The number of bars desired. ...
zipline/data/data_portal.py
def get_history_window(self, assets, end_dt, bar_count, frequency, field, data_frequency, ffill=True): """ Public A...
def get_history_window(self, assets, end_dt, bar_count, frequency, field, data_frequency, ffill=True): """ Public A...
[ "Public", "API", "method", "that", "returns", "a", "dataframe", "containing", "the", "requested", "history", "window", ".", "Data", "is", "fully", "adjusted", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/data_portal.py#L915-L1034
[ "def", "get_history_window", "(", "self", ",", "assets", ",", "end_dt", ",", "bar_count", ",", "frequency", ",", "field", ",", "data_frequency", ",", "ffill", "=", "True", ")", ":", "if", "field", "not", "in", "OHLCVP_FIELDS", "and", "field", "!=", "'sid'"...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
DataPortal._get_minute_window_data
Internal method that gets a window of adjusted minute data for an asset and specified date range. Used to support the history API method for minute bars. Missing bars are filled with NaN. Parameters ---------- assets : iterable[Asset] The assets whose data ...
zipline/data/data_portal.py
def _get_minute_window_data(self, assets, field, minutes_for_window): """ Internal method that gets a window of adjusted minute data for an asset and specified date range. Used to support the history API method for minute bars. Missing bars are filled with NaN. Paramet...
def _get_minute_window_data(self, assets, field, minutes_for_window): """ Internal method that gets a window of adjusted minute data for an asset and specified date range. Used to support the history API method for minute bars. Missing bars are filled with NaN. Paramet...
[ "Internal", "method", "that", "gets", "a", "window", "of", "adjusted", "minute", "data", "for", "an", "asset", "and", "specified", "date", "range", ".", "Used", "to", "support", "the", "history", "API", "method", "for", "minute", "bars", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/data_portal.py#L1036-L1063
[ "def", "_get_minute_window_data", "(", "self", ",", "assets", ",", "field", ",", "minutes_for_window", ")", ":", "return", "self", ".", "_minute_history_loader", ".", "history", "(", "assets", ",", "minutes_for_window", ",", "field", ",", "False", ")" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
DataPortal._get_daily_window_data
Internal method that gets a window of adjusted daily data for a sid and specified date range. Used to support the history API method for daily bars. Parameters ---------- asset : Asset The asset whose data is desired. start_dt: pandas.Timestamp ...
zipline/data/data_portal.py
def _get_daily_window_data(self, assets, field, days_in_window, extra_slot=True): """ Internal method that gets a window of adjusted daily data for a sid and specified date...
def _get_daily_window_data(self, assets, field, days_in_window, extra_slot=True): """ Internal method that gets a window of adjusted daily data for a sid and specified date...
[ "Internal", "method", "that", "gets", "a", "window", "of", "adjusted", "daily", "data", "for", "a", "sid", "and", "specified", "date", "range", ".", "Used", "to", "support", "the", "history", "API", "method", "for", "daily", "bars", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/data_portal.py#L1065-L1122
[ "def", "_get_daily_window_data", "(", "self", ",", "assets", ",", "field", ",", "days_in_window", ",", "extra_slot", "=", "True", ")", ":", "bar_count", "=", "len", "(", "days_in_window", ")", "# create an np.array of size bar_count", "dtype", "=", "float64", "if"...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
DataPortal._get_adjustment_list
Internal method that returns a list of adjustments for the given sid. Parameters ---------- asset : Asset The asset for which to return adjustments. adjustments_dict: dict A dictionary of sid -> list that is used as a cache. table_name: string ...
zipline/data/data_portal.py
def _get_adjustment_list(self, asset, adjustments_dict, table_name): """ Internal method that returns a list of adjustments for the given sid. Parameters ---------- asset : Asset The asset for which to return adjustments. adjustments_dict: dict A...
def _get_adjustment_list(self, asset, adjustments_dict, table_name): """ Internal method that returns a list of adjustments for the given sid. Parameters ---------- asset : Asset The asset for which to return adjustments. adjustments_dict: dict A...
[ "Internal", "method", "that", "returns", "a", "list", "of", "adjustments", "for", "the", "given", "sid", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/data_portal.py#L1124-L1156
[ "def", "_get_adjustment_list", "(", "self", ",", "asset", ",", "adjustments_dict", ",", "table_name", ")", ":", "if", "self", ".", "_adjustment_reader", "is", "None", ":", "return", "[", "]", "sid", "=", "int", "(", "asset", ")", "try", ":", "adjustments",...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
DataPortal.get_splits
Returns any splits for the given sids and the given dt. Parameters ---------- assets : container Assets for which we want splits. dt : pd.Timestamp The date for which we are checking for splits. Note: this is expected to be midnight UTC. Retu...
zipline/data/data_portal.py
def get_splits(self, assets, dt): """ Returns any splits for the given sids and the given dt. Parameters ---------- assets : container Assets for which we want splits. dt : pd.Timestamp The date for which we are checking for splits. Note: this is ...
def get_splits(self, assets, dt): """ Returns any splits for the given sids and the given dt. Parameters ---------- assets : container Assets for which we want splits. dt : pd.Timestamp The date for which we are checking for splits. Note: this is ...
[ "Returns", "any", "splits", "for", "the", "given", "sids", "and", "the", "given", "dt", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/data_portal.py#L1158-L1190
[ "def", "get_splits", "(", "self", ",", "assets", ",", "dt", ")", ":", "if", "self", ".", "_adjustment_reader", "is", "None", "or", "not", "assets", ":", "return", "[", "]", "# convert dt to # of seconds since epoch, because that's what we use", "# in the adjustments d...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
DataPortal.get_stock_dividends
Returns all the stock dividends for a specific sid that occur in the given trading range. Parameters ---------- sid: int The asset whose stock dividends should be returned. trading_days: pd.DatetimeIndex The trading range. Returns ------...
zipline/data/data_portal.py
def get_stock_dividends(self, sid, trading_days): """ Returns all the stock dividends for a specific sid that occur in the given trading range. Parameters ---------- sid: int The asset whose stock dividends should be returned. trading_days: pd.Dateti...
def get_stock_dividends(self, sid, trading_days): """ Returns all the stock dividends for a specific sid that occur in the given trading range. Parameters ---------- sid: int The asset whose stock dividends should be returned. trading_days: pd.Dateti...
[ "Returns", "all", "the", "stock", "dividends", "for", "a", "specific", "sid", "that", "occur", "in", "the", "given", "trading", "range", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/data_portal.py#L1192-L1237
[ "def", "get_stock_dividends", "(", "self", ",", "sid", ",", "trading_days", ")", ":", "if", "self", ".", "_adjustment_reader", "is", "None", ":", "return", "[", "]", "if", "len", "(", "trading_days", ")", "==", "0", ":", "return", "[", "]", "start_dt", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
DataPortal.get_fetcher_assets
Returns a list of assets for the current date, as defined by the fetcher data. Returns ------- list: a list of Asset objects.
zipline/data/data_portal.py
def get_fetcher_assets(self, dt): """ Returns a list of assets for the current date, as defined by the fetcher data. Returns ------- list: a list of Asset objects. """ # return a list of assets for the current date, as defined by the # fetcher sou...
def get_fetcher_assets(self, dt): """ Returns a list of assets for the current date, as defined by the fetcher data. Returns ------- list: a list of Asset objects. """ # return a list of assets for the current date, as defined by the # fetcher sou...
[ "Returns", "a", "list", "of", "assets", "for", "the", "current", "date", "as", "defined", "by", "the", "fetcher", "data", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/data_portal.py#L1244-L1268
[ "def", "get_fetcher_assets", "(", "self", ",", "dt", ")", ":", "# return a list of assets for the current date, as defined by the", "# fetcher source", "if", "self", ".", "_extra_source_df", "is", "None", ":", "return", "[", "]", "day", "=", "normalize_date", "(", "dt...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
DataPortal.get_current_future_chain
Retrieves the future chain for the contract at the given `dt` according the `continuous_future` specification. Returns ------- future_chain : list[Future] A list of active futures, where the first index is the current contract specified by the continuous future ...
zipline/data/data_portal.py
def get_current_future_chain(self, continuous_future, dt): """ Retrieves the future chain for the contract at the given `dt` according the `continuous_future` specification. Returns ------- future_chain : list[Future] A list of active futures, where the firs...
def get_current_future_chain(self, continuous_future, dt): """ Retrieves the future chain for the contract at the given `dt` according the `continuous_future` specification. Returns ------- future_chain : list[Future] A list of active futures, where the firs...
[ "Retrieves", "the", "future", "chain", "for", "the", "contract", "at", "the", "given", "dt", "according", "the", "continuous_future", "specification", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/data_portal.py#L1391-L1412
[ "def", "get_current_future_chain", "(", "self", ",", "continuous_future", ",", "dt", ")", ":", "rf", "=", "self", ".", "_roll_finders", "[", "continuous_future", ".", "roll_style", "]", "session", "=", "self", ".", "trading_calendar", ".", "minute_to_session_label...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
make_kind_check
Make a function that checks whether a scalar or array is of a given kind (e.g. float, int, datetime, timedelta).
zipline/utils/numpy_utils.py
def make_kind_check(python_types, numpy_kind): """ Make a function that checks whether a scalar or array is of a given kind (e.g. float, int, datetime, timedelta). """ def check(value): if hasattr(value, 'dtype'): return value.dtype.kind == numpy_kind return isinstance(va...
def make_kind_check(python_types, numpy_kind): """ Make a function that checks whether a scalar or array is of a given kind (e.g. float, int, datetime, timedelta). """ def check(value): if hasattr(value, 'dtype'): return value.dtype.kind == numpy_kind return isinstance(va...
[ "Make", "a", "function", "that", "checks", "whether", "a", "scalar", "or", "array", "is", "of", "a", "given", "kind", "(", "e", ".", "g", ".", "float", "int", "datetime", "timedelta", ")", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/numpy_utils.py#L124-L133
[ "def", "make_kind_check", "(", "python_types", ",", "numpy_kind", ")", ":", "def", "check", "(", "value", ")", ":", "if", "hasattr", "(", "value", ",", "'dtype'", ")", ":", "return", "value", ".", "dtype", ".", "kind", "==", "numpy_kind", "return", "isin...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
coerce_to_dtype
Make a value with the specified numpy dtype. Only datetime64[ns] and datetime64[D] are supported for datetime dtypes.
zipline/utils/numpy_utils.py
def coerce_to_dtype(dtype, value): """ Make a value with the specified numpy dtype. Only datetime64[ns] and datetime64[D] are supported for datetime dtypes. """ name = dtype.name if name.startswith('datetime64'): if name == 'datetime64[D]': return make_datetime64D(value) ...
def coerce_to_dtype(dtype, value): """ Make a value with the specified numpy dtype. Only datetime64[ns] and datetime64[D] are supported for datetime dtypes. """ name = dtype.name if name.startswith('datetime64'): if name == 'datetime64[D]': return make_datetime64D(value) ...
[ "Make", "a", "value", "with", "the", "specified", "numpy", "dtype", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/numpy_utils.py#L142-L158
[ "def", "coerce_to_dtype", "(", "dtype", ",", "value", ")", ":", "name", "=", "dtype", ".", "name", "if", "name", ".", "startswith", "(", "'datetime64'", ")", ":", "if", "name", "==", "'datetime64[D]'", ":", "return", "make_datetime64D", "(", "value", ")", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
repeat_first_axis
Restride `array` to repeat `count` times along the first axis. Parameters ---------- array : np.array The array to restride. count : int Number of times to repeat `array`. Returns ------- result : array Array of shape (count,) + array.shape, composed of `array` repe...
zipline/utils/numpy_utils.py
def repeat_first_axis(array, count): """ Restride `array` to repeat `count` times along the first axis. Parameters ---------- array : np.array The array to restride. count : int Number of times to repeat `array`. Returns ------- result : array Array of shape...
def repeat_first_axis(array, count): """ Restride `array` to repeat `count` times along the first axis. Parameters ---------- array : np.array The array to restride. count : int Number of times to repeat `array`. Returns ------- result : array Array of shape...
[ "Restride", "array", "to", "repeat", "count", "times", "along", "the", "first", "axis", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/numpy_utils.py#L173-L213
[ "def", "repeat_first_axis", "(", "array", ",", "count", ")", ":", "return", "as_strided", "(", "array", ",", "(", "count", ",", ")", "+", "array", ".", "shape", ",", "(", "0", ",", ")", "+", "array", ".", "strides", ")" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
repeat_last_axis
Restride `array` to repeat `count` times along the last axis. Parameters ---------- array : np.array The array to restride. count : int Number of times to repeat `array`. Returns ------- result : array Array of shape array.shape + (count,) composed of `array` repeat...
zipline/utils/numpy_utils.py
def repeat_last_axis(array, count): """ Restride `array` to repeat `count` times along the last axis. Parameters ---------- array : np.array The array to restride. count : int Number of times to repeat `array`. Returns ------- result : array Array of shape a...
def repeat_last_axis(array, count): """ Restride `array` to repeat `count` times along the last axis. Parameters ---------- array : np.array The array to restride. count : int Number of times to repeat `array`. Returns ------- result : array Array of shape a...
[ "Restride", "array", "to", "repeat", "count", "times", "along", "the", "last", "axis", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/numpy_utils.py#L216-L256
[ "def", "repeat_last_axis", "(", "array", ",", "count", ")", ":", "return", "as_strided", "(", "array", ",", "array", ".", "shape", "+", "(", "count", ",", ")", ",", "array", ".", "strides", "+", "(", "0", ",", ")", ")" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe