repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
quantopian/zipline
zipline/utils/run_algo.py
_run
def _run(handle_data, initialize, before_trading_start, analyze, algofile, algotext, defines, data_frequency, capital_base, bundle, bundle_timestamp, start, end, output, trading_calendar, ...
python
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", "...
Run a backtest for the given algorithm. This is shared between the cli and :func:`zipline.run_algo`.
[ "Run", "a", "backtest", "for", "the", "given", "algorithm", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/run_algo.py#L56-L213
train
quantopian/zipline
zipline/utils/run_algo.py
load_extensions
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...
python
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", ")", ":", "if", "default", ":", "default_extension_path", "=", "pth", ".", "default_extension", "(", "environ", "=", "environ", ")", "pth...
Load all of the given extensions. This should be called by run_algo or the cli. Parameters ---------- default : bool Load the default exension (~/.zipline/extension.py)? extension : iterable[str] The paths to the extensions to load. If the path ends in ``.py`` it is treated ...
[ "Load", "all", "of", "the", "given", "extensions", ".", "This", "should", "be", "called", "by", "run_algo", "or", "the", "cli", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/run_algo.py#L220-L268
train
quantopian/zipline
zipline/utils/run_algo.py
run_algorithm
def run_algorithm(start, end, initialize, capital_base, handle_data=None, before_trading_start=None, analyze=None, data_frequency='daily', bundle='quantopian-quandl', ...
python
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", "=", "'qua...
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...
[ "Run", "a", "trading", "algorithm", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/run_algo.py#L271-L381
train
quantopian/zipline
zipline/data/data_portal.py
DataPortal.handle_extra_source
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...
python
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", ")", ":", "if", "source_df", "is", "None", ":", "return", "# Normalize all the dates in the df", "source_df", ".", "index", "=", "source_df", ".", "index", ".", "normalize", "(", ")"...
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.
[ "Extra", "sources", "always", "have", "a", "sid", "column", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/data_portal.py#L324-L394
train
quantopian/zipline
zipline/data/data_portal.py
DataPortal.get_last_traded_dt
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...
python
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", ")", ":", "return", "self", ".", "_get_pricing_reader", "(", "data_frequency", ")", ".", "get_last_traded_dt", "(", "asset", ",", "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.
[ "Given", "an", "asset", "and", "dt", "returns", "the", "last", "traded", "dt", "from", "the", "viewpoint", "of", "the", "given", "dt", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/data_portal.py#L399-L407
train
quantopian/zipline
zipline/data/data_portal.py
DataPortal._is_extra_source
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...
python
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", ")", ":", "# 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",...
Internal method that determines if this asset/field combination represents a fetcher value or a regular OHLCVP lookup.
[ "Internal", "method", "that", "determines", "if", "this", "asset", "/", "field", "combination", "represents", "a", "fetcher", "value", "or", "a", "regular", "OHLCVP", "lookup", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/data_portal.py#L410-L420
train
quantopian/zipline
zipline/data/data_portal.py
DataPortal.get_spot_value
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. ...
python
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", ")", ":", "assets_is_scalar", "=", "False", "if", "isinstance", "(", "assets", ",", "(", "AssetConvertible", ",", "PricingDataAssociable", ")", ")", ":", "as...
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', ...
[ "Public", "API", "method", "that", "returns", "a", "scalar", "value", "representing", "the", "value", "of", "the", "desired", "asset", "s", "field", "at", "either", "the", "given", "dt", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/data_portal.py#L475-L537
train
quantopian/zipline
zipline/data/data_portal.py
DataPortal.get_scalar_asset_spot_value
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...
python
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", ")", ":", "return", "self", ".", "_get_single_asset_value", "(", "self", ".", "trading_calendar", ".", "minute_to_session_label", "(", "dt", ")", ","...
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 :...
[ "Public", "API", "method", "that", "returns", "a", "scalar", "value", "representing", "the", "value", "of", "the", "desired", "asset", "s", "field", "at", "either", "the", "given", "dt", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/data_portal.py#L539-L573
train
quantopian/zipline
zipline/data/data_portal.py
DataPortal.get_adjustments
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...
python
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", ")", ":", "if", "isinstance", "(", "assets", ",", "Asset", ")", ":", "assets", "=", "[", "assets", "]", "adjustment_ratios_per_asset", "=", "[", "]", "d...
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', \...
[ "Returns", "a", "list", "of", "adjustments", "between", "the", "dt", "and", "perspective_dt", "for", "the", "given", "field", "and", "list", "of", "assets" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/data_portal.py#L575-L638
train
quantopian/zipline
zipline/data/data_portal.py
DataPortal.get_adjusted_value
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...
python
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", ")", ":", "if", "spot_value", "is", "None", ":", "# if this a fetcher field, we want to use perspective_dt ...
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...
[ "Returns", "a", "scalar", "value", "representing", "the", "value", "of", "the", "desired", "asset", "s", "field", "at", "the", "given", "dt", "with", "adjustments", "applied", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/data_portal.py#L640-L689
train
quantopian/zipline
zipline/data/data_portal.py
DataPortal._get_history_daily_window
def _get_history_daily_window(self, assets, end_dt, bar_count, field_to_use, data_frequency): """ Internal method that returns a dataf...
python
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", ")", ":", "session", "=", "self", ".", "trading_calendar", ".", "minute_to_session_label", "(", "end_dt", ")", "days_for_wi...
Internal method that returns a dataframe containing history bars of daily frequency for the given sids.
[ "Internal", "method", "that", "returns", "a", "dataframe", "containing", "history", "bars", "of", "daily", "frequency", "for", "the", "given", "sids", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/data_portal.py#L787-L812
train
quantopian/zipline
zipline/data/data_portal.py
DataPortal._get_history_minute_window
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: ...
python
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", ")", ":", "# get all the minutes for this window", "try", ":", "minutes_for_window", "=", "self", ".", "trading_calendar", ".", "minutes_window", "("...
Internal method that returns a dataframe containing history bars of minute frequency for the given sids.
[ "Internal", "method", "that", "returns", "a", "dataframe", "containing", "history", "bars", "of", "minute", "frequency", "for", "the", "given", "sids", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/data_portal.py#L886-L913
train
quantopian/zipline
zipline/data/data_portal.py
DataPortal.get_history_window
def get_history_window(self, assets, end_dt, bar_count, frequency, field, data_frequency, ffill=True): """ Public A...
python
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", ")", ":", "if", "field", "not", "in", "OHLCVP_FIELDS", "and", "field", "!=", "'sid'"...
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. ...
[ "Public", "API", "method", "that", "returns", "a", "dataframe", "containing", "the", "requested", "history", "window", ".", "Data", "is", "fully", "adjusted", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/data_portal.py#L915-L1034
train
quantopian/zipline
zipline/data/data_portal.py
DataPortal._get_minute_window_data
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...
python
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", ")", ":", "return", "self", ".", "_minute_history_loader", ".", "history", "(", "assets", ",", "minutes_for_window", ",", "field", ",", "False", ")" ]
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 ...
[ "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", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/data_portal.py#L1036-L1063
train
quantopian/zipline
zipline/data/data_portal.py
DataPortal._get_daily_window_data
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...
python
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", ")", ":", "bar_count", "=", "len", "(", "days_in_window", ")", "# create an np.array of size bar_count", "dtype", "=", "float64", "if"...
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 ...
[ "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", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/data_portal.py#L1065-L1122
train
quantopian/zipline
zipline/data/data_portal.py
DataPortal._get_adjustment_list
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...
python
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", ")", ":", "if", "self", ".", "_adjustment_reader", "is", "None", ":", "return", "[", "]", "sid", "=", "int", "(", "asset", ")", "try", ":", "adjustments",...
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 ...
[ "Internal", "method", "that", "returns", "a", "list", "of", "adjustments", "for", "the", "given", "sid", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/data_portal.py#L1124-L1156
train
quantopian/zipline
zipline/data/data_portal.py
DataPortal.get_splits
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 ...
python
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", ")", ":", "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...
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...
[ "Returns", "any", "splits", "for", "the", "given", "sids", "and", "the", "given", "dt", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/data_portal.py#L1158-L1190
train
quantopian/zipline
zipline/data/data_portal.py
DataPortal.get_stock_dividends
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...
python
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", ")", ":", "if", "self", ".", "_adjustment_reader", "is", "None", ":", "return", "[", "]", "if", "len", "(", "trading_days", ")", "==", "0", ":", "return", "[", "]", "start_dt", ...
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 ------...
[ "Returns", "all", "the", "stock", "dividends", "for", "a", "specific", "sid", "that", "occur", "in", "the", "given", "trading", "range", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/data_portal.py#L1192-L1237
train
quantopian/zipline
zipline/data/data_portal.py
DataPortal.get_fetcher_assets
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...
python
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", ")", ":", "# 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...
Returns a list of assets for the current date, as defined by the fetcher data. Returns ------- list: a list of Asset objects.
[ "Returns", "a", "list", "of", "assets", "for", "the", "current", "date", "as", "defined", "by", "the", "fetcher", "data", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/data_portal.py#L1244-L1268
train
quantopian/zipline
zipline/data/data_portal.py
DataPortal.get_current_future_chain
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...
python
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", ")", ":", "rf", "=", "self", ".", "_roll_finders", "[", "continuous_future", ".", "roll_style", "]", "session", "=", "self", ".", "trading_calendar", ".", "minute_to_session_label...
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 ...
[ "Retrieves", "the", "future", "chain", "for", "the", "contract", "at", "the", "given", "dt", "according", "the", "continuous_future", "specification", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/data_portal.py#L1391-L1412
train
quantopian/zipline
zipline/utils/numpy_utils.py
make_kind_check
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...
python
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", ")", ":", "def", "check", "(", "value", ")", ":", "if", "hasattr", "(", "value", ",", "'dtype'", ")", ":", "return", "value", ".", "dtype", ".", "kind", "==", "numpy_kind", "return", "isin...
Make a function that checks whether a scalar or array is of a given kind (e.g. float, int, datetime, timedelta).
[ "Make", "a", "function", "that", "checks", "whether", "a", "scalar", "or", "array", "is", "of", "a", "given", "kind", "(", "e", ".", "g", ".", "float", "int", "datetime", "timedelta", ")", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/numpy_utils.py#L124-L133
train
quantopian/zipline
zipline/utils/numpy_utils.py
coerce_to_dtype
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) ...
python
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", ")", ":", "name", "=", "dtype", ".", "name", "if", "name", ".", "startswith", "(", "'datetime64'", ")", ":", "if", "name", "==", "'datetime64[D]'", ":", "return", "make_datetime64D", "(", "value", ")", ...
Make a value with the specified numpy dtype. Only datetime64[ns] and datetime64[D] are supported for datetime dtypes.
[ "Make", "a", "value", "with", "the", "specified", "numpy", "dtype", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/numpy_utils.py#L142-L158
train
quantopian/zipline
zipline/utils/numpy_utils.py
repeat_first_axis
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...
python
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", ")", ":", "return", "as_strided", "(", "array", ",", "(", "count", ",", ")", "+", "array", ".", "shape", ",", "(", "0", ",", ")", "+", "array", ".", "strides", ")" ]
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...
[ "Restride", "array", "to", "repeat", "count", "times", "along", "the", "first", "axis", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/numpy_utils.py#L173-L213
train
quantopian/zipline
zipline/utils/numpy_utils.py
repeat_last_axis
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...
python
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", ")", ":", "return", "as_strided", "(", "array", ",", "array", ".", "shape", "+", "(", "count", ",", ")", ",", "array", ".", "strides", "+", "(", "0", ",", ")", ")" ]
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...
[ "Restride", "array", "to", "repeat", "count", "times", "along", "the", "last", "axis", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/numpy_utils.py#L216-L256
train
quantopian/zipline
zipline/utils/numpy_utils.py
rolling_window
def rolling_window(array, length): """ Restride an array of shape (X_0, ... X_N) into an array of shape (length, X_0 - length + 1, ... X_N) where each slice at index i along the first axis is equivalent to result[i] = array[length * i:length * (i + 1)] Parameters --...
python
def rolling_window(array, length): """ Restride an array of shape (X_0, ... X_N) into an array of shape (length, X_0 - length + 1, ... X_N) where each slice at index i along the first axis is equivalent to result[i] = array[length * i:length * (i + 1)] Parameters --...
[ "def", "rolling_window", "(", "array", ",", "length", ")", ":", "orig_shape", "=", "array", ".", "shape", "if", "not", "orig_shape", ":", "raise", "IndexError", "(", "\"Can't restride a scalar.\"", ")", "elif", "orig_shape", "[", "0", "]", "<=", "length", ":...
Restride an array of shape (X_0, ... X_N) into an array of shape (length, X_0 - length + 1, ... X_N) where each slice at index i along the first axis is equivalent to result[i] = array[length * i:length * (i + 1)] Parameters ---------- array : np.ndarray The bas...
[ "Restride", "an", "array", "of", "shape" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/numpy_utils.py#L259-L325
train
quantopian/zipline
zipline/utils/numpy_utils.py
isnat
def isnat(obj): """ Check if a value is np.NaT. """ if obj.dtype.kind not in ('m', 'M'): raise ValueError("%s is not a numpy datetime or timedelta") return obj.view(int64_dtype) == iNaT
python
def isnat(obj): """ Check if a value is np.NaT. """ if obj.dtype.kind not in ('m', 'M'): raise ValueError("%s is not a numpy datetime or timedelta") return obj.view(int64_dtype) == iNaT
[ "def", "isnat", "(", "obj", ")", ":", "if", "obj", ".", "dtype", ".", "kind", "not", "in", "(", "'m'", ",", "'M'", ")", ":", "raise", "ValueError", "(", "\"%s is not a numpy datetime or timedelta\"", ")", "return", "obj", ".", "view", "(", "int64_dtype", ...
Check if a value is np.NaT.
[ "Check", "if", "a", "value", "is", "np", ".", "NaT", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/numpy_utils.py#L334-L340
train
quantopian/zipline
zipline/utils/numpy_utils.py
is_missing
def is_missing(data, missing_value): """ Generic is_missing function that handles NaN and NaT. """ if is_float(data) and isnan(missing_value): return isnan(data) elif is_datetime(data) and isnat(missing_value): return isnat(data) return (data == missing_value)
python
def is_missing(data, missing_value): """ Generic is_missing function that handles NaN and NaT. """ if is_float(data) and isnan(missing_value): return isnan(data) elif is_datetime(data) and isnat(missing_value): return isnat(data) return (data == missing_value)
[ "def", "is_missing", "(", "data", ",", "missing_value", ")", ":", "if", "is_float", "(", "data", ")", "and", "isnan", "(", "missing_value", ")", ":", "return", "isnan", "(", "data", ")", "elif", "is_datetime", "(", "data", ")", "and", "isnat", "(", "mi...
Generic is_missing function that handles NaN and NaT.
[ "Generic", "is_missing", "function", "that", "handles", "NaN", "and", "NaT", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/numpy_utils.py#L343-L351
train
quantopian/zipline
zipline/utils/numpy_utils.py
busday_count_mask_NaT
def busday_count_mask_NaT(begindates, enddates, out=None): """ Simple of numpy.busday_count that returns `float` arrays rather than int arrays, and handles `NaT`s by returning `NaN`s where the inputs were `NaT`. Doesn't support custom weekdays or calendars, but probably should in the future. S...
python
def busday_count_mask_NaT(begindates, enddates, out=None): """ Simple of numpy.busday_count that returns `float` arrays rather than int arrays, and handles `NaT`s by returning `NaN`s where the inputs were `NaT`. Doesn't support custom weekdays or calendars, but probably should in the future. S...
[ "def", "busday_count_mask_NaT", "(", "begindates", ",", "enddates", ",", "out", "=", "None", ")", ":", "if", "out", "is", "None", ":", "out", "=", "empty", "(", "broadcast", "(", "begindates", ",", "enddates", ")", ".", "shape", ",", "dtype", "=", "flo...
Simple of numpy.busday_count that returns `float` arrays rather than int arrays, and handles `NaT`s by returning `NaN`s where the inputs were `NaT`. Doesn't support custom weekdays or calendars, but probably should in the future. See Also -------- np.busday_count
[ "Simple", "of", "numpy", ".", "busday_count", "that", "returns", "float", "arrays", "rather", "than", "int", "arrays", "and", "handles", "NaT", "s", "by", "returning", "NaN", "s", "where", "the", "inputs", "were", "NaT", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/numpy_utils.py#L354-L381
train
quantopian/zipline
zipline/utils/numpy_utils.py
changed_locations
def changed_locations(a, include_first): """ Compute indices of values in ``a`` that differ from the previous value. Parameters ---------- a : np.ndarray The array on which to indices of change. include_first : bool Whether or not to consider the first index of the array as "cha...
python
def changed_locations(a, include_first): """ Compute indices of values in ``a`` that differ from the previous value. Parameters ---------- a : np.ndarray The array on which to indices of change. include_first : bool Whether or not to consider the first index of the array as "cha...
[ "def", "changed_locations", "(", "a", ",", "include_first", ")", ":", "if", "a", ".", "ndim", ">", "1", ":", "raise", "ValueError", "(", "\"indices_of_changed_values only supports 1D arrays.\"", ")", "indices", "=", "flatnonzero", "(", "diff", "(", "a", ")", "...
Compute indices of values in ``a`` that differ from the previous value. Parameters ---------- a : np.ndarray The array on which to indices of change. include_first : bool Whether or not to consider the first index of the array as "changed". Example ------- >>> import numpy ...
[ "Compute", "indices", "of", "values", "in", "a", "that", "differ", "from", "the", "previous", "value", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/numpy_utils.py#L469-L496
train
quantopian/zipline
zipline/utils/date_utils.py
compute_date_range_chunks
def compute_date_range_chunks(sessions, start_date, end_date, chunksize): """Compute the start and end dates to run a pipeline for. Parameters ---------- sessions : DatetimeIndex The available dates. start_date : pd.Timestamp The first date in the pipeline. end_date : pd.Timesta...
python
def compute_date_range_chunks(sessions, start_date, end_date, chunksize): """Compute the start and end dates to run a pipeline for. Parameters ---------- sessions : DatetimeIndex The available dates. start_date : pd.Timestamp The first date in the pipeline. end_date : pd.Timesta...
[ "def", "compute_date_range_chunks", "(", "sessions", ",", "start_date", ",", "end_date", ",", "chunksize", ")", ":", "if", "start_date", "not", "in", "sessions", ":", "raise", "KeyError", "(", "\"Start date %s is not found in calendar.\"", "%", "(", "start_date", "....
Compute the start and end dates to run a pipeline for. Parameters ---------- sessions : DatetimeIndex The available dates. start_date : pd.Timestamp The first date in the pipeline. end_date : pd.Timestamp The last date in the pipeline. chunksize : int or None The...
[ "Compute", "the", "start", "and", "end", "dates", "to", "run", "a", "pipeline", "for", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/date_utils.py#L4-L42
train
quantopian/zipline
zipline/pipeline/engine.py
SimplePipelineEngine.run_pipeline
def run_pipeline(self, pipeline, start_date, end_date): """ Compute a pipeline. Parameters ---------- pipeline : zipline.pipeline.Pipeline The pipeline to run. start_date : pd.Timestamp Start date of the computed matrix. end_date : pd.Time...
python
def run_pipeline(self, pipeline, start_date, end_date): """ Compute a pipeline. Parameters ---------- pipeline : zipline.pipeline.Pipeline The pipeline to run. start_date : pd.Timestamp Start date of the computed matrix. end_date : pd.Time...
[ "def", "run_pipeline", "(", "self", ",", "pipeline", ",", "start_date", ",", "end_date", ")", ":", "# See notes at the top of this module for a description of the", "# algorithm implemented here.", "if", "end_date", "<", "start_date", ":", "raise", "ValueError", "(", "\"s...
Compute a pipeline. Parameters ---------- pipeline : zipline.pipeline.Pipeline The pipeline to run. start_date : pd.Timestamp Start date of the computed matrix. end_date : pd.Timestamp End date of the computed matrix. Returns ...
[ "Compute", "a", "pipeline", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/engine.py#L265-L336
train
quantopian/zipline
zipline/pipeline/engine.py
SimplePipelineEngine._compute_root_mask
def _compute_root_mask(self, domain, start_date, end_date, extra_rows): """ Compute a lifetimes matrix from our AssetFinder, then drop columns that didn't exist at all during the query dates. Parameters ---------- domain : zipline.pipeline.domain.Domain Domai...
python
def _compute_root_mask(self, domain, start_date, end_date, extra_rows): """ Compute a lifetimes matrix from our AssetFinder, then drop columns that didn't exist at all during the query dates. Parameters ---------- domain : zipline.pipeline.domain.Domain Domai...
[ "def", "_compute_root_mask", "(", "self", ",", "domain", ",", "start_date", ",", "end_date", ",", "extra_rows", ")", ":", "sessions", "=", "domain", ".", "all_sessions", "(", ")", "if", "start_date", "not", "in", "sessions", ":", "raise", "ValueError", "(", ...
Compute a lifetimes matrix from our AssetFinder, then drop columns that didn't exist at all during the query dates. Parameters ---------- domain : zipline.pipeline.domain.Domain Domain for which we're computing a pipeline. start_date : pd.Timestamp Base s...
[ "Compute", "a", "lifetimes", "matrix", "from", "our", "AssetFinder", "then", "drop", "columns", "that", "didn", "t", "exist", "at", "all", "during", "the", "query", "dates", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/engine.py#L356-L439
train
quantopian/zipline
zipline/pipeline/engine.py
SimplePipelineEngine.compute_chunk
def compute_chunk(self, graph, dates, sids, initial_workspace): """ Compute the Pipeline terms in the graph for the requested start and end dates. This is where we do the actual work of running a pipeline. Parameters ---------- graph : zipline.pipeline.graph.Exe...
python
def compute_chunk(self, graph, dates, sids, initial_workspace): """ Compute the Pipeline terms in the graph for the requested start and end dates. This is where we do the actual work of running a pipeline. Parameters ---------- graph : zipline.pipeline.graph.Exe...
[ "def", "compute_chunk", "(", "self", ",", "graph", ",", "dates", ",", "sids", ",", "initial_workspace", ")", ":", "self", ".", "_validate_compute_chunk_params", "(", "graph", ",", "dates", ",", "sids", ",", "initial_workspace", ",", ")", "get_loader", "=", "...
Compute the Pipeline terms in the graph for the requested start and end dates. This is where we do the actual work of running a pipeline. Parameters ---------- graph : zipline.pipeline.graph.ExecutionPlan Dependency graph of the terms to be executed. dates :...
[ "Compute", "the", "Pipeline", "terms", "in", "the", "graph", "for", "the", "requested", "start", "and", "end", "dates", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/engine.py#L484-L606
train
quantopian/zipline
zipline/pipeline/engine.py
SimplePipelineEngine._to_narrow
def _to_narrow(self, terms, data, mask, dates, assets): """ Convert raw computed pipeline results into a DataFrame for public APIs. Parameters ---------- terms : dict[str -> Term] Dict mapping column names to terms. data : dict[str -> ndarray[ndim=2]] ...
python
def _to_narrow(self, terms, data, mask, dates, assets): """ Convert raw computed pipeline results into a DataFrame for public APIs. Parameters ---------- terms : dict[str -> Term] Dict mapping column names to terms. data : dict[str -> ndarray[ndim=2]] ...
[ "def", "_to_narrow", "(", "self", ",", "terms", ",", "data", ",", "mask", ",", "dates", ",", "assets", ")", ":", "if", "not", "mask", ".", "any", "(", ")", ":", "# Manually handle the empty DataFrame case. This is a workaround", "# to pandas failing to tz_localize a...
Convert raw computed pipeline results into a DataFrame for public APIs. Parameters ---------- terms : dict[str -> Term] Dict mapping column names to terms. data : dict[str -> ndarray[ndim=2]] Dict mapping column names to computed results for those names. ...
[ "Convert", "raw", "computed", "pipeline", "results", "into", "a", "DataFrame", "for", "public", "APIs", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/engine.py#L608-L672
train
quantopian/zipline
zipline/pipeline/engine.py
SimplePipelineEngine._validate_compute_chunk_params
def _validate_compute_chunk_params(self, graph, dates, sids, initial_workspace): """ Verify that the values passed to compute_chunk are well-formed....
python
def _validate_compute_chunk_params(self, graph, dates, sids, initial_workspace): """ Verify that the values passed to compute_chunk are well-formed....
[ "def", "_validate_compute_chunk_params", "(", "self", ",", "graph", ",", "dates", ",", "sids", ",", "initial_workspace", ")", ":", "root", "=", "self", ".", "_root_mask_term", "clsname", "=", "type", "(", "self", ")", ".", "__name__", "# Writing this out explici...
Verify that the values passed to compute_chunk are well-formed.
[ "Verify", "that", "the", "values", "passed", "to", "compute_chunk", "are", "well", "-", "formed", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/engine.py#L674-L752
train
quantopian/zipline
zipline/pipeline/engine.py
SimplePipelineEngine.resolve_domain
def resolve_domain(self, pipeline): """Resolve a concrete domain for ``pipeline``. """ domain = pipeline.domain(default=self._default_domain) if domain is GENERIC: raise ValueError( "Unable to determine domain for Pipeline.\n" "Pass domain=<des...
python
def resolve_domain(self, pipeline): """Resolve a concrete domain for ``pipeline``. """ domain = pipeline.domain(default=self._default_domain) if domain is GENERIC: raise ValueError( "Unable to determine domain for Pipeline.\n" "Pass domain=<des...
[ "def", "resolve_domain", "(", "self", ",", "pipeline", ")", ":", "domain", "=", "pipeline", ".", "domain", "(", "default", "=", "self", ".", "_default_domain", ")", "if", "domain", "is", "GENERIC", ":", "raise", "ValueError", "(", "\"Unable to determine domain...
Resolve a concrete domain for ``pipeline``.
[ "Resolve", "a", "concrete", "domain", "for", "pipeline", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/engine.py#L754-L764
train
quantopian/zipline
zipline/utils/api_support.py
require_initialized
def require_initialized(exception): """ Decorator for API methods that should only be called after TradingAlgorithm.initialize. `exception` will be raised if the method is called before initialize has completed. Examples -------- @require_initialized(SomeException("Don't do that!")) de...
python
def require_initialized(exception): """ Decorator for API methods that should only be called after TradingAlgorithm.initialize. `exception` will be raised if the method is called before initialize has completed. Examples -------- @require_initialized(SomeException("Don't do that!")) de...
[ "def", "require_initialized", "(", "exception", ")", ":", "def", "decorator", "(", "method", ")", ":", "@", "wraps", "(", "method", ")", "def", "wrapped_method", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", "...
Decorator for API methods that should only be called after TradingAlgorithm.initialize. `exception` will be raised if the method is called before initialize has completed. Examples -------- @require_initialized(SomeException("Don't do that!")) def method(self): # Do stuff that should o...
[ "Decorator", "for", "API", "methods", "that", "should", "only", "be", "called", "after", "TradingAlgorithm", ".", "initialize", ".", "exception", "will", "be", "raised", "if", "the", "method", "is", "called", "before", "initialize", "has", "completed", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/api_support.py#L86-L105
train
quantopian/zipline
zipline/utils/api_support.py
disallowed_in_before_trading_start
def disallowed_in_before_trading_start(exception): """ Decorator for API methods that cannot be called from within TradingAlgorithm.before_trading_start. `exception` will be raised if the method is called inside `before_trading_start`. Examples -------- @disallowed_in_before_trading_start(...
python
def disallowed_in_before_trading_start(exception): """ Decorator for API methods that cannot be called from within TradingAlgorithm.before_trading_start. `exception` will be raised if the method is called inside `before_trading_start`. Examples -------- @disallowed_in_before_trading_start(...
[ "def", "disallowed_in_before_trading_start", "(", "exception", ")", ":", "def", "decorator", "(", "method", ")", ":", "@", "wraps", "(", "method", ")", "def", "wrapped_method", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self...
Decorator for API methods that cannot be called from within TradingAlgorithm.before_trading_start. `exception` will be raised if the method is called inside `before_trading_start`. Examples -------- @disallowed_in_before_trading_start(SomeException("Don't do that!")) def method(self): ...
[ "Decorator", "for", "API", "methods", "that", "cannot", "be", "called", "from", "within", "TradingAlgorithm", ".", "before_trading_start", ".", "exception", "will", "be", "raised", "if", "the", "method", "is", "called", "inside", "before_trading_start", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/api_support.py#L108-L127
train
quantopian/zipline
zipline/lib/normalize.py
naive_grouped_rowwise_apply
def naive_grouped_rowwise_apply(data, group_labels, func, func_args=(), out=None): """ Simple implementation of grouped row-wise function application. Parameters ---------- ...
python
def naive_grouped_rowwise_apply(data, group_labels, func, func_args=(), out=None): """ Simple implementation of grouped row-wise function application. Parameters ---------- ...
[ "def", "naive_grouped_rowwise_apply", "(", "data", ",", "group_labels", ",", "func", ",", "func_args", "=", "(", ")", ",", "out", "=", "None", ")", ":", "if", "out", "is", "None", ":", "out", "=", "np", ".", "empty_like", "(", "data", ")", "for", "("...
Simple implementation of grouped row-wise function application. Parameters ---------- data : ndarray[ndim=2] Input array over which to apply a grouped function. group_labels : ndarray[ndim=2, dtype=int64] Labels to use to bucket inputs from array. Should be the same shape as arr...
[ "Simple", "implementation", "of", "grouped", "row", "-", "wise", "function", "application", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/lib/normalize.py#L4-L51
train
quantopian/zipline
zipline/utils/formatting.py
bulleted_list
def bulleted_list(items, indent=0, bullet_type='-'): """Format a bulleted list of values. Parameters ---------- items : sequence The items to make a list. indent : int, optional The number of spaces to add before each bullet. bullet_type : str, optional The bullet type t...
python
def bulleted_list(items, indent=0, bullet_type='-'): """Format a bulleted list of values. Parameters ---------- items : sequence The items to make a list. indent : int, optional The number of spaces to add before each bullet. bullet_type : str, optional The bullet type t...
[ "def", "bulleted_list", "(", "items", ",", "indent", "=", "0", ",", "bullet_type", "=", "'-'", ")", ":", "format_string", "=", "' '", "*", "indent", "+", "bullet_type", "+", "' {}'", "return", "\"\\n\"", ".", "join", "(", "map", "(", "format_string", "."...
Format a bulleted list of values. Parameters ---------- items : sequence The items to make a list. indent : int, optional The number of spaces to add before each bullet. bullet_type : str, optional The bullet type to use. Returns ------- formatted_list : str ...
[ "Format", "a", "bulleted", "list", "of", "values", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/formatting.py#L48-L66
train
quantopian/zipline
zipline/assets/synthetic.py
make_rotating_equity_info
def make_rotating_equity_info(num_assets, first_start, frequency, periods_between_starts, asset_lifetime, exchange='TEST'): """ Create a DataFrame representing li...
python
def make_rotating_equity_info(num_assets, first_start, frequency, periods_between_starts, asset_lifetime, exchange='TEST'): """ Create a DataFrame representing li...
[ "def", "make_rotating_equity_info", "(", "num_assets", ",", "first_start", ",", "frequency", ",", "periods_between_starts", ",", "asset_lifetime", ",", "exchange", "=", "'TEST'", ")", ":", "return", "pd", ".", "DataFrame", "(", "{", "'symbol'", ":", "[", "chr", ...
Create a DataFrame representing lifetimes of assets that are constantly rotating in and out of existence. Parameters ---------- num_assets : int How many assets to create. first_start : pd.Timestamp The start date for the first asset. frequency : str or pd.tseries.offsets.Offset...
[ "Create", "a", "DataFrame", "representing", "lifetimes", "of", "assets", "that", "are", "constantly", "rotating", "in", "and", "out", "of", "existence", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/synthetic.py#L11-L59
train
quantopian/zipline
zipline/assets/synthetic.py
make_simple_equity_info
def make_simple_equity_info(sids, start_date, end_date, symbols=None, names=None, exchange='TEST'): """ Create a DataFrame representing assets that exist for the full durat...
python
def make_simple_equity_info(sids, start_date, end_date, symbols=None, names=None, exchange='TEST'): """ Create a DataFrame representing assets that exist for the full durat...
[ "def", "make_simple_equity_info", "(", "sids", ",", "start_date", ",", "end_date", ",", "symbols", "=", "None", ",", "names", "=", "None", ",", "exchange", "=", "'TEST'", ")", ":", "num_assets", "=", "len", "(", "sids", ")", "if", "symbols", "is", "None"...
Create a DataFrame representing assets that exist for the full duration between `start_date` and `end_date`. Parameters ---------- sids : array-like of int start_date : pd.Timestamp, optional end_date : pd.Timestamp, optional symbols : list, optional Symbols to use for the assets. ...
[ "Create", "a", "DataFrame", "representing", "assets", "that", "exist", "for", "the", "full", "duration", "between", "start_date", "and", "end_date", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/synthetic.py#L62-L117
train
quantopian/zipline
zipline/assets/synthetic.py
make_simple_multi_country_equity_info
def make_simple_multi_country_equity_info(countries_to_sids, countries_to_exchanges, start_date, end_date): """Create a DataFrame representing assets that exist for the full duration bet...
python
def make_simple_multi_country_equity_info(countries_to_sids, countries_to_exchanges, start_date, end_date): """Create a DataFrame representing assets that exist for the full duration bet...
[ "def", "make_simple_multi_country_equity_info", "(", "countries_to_sids", ",", "countries_to_exchanges", ",", "start_date", ",", "end_date", ")", ":", "sids", "=", "[", "]", "symbols", "=", "[", "]", "exchanges", "=", "[", "]", "for", "country", ",", "country_si...
Create a DataFrame representing assets that exist for the full duration between `start_date` and `end_date`, from multiple countries.
[ "Create", "a", "DataFrame", "representing", "assets", "that", "exist", "for", "the", "full", "duration", "between", "start_date", "and", "end_date", "from", "multiple", "countries", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/synthetic.py#L120-L154
train
quantopian/zipline
zipline/assets/synthetic.py
make_jagged_equity_info
def make_jagged_equity_info(num_assets, start_date, first_end, frequency, periods_between_ends, auto_close_delta): """ Create a DataFrame representing assets that all begin...
python
def make_jagged_equity_info(num_assets, start_date, first_end, frequency, periods_between_ends, auto_close_delta): """ Create a DataFrame representing assets that all begin...
[ "def", "make_jagged_equity_info", "(", "num_assets", ",", "start_date", ",", "first_end", ",", "frequency", ",", "periods_between_ends", ",", "auto_close_delta", ")", ":", "frame", "=", "pd", ".", "DataFrame", "(", "{", "'symbol'", ":", "[", "chr", "(", "ord",...
Create a DataFrame representing assets that all begin at the same start date, but have cascading end dates. Parameters ---------- num_assets : int How many assets to create. start_date : pd.Timestamp The start date for all the assets. first_end : pd.Timestamp The date at...
[ "Create", "a", "DataFrame", "representing", "assets", "that", "all", "begin", "at", "the", "same", "start", "date", "but", "have", "cascading", "end", "dates", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/synthetic.py#L157-L204
train
quantopian/zipline
zipline/assets/synthetic.py
make_future_info
def make_future_info(first_sid, root_symbols, years, notice_date_func, expiration_date_func, start_date_func, month_codes=None, multiplier=500): """ Create a DataFra...
python
def make_future_info(first_sid, root_symbols, years, notice_date_func, expiration_date_func, start_date_func, month_codes=None, multiplier=500): """ Create a DataFra...
[ "def", "make_future_info", "(", "first_sid", ",", "root_symbols", ",", "years", ",", "notice_date_func", ",", "expiration_date_func", ",", "start_date_func", ",", "month_codes", "=", "None", ",", "multiplier", "=", "500", ")", ":", "if", "month_codes", "is", "No...
Create a DataFrame representing futures for `root_symbols` during `year`. Generates a contract per triple of (symbol, year, month) supplied to `root_symbols`, `years`, and `month_codes`. Parameters ---------- first_sid : int The first sid to use for assigning sids to the created contracts....
[ "Create", "a", "DataFrame", "representing", "futures", "for", "root_symbols", "during", "year", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/synthetic.py#L207-L281
train
quantopian/zipline
zipline/assets/synthetic.py
make_commodity_future_info
def make_commodity_future_info(first_sid, root_symbols, years, month_codes=None, multiplier=500): """ Make futures testing data that simulates the notice/expiration date behavior of ph...
python
def make_commodity_future_info(first_sid, root_symbols, years, month_codes=None, multiplier=500): """ Make futures testing data that simulates the notice/expiration date behavior of ph...
[ "def", "make_commodity_future_info", "(", "first_sid", ",", "root_symbols", ",", "years", ",", "month_codes", "=", "None", ",", "multiplier", "=", "500", ")", ":", "nineteen_days", "=", "pd", ".", "Timedelta", "(", "days", "=", "19", ")", "one_year", "=", ...
Make futures testing data that simulates the notice/expiration date behavior of physical commodities like oil. Parameters ---------- first_sid : int The first sid to use for assigning sids to the created contracts. root_symbols : list[str] A list of root symbols for which to create ...
[ "Make", "futures", "testing", "data", "that", "simulates", "the", "notice", "/", "expiration", "date", "behavior", "of", "physical", "commodities", "like", "oil", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/synthetic.py#L284-L327
train
quantopian/zipline
zipline/pipeline/classifiers/classifier.py
Classifier.eq
def eq(self, other): """ Construct a Filter returning True for asset/date pairs where the output of ``self`` matches ``other``. """ # We treat this as an error because missing_values have NaN semantics, # which means this would return an array of all False, which is almos...
python
def eq(self, other): """ Construct a Filter returning True for asset/date pairs where the output of ``self`` matches ``other``. """ # We treat this as an error because missing_values have NaN semantics, # which means this would return an array of all False, which is almos...
[ "def", "eq", "(", "self", ",", "other", ")", ":", "# We treat this as an error because missing_values have NaN semantics,", "# which means this would return an array of all False, which is almost", "# certainly not what the user wants.", "if", "other", "==", "self", ".", "missing_val...
Construct a Filter returning True for asset/date pairs where the output of ``self`` matches ``other``.
[ "Construct", "a", "Filter", "returning", "True", "for", "asset", "/", "date", "pairs", "where", "the", "output", "of", "self", "matches", "other", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/classifiers/classifier.py#L83-L116
train
quantopian/zipline
zipline/pipeline/classifiers/classifier.py
Classifier.startswith
def startswith(self, prefix): """ Construct a Filter matching values starting with ``prefix``. Parameters ---------- prefix : str String prefix against which to compare values produced by ``self``. Returns ------- matches : Filter ...
python
def startswith(self, prefix): """ Construct a Filter matching values starting with ``prefix``. Parameters ---------- prefix : str String prefix against which to compare values produced by ``self``. Returns ------- matches : Filter ...
[ "def", "startswith", "(", "self", ",", "prefix", ")", ":", "return", "ArrayPredicate", "(", "term", "=", "self", ",", "op", "=", "LabelArray", ".", "startswith", ",", "opargs", "=", "(", "prefix", ",", ")", ",", ")" ]
Construct a Filter matching values starting with ``prefix``. Parameters ---------- prefix : str String prefix against which to compare values produced by ``self``. Returns ------- matches : Filter Filter returning True for all sid/date pairs for ...
[ "Construct", "a", "Filter", "matching", "values", "starting", "with", "prefix", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/classifiers/classifier.py#L150-L169
train
quantopian/zipline
zipline/pipeline/classifiers/classifier.py
Classifier.endswith
def endswith(self, suffix): """ Construct a Filter matching values ending with ``suffix``. Parameters ---------- suffix : str String suffix against which to compare values produced by ``self``. Returns ------- matches : Filter Fil...
python
def endswith(self, suffix): """ Construct a Filter matching values ending with ``suffix``. Parameters ---------- suffix : str String suffix against which to compare values produced by ``self``. Returns ------- matches : Filter Fil...
[ "def", "endswith", "(", "self", ",", "suffix", ")", ":", "return", "ArrayPredicate", "(", "term", "=", "self", ",", "op", "=", "LabelArray", ".", "endswith", ",", "opargs", "=", "(", "suffix", ",", ")", ",", ")" ]
Construct a Filter matching values ending with ``suffix``. Parameters ---------- suffix : str String suffix against which to compare values produced by ``self``. Returns ------- matches : Filter Filter returning True for all sid/date pairs for wh...
[ "Construct", "a", "Filter", "matching", "values", "ending", "with", "suffix", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/classifiers/classifier.py#L173-L192
train
quantopian/zipline
zipline/pipeline/classifiers/classifier.py
Classifier.has_substring
def has_substring(self, substring): """ Construct a Filter matching values containing ``substring``. Parameters ---------- substring : str Sub-string against which to compare values produced by ``self``. Returns ------- matches : Filter ...
python
def has_substring(self, substring): """ Construct a Filter matching values containing ``substring``. Parameters ---------- substring : str Sub-string against which to compare values produced by ``self``. Returns ------- matches : Filter ...
[ "def", "has_substring", "(", "self", ",", "substring", ")", ":", "return", "ArrayPredicate", "(", "term", "=", "self", ",", "op", "=", "LabelArray", ".", "has_substring", ",", "opargs", "=", "(", "substring", ",", ")", ",", ")" ]
Construct a Filter matching values containing ``substring``. Parameters ---------- substring : str Sub-string against which to compare values produced by ``self``. Returns ------- matches : Filter Filter returning True for all sid/date pairs for ...
[ "Construct", "a", "Filter", "matching", "values", "containing", "substring", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/classifiers/classifier.py#L196-L215
train
quantopian/zipline
zipline/pipeline/classifiers/classifier.py
Classifier.matches
def matches(self, pattern): """ Construct a Filter that checks regex matches against ``pattern``. Parameters ---------- pattern : str Regex pattern against which to compare values produced by ``self``. Returns ------- matches : Filter ...
python
def matches(self, pattern): """ Construct a Filter that checks regex matches against ``pattern``. Parameters ---------- pattern : str Regex pattern against which to compare values produced by ``self``. Returns ------- matches : Filter ...
[ "def", "matches", "(", "self", ",", "pattern", ")", ":", "return", "ArrayPredicate", "(", "term", "=", "self", ",", "op", "=", "LabelArray", ".", "matches", ",", "opargs", "=", "(", "pattern", ",", ")", ",", ")" ]
Construct a Filter that checks regex matches against ``pattern``. Parameters ---------- pattern : str Regex pattern against which to compare values produced by ``self``. Returns ------- matches : Filter Filter returning True for all sid/date pair...
[ "Construct", "a", "Filter", "that", "checks", "regex", "matches", "against", "pattern", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/classifiers/classifier.py#L219-L242
train
quantopian/zipline
zipline/pipeline/classifiers/classifier.py
Classifier.element_of
def element_of(self, choices): """ Construct a Filter indicating whether values are in ``choices``. Parameters ---------- choices : iterable[str or int] An iterable of choices. Returns ------- matches : Filter Filter returning Tru...
python
def element_of(self, choices): """ Construct a Filter indicating whether values are in ``choices``. Parameters ---------- choices : iterable[str or int] An iterable of choices. Returns ------- matches : Filter Filter returning Tru...
[ "def", "element_of", "(", "self", ",", "choices", ")", ":", "try", ":", "choices", "=", "frozenset", "(", "choices", ")", "except", "Exception", "as", "e", ":", "raise", "TypeError", "(", "\"Expected `choices` to be an iterable of hashable values,\"", "\" but got {}...
Construct a Filter indicating whether values are in ``choices``. Parameters ---------- choices : iterable[str or int] An iterable of choices. Returns ------- matches : Filter Filter returning True for all sid/date pairs for which ``self`` ...
[ "Construct", "a", "Filter", "indicating", "whether", "values", "are", "in", "choices", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/classifiers/classifier.py#L264-L336
train
quantopian/zipline
zipline/pipeline/classifiers/classifier.py
Classifier.to_workspace_value
def to_workspace_value(self, result, assets): """ Called with the result of a pipeline. This needs to return an object which can be put into the workspace to continue doing computations. This is the inverse of :func:`~zipline.pipeline.term.Term.postprocess`. """ if self....
python
def to_workspace_value(self, result, assets): """ Called with the result of a pipeline. This needs to return an object which can be put into the workspace to continue doing computations. This is the inverse of :func:`~zipline.pipeline.term.Term.postprocess`. """ if self....
[ "def", "to_workspace_value", "(", "self", ",", "result", ",", "assets", ")", ":", "if", "self", ".", "dtype", "==", "int64_dtype", ":", "return", "super", "(", "Classifier", ",", "self", ")", ".", "to_workspace_value", "(", "result", ",", "assets", ")", ...
Called with the result of a pipeline. This needs to return an object which can be put into the workspace to continue doing computations. This is the inverse of :func:`~zipline.pipeline.term.Term.postprocess`.
[ "Called", "with", "the", "result", "of", "a", "pipeline", ".", "This", "needs", "to", "return", "an", "object", "which", "can", "be", "put", "into", "the", "workspace", "to", "continue", "doing", "computations", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/classifiers/classifier.py#L345-L371
train
quantopian/zipline
zipline/pipeline/classifiers/classifier.py
Classifier._to_integral
def _to_integral(self, output_array): """ Convert an array produced by this classifier into an array of integer labels and a missing value label. """ if self.dtype == int64_dtype: group_labels = output_array null_label = self.missing_value elif sel...
python
def _to_integral(self, output_array): """ Convert an array produced by this classifier into an array of integer labels and a missing value label. """ if self.dtype == int64_dtype: group_labels = output_array null_label = self.missing_value elif sel...
[ "def", "_to_integral", "(", "self", ",", "output_array", ")", ":", "if", "self", ".", "dtype", "==", "int64_dtype", ":", "group_labels", "=", "output_array", "null_label", "=", "self", ".", "missing_value", "elif", "self", ".", "dtype", "==", "categorical_dtyp...
Convert an array produced by this classifier into an array of integer labels and a missing value label.
[ "Convert", "an", "array", "produced", "by", "this", "classifier", "into", "an", "array", "of", "integer", "labels", "and", "a", "missing", "value", "label", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/classifiers/classifier.py#L381-L399
train
quantopian/zipline
zipline/pipeline/classifiers/classifier.py
CustomClassifier._allocate_output
def _allocate_output(self, windows, shape): """ Override the default array allocation to produce a LabelArray when we have a string-like dtype. """ if self.dtype == int64_dtype: return super(CustomClassifier, self)._allocate_output( windows, ...
python
def _allocate_output(self, windows, shape): """ Override the default array allocation to produce a LabelArray when we have a string-like dtype. """ if self.dtype == int64_dtype: return super(CustomClassifier, self)._allocate_output( windows, ...
[ "def", "_allocate_output", "(", "self", ",", "windows", ",", "shape", ")", ":", "if", "self", ".", "dtype", "==", "int64_dtype", ":", "return", "super", "(", "CustomClassifier", ",", "self", ")", ".", "_allocate_output", "(", "windows", ",", "shape", ",", ...
Override the default array allocation to produce a LabelArray when we have a string-like dtype.
[ "Override", "the", "default", "array", "allocation", "to", "produce", "a", "LabelArray", "when", "we", "have", "a", "string", "-", "like", "dtype", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/classifiers/classifier.py#L517-L531
train
quantopian/zipline
zipline/utils/input_validation.py
verify_indices_all_unique
def verify_indices_all_unique(obj): """ Check that all axes of a pandas object are unique. Parameters ---------- obj : pd.Series / pd.DataFrame / pd.Panel The object to validate. Returns ------- obj : pd.Series / pd.DataFrame / pd.Panel The validated object, unchanged. ...
python
def verify_indices_all_unique(obj): """ Check that all axes of a pandas object are unique. Parameters ---------- obj : pd.Series / pd.DataFrame / pd.Panel The object to validate. Returns ------- obj : pd.Series / pd.DataFrame / pd.Panel The validated object, unchanged. ...
[ "def", "verify_indices_all_unique", "(", "obj", ")", ":", "axis_names", "=", "[", "(", "'index'", ",", ")", ",", "# Series", "(", "'index'", ",", "'columns'", ")", ",", "# DataFrame", "(", "'items'", ",", "'major_axis'", ",", "'minor_axis'", ")", "# Panel", ...
Check that all axes of a pandas object are unique. Parameters ---------- obj : pd.Series / pd.DataFrame / pd.Panel The object to validate. Returns ------- obj : pd.Series / pd.DataFrame / pd.Panel The validated object, unchanged. Raises ------ ValueError If...
[ "Check", "that", "all", "axes", "of", "a", "pandas", "object", "are", "unique", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/input_validation.py#L50-L86
train
quantopian/zipline
zipline/utils/input_validation.py
optionally
def optionally(preprocessor): """Modify a preprocessor to explicitly allow `None`. Parameters ---------- preprocessor : callable[callable, str, any -> any] A preprocessor to delegate to when `arg is not None`. Returns ------- optional_preprocessor : callable[callable, str, any -> a...
python
def optionally(preprocessor): """Modify a preprocessor to explicitly allow `None`. Parameters ---------- preprocessor : callable[callable, str, any -> any] A preprocessor to delegate to when `arg is not None`. Returns ------- optional_preprocessor : callable[callable, str, any -> a...
[ "def", "optionally", "(", "preprocessor", ")", ":", "@", "wraps", "(", "preprocessor", ")", "def", "wrapper", "(", "func", ",", "argname", ",", "arg", ")", ":", "return", "arg", "if", "arg", "is", "None", "else", "preprocessor", "(", "func", ",", "argn...
Modify a preprocessor to explicitly allow `None`. Parameters ---------- preprocessor : callable[callable, str, any -> any] A preprocessor to delegate to when `arg is not None`. Returns ------- optional_preprocessor : callable[callable, str, any -> any] A preprocessor that deleg...
[ "Modify", "a", "preprocessor", "to", "explicitly", "allow", "None", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/input_validation.py#L89-L126
train
quantopian/zipline
zipline/utils/input_validation.py
ensure_dtype
def ensure_dtype(func, argname, arg): """ Argument preprocessor that converts the input into a numpy dtype. Examples -------- >>> import numpy as np >>> from zipline.utils.preprocess import preprocess >>> @preprocess(dtype=ensure_dtype) ... def foo(dtype): ... return dtype ....
python
def ensure_dtype(func, argname, arg): """ Argument preprocessor that converts the input into a numpy dtype. Examples -------- >>> import numpy as np >>> from zipline.utils.preprocess import preprocess >>> @preprocess(dtype=ensure_dtype) ... def foo(dtype): ... return dtype ....
[ "def", "ensure_dtype", "(", "func", ",", "argname", ",", "arg", ")", ":", "try", ":", "return", "dtype", "(", "arg", ")", "except", "TypeError", ":", "raise", "TypeError", "(", "\"{func}() couldn't convert argument \"", "\"{argname}={arg!r} to a numpy dtype.\"", "."...
Argument preprocessor that converts the input into a numpy dtype. Examples -------- >>> import numpy as np >>> from zipline.utils.preprocess import preprocess >>> @preprocess(dtype=ensure_dtype) ... def foo(dtype): ... return dtype ... >>> foo(float) dtype('float64')
[ "Argument", "preprocessor", "that", "converts", "the", "input", "into", "a", "numpy", "dtype", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/input_validation.py#L143-L168
train
quantopian/zipline
zipline/utils/input_validation.py
ensure_timezone
def ensure_timezone(func, argname, arg): """Argument preprocessor that converts the input into a tzinfo object. Examples -------- >>> from zipline.utils.preprocess import preprocess >>> @preprocess(tz=ensure_timezone) ... def foo(tz): ... return tz >>> foo('utc') <UTC> """ ...
python
def ensure_timezone(func, argname, arg): """Argument preprocessor that converts the input into a tzinfo object. Examples -------- >>> from zipline.utils.preprocess import preprocess >>> @preprocess(tz=ensure_timezone) ... def foo(tz): ... return tz >>> foo('utc') <UTC> """ ...
[ "def", "ensure_timezone", "(", "func", ",", "argname", ",", "arg", ")", ":", "if", "isinstance", "(", "arg", ",", "tzinfo", ")", ":", "return", "arg", "if", "isinstance", "(", "arg", ",", "string_types", ")", ":", "return", "timezone", "(", "arg", ")",...
Argument preprocessor that converts the input into a tzinfo object. Examples -------- >>> from zipline.utils.preprocess import preprocess >>> @preprocess(tz=ensure_timezone) ... def foo(tz): ... return tz >>> foo('utc') <UTC>
[ "Argument", "preprocessor", "that", "converts", "the", "input", "into", "a", "tzinfo", "object", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/input_validation.py#L171-L195
train
quantopian/zipline
zipline/utils/input_validation.py
ensure_timestamp
def ensure_timestamp(func, argname, arg): """Argument preprocessor that converts the input into a pandas Timestamp object. Examples -------- >>> from zipline.utils.preprocess import preprocess >>> @preprocess(ts=ensure_timestamp) ... def foo(ts): ... return ts >>> foo('2014-01-0...
python
def ensure_timestamp(func, argname, arg): """Argument preprocessor that converts the input into a pandas Timestamp object. Examples -------- >>> from zipline.utils.preprocess import preprocess >>> @preprocess(ts=ensure_timestamp) ... def foo(ts): ... return ts >>> foo('2014-01-0...
[ "def", "ensure_timestamp", "(", "func", ",", "argname", ",", "arg", ")", ":", "try", ":", "return", "pd", ".", "Timestamp", "(", "arg", ")", "except", "ValueError", "as", "e", ":", "raise", "TypeError", "(", "\"{func}() couldn't convert argument \"", "\"{argna...
Argument preprocessor that converts the input into a pandas Timestamp object. Examples -------- >>> from zipline.utils.preprocess import preprocess >>> @preprocess(ts=ensure_timestamp) ... def foo(ts): ... return ts >>> foo('2014-01-01') Timestamp('2014-01-01 00:00:00')
[ "Argument", "preprocessor", "that", "converts", "the", "input", "into", "a", "pandas", "Timestamp", "object", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/input_validation.py#L198-L224
train
quantopian/zipline
zipline/utils/input_validation.py
expect_dtypes
def expect_dtypes(__funcname=_qualified_name, **named): """ Preprocessing decorator that verifies inputs have expected numpy dtypes. Examples -------- >>> from numpy import dtype, arange, int8, float64 >>> @expect_dtypes(x=dtype(int8)) ... def foo(x, y): ... return x, y ... >...
python
def expect_dtypes(__funcname=_qualified_name, **named): """ Preprocessing decorator that verifies inputs have expected numpy dtypes. Examples -------- >>> from numpy import dtype, arange, int8, float64 >>> @expect_dtypes(x=dtype(int8)) ... def foo(x, y): ... return x, y ... >...
[ "def", "expect_dtypes", "(", "__funcname", "=", "_qualified_name", ",", "*", "*", "named", ")", ":", "for", "name", ",", "type_", "in", "iteritems", "(", "named", ")", ":", "if", "not", "isinstance", "(", "type_", ",", "(", "dtype", ",", "tuple", ")", ...
Preprocessing decorator that verifies inputs have expected numpy dtypes. Examples -------- >>> from numpy import dtype, arange, int8, float64 >>> @expect_dtypes(x=dtype(int8)) ... def foo(x, y): ... return x, y ... >>> foo(arange(3, dtype=int8), 'foo') (array([0, 1, 2], dtype=int...
[ "Preprocessing", "decorator", "that", "verifies", "inputs", "have", "expected", "numpy", "dtypes", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/input_validation.py#L227-L292
train
quantopian/zipline
zipline/utils/input_validation.py
expect_kinds
def expect_kinds(**named): """ Preprocessing decorator that verifies inputs have expected dtype kinds. Examples -------- >>> from numpy import int64, int32, float32 >>> @expect_kinds(x='i') ... def foo(x): ... return x ... >>> foo(int64(2)) 2 >>> foo(int32(2)) 2 ...
python
def expect_kinds(**named): """ Preprocessing decorator that verifies inputs have expected dtype kinds. Examples -------- >>> from numpy import int64, int32, float32 >>> @expect_kinds(x='i') ... def foo(x): ... return x ... >>> foo(int64(2)) 2 >>> foo(int32(2)) 2 ...
[ "def", "expect_kinds", "(", "*", "*", "named", ")", ":", "for", "name", ",", "kind", "in", "iteritems", "(", "named", ")", ":", "if", "not", "isinstance", "(", "kind", ",", "(", "str", ",", "tuple", ")", ")", ":", "raise", "TypeError", "(", "\"expe...
Preprocessing decorator that verifies inputs have expected dtype kinds. Examples -------- >>> from numpy import int64, int32, float32 >>> @expect_kinds(x='i') ... def foo(x): ... return x ... >>> foo(int64(2)) 2 >>> foo(int32(2)) 2 >>> foo(float32(2)) # doctest: +NOR...
[ "Preprocessing", "decorator", "that", "verifies", "inputs", "have", "expected", "dtype", "kinds", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/input_validation.py#L295-L355
train
quantopian/zipline
zipline/utils/input_validation.py
expect_types
def expect_types(__funcname=_qualified_name, **named): """ Preprocessing decorator that verifies inputs have expected types. Examples -------- >>> @expect_types(x=int, y=str) ... def foo(x, y): ... return x, y ... >>> foo(2, '3') (2, '3') >>> foo(2.0, '3') # doctest: +NO...
python
def expect_types(__funcname=_qualified_name, **named): """ Preprocessing decorator that verifies inputs have expected types. Examples -------- >>> @expect_types(x=int, y=str) ... def foo(x, y): ... return x, y ... >>> foo(2, '3') (2, '3') >>> foo(2.0, '3') # doctest: +NO...
[ "def", "expect_types", "(", "__funcname", "=", "_qualified_name", ",", "*", "*", "named", ")", ":", "for", "name", ",", "type_", "in", "iteritems", "(", "named", ")", ":", "if", "not", "isinstance", "(", "type_", ",", "(", "type", ",", "tuple", ")", ...
Preprocessing decorator that verifies inputs have expected types. Examples -------- >>> @expect_types(x=int, y=str) ... def foo(x, y): ... return x, y ... >>> foo(2, '3') (2, '3') >>> foo(2.0, '3') # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS Traceback (most recent call last):...
[ "Preprocessing", "decorator", "that", "verifies", "inputs", "have", "expected", "types", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/input_validation.py#L358-L413
train
quantopian/zipline
zipline/utils/input_validation.py
make_check
def make_check(exc_type, template, pred, actual, funcname): """ Factory for making preprocessing functions that check a predicate on the input value. Parameters ---------- exc_type : Exception The exception type to raise if the predicate fails. template : str A template stri...
python
def make_check(exc_type, template, pred, actual, funcname): """ Factory for making preprocessing functions that check a predicate on the input value. Parameters ---------- exc_type : Exception The exception type to raise if the predicate fails. template : str A template stri...
[ "def", "make_check", "(", "exc_type", ",", "template", ",", "pred", ",", "actual", ",", "funcname", ")", ":", "if", "isinstance", "(", "funcname", ",", "str", ")", ":", "def", "get_funcname", "(", "_", ")", ":", "return", "funcname", "else", ":", "get_...
Factory for making preprocessing functions that check a predicate on the input value. Parameters ---------- exc_type : Exception The exception type to raise if the predicate fails. template : str A template string to use to create error messages. Should have %-style named te...
[ "Factory", "for", "making", "preprocessing", "functions", "that", "check", "a", "predicate", "on", "the", "input", "value", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/input_validation.py#L416-L457
train
quantopian/zipline
zipline/utils/input_validation.py
expect_element
def expect_element(__funcname=_qualified_name, **named): """ Preprocessing decorator that verifies inputs are elements of some expected collection. Examples -------- >>> @expect_element(x=('a', 'b')) ... def foo(x): ... return x.upper() ... >>> foo('a') 'A' >>> foo('b...
python
def expect_element(__funcname=_qualified_name, **named): """ Preprocessing decorator that verifies inputs are elements of some expected collection. Examples -------- >>> @expect_element(x=('a', 'b')) ... def foo(x): ... return x.upper() ... >>> foo('a') 'A' >>> foo('b...
[ "def", "expect_element", "(", "__funcname", "=", "_qualified_name", ",", "*", "*", "named", ")", ":", "def", "_expect_element", "(", "collection", ")", ":", "if", "isinstance", "(", "collection", ",", "(", "set", ",", "frozenset", ")", ")", ":", "# Special...
Preprocessing decorator that verifies inputs are elements of some expected collection. Examples -------- >>> @expect_element(x=('a', 'b')) ... def foo(x): ... return x.upper() ... >>> foo('a') 'A' >>> foo('b') 'B' >>> foo('c') # doctest: +NORMALIZE_WHITESPACE +ELLIPS...
[ "Preprocessing", "decorator", "that", "verifies", "inputs", "are", "elements", "of", "some", "expected", "collection", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/input_validation.py#L484-L535
train
quantopian/zipline
zipline/utils/input_validation.py
expect_bounded
def expect_bounded(__funcname=_qualified_name, **named): """ Preprocessing decorator verifying that inputs fall INCLUSIVELY between bounds. Bounds should be passed as a pair of ``(min_value, max_value)``. ``None`` may be passed as ``min_value`` or ``max_value`` to signify that the input is onl...
python
def expect_bounded(__funcname=_qualified_name, **named): """ Preprocessing decorator verifying that inputs fall INCLUSIVELY between bounds. Bounds should be passed as a pair of ``(min_value, max_value)``. ``None`` may be passed as ``min_value`` or ``max_value`` to signify that the input is onl...
[ "def", "expect_bounded", "(", "__funcname", "=", "_qualified_name", ",", "*", "*", "named", ")", ":", "def", "_make_bounded_check", "(", "bounds", ")", ":", "(", "lower", ",", "upper", ")", "=", "bounds", "if", "lower", "is", "None", ":", "def", "should_...
Preprocessing decorator verifying that inputs fall INCLUSIVELY between bounds. Bounds should be passed as a pair of ``(min_value, max_value)``. ``None`` may be passed as ``min_value`` or ``max_value`` to signify that the input is only bounded above or below. Examples -------- >>> @expect_...
[ "Preprocessing", "decorator", "verifying", "that", "inputs", "fall", "INCLUSIVELY", "between", "bounds", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/input_validation.py#L538-L614
train
quantopian/zipline
zipline/utils/input_validation.py
expect_dimensions
def expect_dimensions(__funcname=_qualified_name, **dimensions): """ Preprocessing decorator that verifies inputs are numpy arrays with a specific dimensionality. Examples -------- >>> from numpy import array >>> @expect_dimensions(x=1, y=2) ... def foo(x, y): ... return x[0] + y...
python
def expect_dimensions(__funcname=_qualified_name, **dimensions): """ Preprocessing decorator that verifies inputs are numpy arrays with a specific dimensionality. Examples -------- >>> from numpy import array >>> @expect_dimensions(x=1, y=2) ... def foo(x, y): ... return x[0] + y...
[ "def", "expect_dimensions", "(", "__funcname", "=", "_qualified_name", ",", "*", "*", "dimensions", ")", ":", "if", "isinstance", "(", "__funcname", ",", "str", ")", ":", "def", "get_funcname", "(", "_", ")", ":", "return", "__funcname", "else", ":", "get_...
Preprocessing decorator that verifies inputs are numpy arrays with a specific dimensionality. Examples -------- >>> from numpy import array >>> @expect_dimensions(x=1, y=2) ... def foo(x, y): ... return x[0] + y[0, 0] ... >>> foo(array([1, 1]), array([[1, 1], [2, 2]])) 2 ...
[ "Preprocessing", "decorator", "that", "verifies", "inputs", "are", "numpy", "arrays", "with", "a", "specific", "dimensionality", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/input_validation.py#L717-L764
train
quantopian/zipline
zipline/utils/input_validation.py
coerce
def coerce(from_, to, **to_kwargs): """ A preprocessing decorator that coerces inputs of a given type by passing them to a callable. Parameters ---------- from : type or tuple or types Inputs types on which to call ``to``. to : function Coercion function to call on inputs. ...
python
def coerce(from_, to, **to_kwargs): """ A preprocessing decorator that coerces inputs of a given type by passing them to a callable. Parameters ---------- from : type or tuple or types Inputs types on which to call ``to``. to : function Coercion function to call on inputs. ...
[ "def", "coerce", "(", "from_", ",", "to", ",", "*", "*", "to_kwargs", ")", ":", "def", "preprocessor", "(", "func", ",", "argname", ",", "arg", ")", ":", "if", "isinstance", "(", "arg", ",", "from_", ")", ":", "return", "to", "(", "arg", ",", "*"...
A preprocessing decorator that coerces inputs of a given type by passing them to a callable. Parameters ---------- from : type or tuple or types Inputs types on which to call ``to``. to : function Coercion function to call on inputs. **to_kwargs Additional keywords to fo...
[ "A", "preprocessing", "decorator", "that", "coerces", "inputs", "of", "a", "given", "type", "by", "passing", "them", "to", "a", "callable", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/input_validation.py#L767-L801
train
quantopian/zipline
zipline/utils/input_validation.py
coerce_types
def coerce_types(**kwargs): """ Preprocessing decorator that applies type coercions. Parameters ---------- **kwargs : dict[str -> (type, callable)] Keyword arguments mapping function parameter names to pairs of (from_type, to_type). Examples -------- >>> @coerce_types...
python
def coerce_types(**kwargs): """ Preprocessing decorator that applies type coercions. Parameters ---------- **kwargs : dict[str -> (type, callable)] Keyword arguments mapping function parameter names to pairs of (from_type, to_type). Examples -------- >>> @coerce_types...
[ "def", "coerce_types", "(", "*", "*", "kwargs", ")", ":", "def", "_coerce", "(", "types", ")", ":", "return", "coerce", "(", "*", "types", ")", "return", "preprocess", "(", "*", "*", "valmap", "(", "_coerce", ",", "kwargs", ")", ")" ]
Preprocessing decorator that applies type coercions. Parameters ---------- **kwargs : dict[str -> (type, callable)] Keyword arguments mapping function parameter names to pairs of (from_type, to_type). Examples -------- >>> @coerce_types(x=(float, int), y=(int, str)) ... d...
[ "Preprocessing", "decorator", "that", "applies", "type", "coercions", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/input_validation.py#L804-L826
train
quantopian/zipline
zipline/utils/input_validation.py
validate_keys
def validate_keys(dict_, expected, funcname): """Validate that a dictionary has an expected set of keys. """ expected = set(expected) received = set(dict_) missing = expected - received if missing: raise ValueError( "Missing keys in {}:\n" "Expected Keys: {}\n" ...
python
def validate_keys(dict_, expected, funcname): """Validate that a dictionary has an expected set of keys. """ expected = set(expected) received = set(dict_) missing = expected - received if missing: raise ValueError( "Missing keys in {}:\n" "Expected Keys: {}\n" ...
[ "def", "validate_keys", "(", "dict_", ",", "expected", ",", "funcname", ")", ":", "expected", "=", "set", "(", "expected", ")", "received", "=", "set", "(", "dict_", ")", "missing", "=", "expected", "-", "received", "if", "missing", ":", "raise", "ValueE...
Validate that a dictionary has an expected set of keys.
[ "Validate", "that", "a", "dictionary", "has", "an", "expected", "set", "of", "keys", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/input_validation.py#L847-L875
train
quantopian/zipline
zipline/utils/enum.py
enum
def enum(option, *options): """ Construct a new enum object. Parameters ---------- *options : iterable of str The names of the fields for the enum. Returns ------- enum A new enum collection. Examples -------- >>> e = enum('a', 'b', 'c') >>> e <enum...
python
def enum(option, *options): """ Construct a new enum object. Parameters ---------- *options : iterable of str The names of the fields for the enum. Returns ------- enum A new enum collection. Examples -------- >>> e = enum('a', 'b', 'c') >>> e <enum...
[ "def", "enum", "(", "option", ",", "*", "options", ")", ":", "options", "=", "(", "option", ",", ")", "+", "options", "rangeob", "=", "range", "(", "len", "(", "options", ")", ")", "try", ":", "inttype", "=", "_inttypes", "[", "int", "(", "np", "...
Construct a new enum object. Parameters ---------- *options : iterable of str The names of the fields for the enum. Returns ------- enum A new enum collection. Examples -------- >>> e = enum('a', 'b', 'c') >>> e <enum: ('a', 'b', 'c')> >>> e.a 0 ...
[ "Construct", "a", "new", "enum", "object", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/enum.py#L48-L114
train
quantopian/zipline
zipline/utils/data.py
RollingPanel.oldest_frame
def oldest_frame(self, raw=False): """ Get the oldest frame in the panel. """ if raw: return self.buffer.values[:, self._start_index, :] return self.buffer.iloc[:, self._start_index, :]
python
def oldest_frame(self, raw=False): """ Get the oldest frame in the panel. """ if raw: return self.buffer.values[:, self._start_index, :] return self.buffer.iloc[:, self._start_index, :]
[ "def", "oldest_frame", "(", "self", ",", "raw", "=", "False", ")", ":", "if", "raw", ":", "return", "self", ".", "buffer", ".", "values", "[", ":", ",", "self", ".", "_start_index", ",", ":", "]", "return", "self", ".", "buffer", ".", "iloc", "[", ...
Get the oldest frame in the panel.
[ "Get", "the", "oldest", "frame", "in", "the", "panel", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/data.py#L82-L88
train
quantopian/zipline
zipline/utils/data.py
RollingPanel.extend_back
def extend_back(self, missing_dts): """ Resizes the buffer to hold a new window with a new cap_multiple. If cap_multiple is None, then the old cap_multiple is used. """ delta = len(missing_dts) if not delta: raise ValueError( 'missing_dts must...
python
def extend_back(self, missing_dts): """ Resizes the buffer to hold a new window with a new cap_multiple. If cap_multiple is None, then the old cap_multiple is used. """ delta = len(missing_dts) if not delta: raise ValueError( 'missing_dts must...
[ "def", "extend_back", "(", "self", ",", "missing_dts", ")", ":", "delta", "=", "len", "(", "missing_dts", ")", "if", "not", "delta", ":", "raise", "ValueError", "(", "'missing_dts must be a non-empty index'", ",", ")", "self", ".", "_window", "+=", "delta", ...
Resizes the buffer to hold a new window with a new cap_multiple. If cap_multiple is None, then the old cap_multiple is used.
[ "Resizes", "the", "buffer", "to", "hold", "a", "new", "window", "with", "a", "new", "cap_multiple", ".", "If", "cap_multiple", "is", "None", "then", "the", "old", "cap_multiple", "is", "used", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/data.py#L107-L148
train
quantopian/zipline
zipline/utils/data.py
RollingPanel.get_current
def get_current(self, item=None, raw=False, start=None, end=None): """ Get a Panel that is the current data in view. It is not safe to persist these objects because internal data might change """ item_indexer = slice(None) if item: item_indexer = self.items.ge...
python
def get_current(self, item=None, raw=False, start=None, end=None): """ Get a Panel that is the current data in view. It is not safe to persist these objects because internal data might change """ item_indexer = slice(None) if item: item_indexer = self.items.ge...
[ "def", "get_current", "(", "self", ",", "item", "=", "None", ",", "raw", "=", "False", ",", "start", "=", "None", ",", "end", "=", "None", ")", ":", "item_indexer", "=", "slice", "(", "None", ")", "if", "item", ":", "item_indexer", "=", "self", "."...
Get a Panel that is the current data in view. It is not safe to persist these objects because internal data might change
[ "Get", "a", "Panel", "that", "is", "the", "current", "data", "in", "view", ".", "It", "is", "not", "safe", "to", "persist", "these", "objects", "because", "internal", "data", "might", "change" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/data.py#L165-L214
train
quantopian/zipline
zipline/utils/data.py
RollingPanel.set_current
def set_current(self, panel): """ Set the values stored in our current in-view data to be values of the passed panel. The passed panel must have the same indices as the panel that would be returned by self.get_current. """ where = slice(self._start_index, self._pos) ...
python
def set_current(self, panel): """ Set the values stored in our current in-view data to be values of the passed panel. The passed panel must have the same indices as the panel that would be returned by self.get_current. """ where = slice(self._start_index, self._pos) ...
[ "def", "set_current", "(", "self", ",", "panel", ")", ":", "where", "=", "slice", "(", "self", ".", "_start_index", ",", "self", ".", "_pos", ")", "self", ".", "buffer", ".", "values", "[", ":", ",", "where", ",", ":", "]", "=", "panel", ".", "va...
Set the values stored in our current in-view data to be values of the passed panel. The passed panel must have the same indices as the panel that would be returned by self.get_current.
[ "Set", "the", "values", "stored", "in", "our", "current", "in", "-", "view", "data", "to", "be", "values", "of", "the", "passed", "panel", ".", "The", "passed", "panel", "must", "have", "the", "same", "indices", "as", "the", "panel", "that", "would", "...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/data.py#L216-L223
train
quantopian/zipline
zipline/utils/data.py
RollingPanel._roll_data
def _roll_data(self): """ Roll window worth of data up to position zero. Save the effort of having to expensively roll at each iteration """ self.buffer.values[:, :self._window, :] = \ self.buffer.values[:, -self._window:, :] self.date_buf[:self._window] = se...
python
def _roll_data(self): """ Roll window worth of data up to position zero. Save the effort of having to expensively roll at each iteration """ self.buffer.values[:, :self._window, :] = \ self.buffer.values[:, -self._window:, :] self.date_buf[:self._window] = se...
[ "def", "_roll_data", "(", "self", ")", ":", "self", ".", "buffer", ".", "values", "[", ":", ",", ":", "self", ".", "_window", ",", ":", "]", "=", "self", ".", "buffer", ".", "values", "[", ":", ",", "-", "self", ".", "_window", ":", ",", ":", ...
Roll window worth of data up to position zero. Save the effort of having to expensively roll at each iteration
[ "Roll", "window", "worth", "of", "data", "up", "to", "position", "zero", ".", "Save", "the", "effort", "of", "having", "to", "expensively", "roll", "at", "each", "iteration" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/data.py#L229-L238
train
quantopian/zipline
zipline/utils/data.py
MutableIndexRollingPanel.oldest_frame
def oldest_frame(self, raw=False): """ Get the oldest frame in the panel. """ if raw: return self.buffer.values[:, self._oldest_frame_idx(), :] return self.buffer.iloc[:, self._oldest_frame_idx(), :]
python
def oldest_frame(self, raw=False): """ Get the oldest frame in the panel. """ if raw: return self.buffer.values[:, self._oldest_frame_idx(), :] return self.buffer.iloc[:, self._oldest_frame_idx(), :]
[ "def", "oldest_frame", "(", "self", ",", "raw", "=", "False", ")", ":", "if", "raw", ":", "return", "self", ".", "buffer", ".", "values", "[", ":", ",", "self", ".", "_oldest_frame_idx", "(", ")", ",", ":", "]", "return", "self", ".", "buffer", "."...
Get the oldest frame in the panel.
[ "Get", "the", "oldest", "frame", "in", "the", "panel", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/data.py#L273-L279
train
quantopian/zipline
zipline/utils/data.py
MutableIndexRollingPanel.get_current
def get_current(self): """ Get a Panel that is the current data in view. It is not safe to persist these objects because internal data might change """ where = slice(self._oldest_frame_idx(), self._pos) major_axis = pd.DatetimeIndex(deepcopy(self.date_buf[where]), tz='ut...
python
def get_current(self): """ Get a Panel that is the current data in view. It is not safe to persist these objects because internal data might change """ where = slice(self._oldest_frame_idx(), self._pos) major_axis = pd.DatetimeIndex(deepcopy(self.date_buf[where]), tz='ut...
[ "def", "get_current", "(", "self", ")", ":", "where", "=", "slice", "(", "self", ".", "_oldest_frame_idx", "(", ")", ",", "self", ".", "_pos", ")", "major_axis", "=", "pd", ".", "DatetimeIndex", "(", "deepcopy", "(", "self", ".", "date_buf", "[", "wher...
Get a Panel that is the current data in view. It is not safe to persist these objects because internal data might change
[ "Get", "a", "Panel", "that", "is", "the", "current", "data", "in", "view", ".", "It", "is", "not", "safe", "to", "persist", "these", "objects", "because", "internal", "data", "might", "change" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/data.py#L294-L303
train
quantopian/zipline
zipline/finance/order.py
Order.check_triggers
def check_triggers(self, price, dt): """ Update internal state based on price triggers and the trade event's price. """ stop_reached, limit_reached, sl_stop_reached = \ self.check_order_triggers(price) if (stop_reached, limit_reached) \ != (sel...
python
def check_triggers(self, price, dt): """ Update internal state based on price triggers and the trade event's price. """ stop_reached, limit_reached, sl_stop_reached = \ self.check_order_triggers(price) if (stop_reached, limit_reached) \ != (sel...
[ "def", "check_triggers", "(", "self", ",", "price", ",", "dt", ")", ":", "stop_reached", ",", "limit_reached", ",", "sl_stop_reached", "=", "self", ".", "check_order_triggers", "(", "price", ")", "if", "(", "stop_reached", ",", "limit_reached", ")", "!=", "(...
Update internal state based on price triggers and the trade event's price.
[ "Update", "internal", "state", "based", "on", "price", "triggers", "and", "the", "trade", "event", "s", "price", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/order.py#L108-L122
train
quantopian/zipline
zipline/finance/order.py
Order.check_order_triggers
def check_order_triggers(self, current_price): """ Given an order and a trade event, return a tuple of (stop_reached, limit_reached). For market orders, will return (False, False). For stop orders, limit_reached will always be False. For limit orders, stop_reached will al...
python
def check_order_triggers(self, current_price): """ Given an order and a trade event, return a tuple of (stop_reached, limit_reached). For market orders, will return (False, False). For stop orders, limit_reached will always be False. For limit orders, stop_reached will al...
[ "def", "check_order_triggers", "(", "self", ",", "current_price", ")", ":", "if", "self", ".", "triggered", ":", "return", "(", "self", ".", "stop_reached", ",", "self", ".", "limit_reached", ",", "False", ")", "stop_reached", "=", "False", "limit_reached", ...
Given an order and a trade event, return a tuple of (stop_reached, limit_reached). For market orders, will return (False, False). For stop orders, limit_reached will always be False. For limit orders, stop_reached will always be False. For stop limit orders a Boolean is returned ...
[ "Given", "an", "order", "and", "a", "trade", "event", "return", "a", "tuple", "of", "(", "stop_reached", "limit_reached", ")", ".", "For", "market", "orders", "will", "return", "(", "False", "False", ")", ".", "For", "stop", "orders", "limit_reached", "wil...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/order.py#L124-L181
train
quantopian/zipline
zipline/finance/order.py
Order.triggered
def triggered(self): """ For a market order, True. For a stop order, True IFF stop_reached. For a limit order, True IFF limit_reached. """ if self.stop is not None and not self.stop_reached: return False if self.limit is not None and not self.limit_re...
python
def triggered(self): """ For a market order, True. For a stop order, True IFF stop_reached. For a limit order, True IFF limit_reached. """ if self.stop is not None and not self.stop_reached: return False if self.limit is not None and not self.limit_re...
[ "def", "triggered", "(", "self", ")", ":", "if", "self", ".", "stop", "is", "not", "None", "and", "not", "self", ".", "stop_reached", ":", "return", "False", "if", "self", ".", "limit", "is", "not", "None", "and", "not", "self", ".", "limit_reached", ...
For a market order, True. For a stop order, True IFF stop_reached. For a limit order, True IFF limit_reached.
[ "For", "a", "market", "order", "True", ".", "For", "a", "stop", "order", "True", "IFF", "stop_reached", ".", "For", "a", "limit", "order", "True", "IFF", "limit_reached", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/order.py#L230-L242
train
quantopian/zipline
zipline/__init__.py
setup
def setup(self, np=np, numpy_version=numpy_version, StrictVersion=StrictVersion, new_pandas=new_pandas): """Lives in zipline.__init__ for doctests.""" if numpy_version >= StrictVersion('1.14'): self.old_opts = np.get_printoptions() np.set_printoptions(leg...
python
def setup(self, np=np, numpy_version=numpy_version, StrictVersion=StrictVersion, new_pandas=new_pandas): """Lives in zipline.__init__ for doctests.""" if numpy_version >= StrictVersion('1.14'): self.old_opts = np.get_printoptions() np.set_printoptions(leg...
[ "def", "setup", "(", "self", ",", "np", "=", "np", ",", "numpy_version", "=", "numpy_version", ",", "StrictVersion", "=", "StrictVersion", ",", "new_pandas", "=", "new_pandas", ")", ":", "if", "numpy_version", ">=", "StrictVersion", "(", "'1.14'", ")", ":", ...
Lives in zipline.__init__ for doctests.
[ "Lives", "in", "zipline", ".", "__init__", "for", "doctests", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/__init__.py#L93-L111
train
quantopian/zipline
zipline/__init__.py
teardown
def teardown(self, np=np): """Lives in zipline.__init__ for doctests.""" if self.old_err is not None: np.seterr(**self.old_err) if self.old_opts is not None: np.set_printoptions(**self.old_opts)
python
def teardown(self, np=np): """Lives in zipline.__init__ for doctests.""" if self.old_err is not None: np.seterr(**self.old_err) if self.old_opts is not None: np.set_printoptions(**self.old_opts)
[ "def", "teardown", "(", "self", ",", "np", "=", "np", ")", ":", "if", "self", ".", "old_err", "is", "not", "None", ":", "np", ".", "seterr", "(", "*", "*", "self", ".", "old_err", ")", "if", "self", ".", "old_opts", "is", "not", "None", ":", "n...
Lives in zipline.__init__ for doctests.
[ "Lives", "in", "zipline", ".", "__init__", "for", "doctests", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/__init__.py#L114-L121
train
quantopian/zipline
zipline/gens/utils.py
hash_args
def hash_args(*args, **kwargs): """Define a unique string for any set of representable args.""" arg_string = '_'.join([str(arg) for arg in args]) kwarg_string = '_'.join([str(key) + '=' + str(value) for key, value in iteritems(kwargs)]) combined = ':'.join([arg_string, kwarg...
python
def hash_args(*args, **kwargs): """Define a unique string for any set of representable args.""" arg_string = '_'.join([str(arg) for arg in args]) kwarg_string = '_'.join([str(key) + '=' + str(value) for key, value in iteritems(kwargs)]) combined = ':'.join([arg_string, kwarg...
[ "def", "hash_args", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "arg_string", "=", "'_'", ".", "join", "(", "[", "str", "(", "arg", ")", "for", "arg", "in", "args", "]", ")", "kwarg_string", "=", "'_'", ".", "join", "(", "[", "str", "(...
Define a unique string for any set of representable args.
[ "Define", "a", "unique", "string", "for", "any", "set", "of", "representable", "args", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/gens/utils.py#L27-L36
train
quantopian/zipline
zipline/gens/utils.py
assert_datasource_protocol
def assert_datasource_protocol(event): """Assert that an event meets the protocol for datasource outputs.""" assert event.type in DATASOURCE_TYPE # Done packets have no dt. if not event.type == DATASOURCE_TYPE.DONE: assert isinstance(event.dt, datetime) assert event.dt.tzinfo == pytz.u...
python
def assert_datasource_protocol(event): """Assert that an event meets the protocol for datasource outputs.""" assert event.type in DATASOURCE_TYPE # Done packets have no dt. if not event.type == DATASOURCE_TYPE.DONE: assert isinstance(event.dt, datetime) assert event.dt.tzinfo == pytz.u...
[ "def", "assert_datasource_protocol", "(", "event", ")", ":", "assert", "event", ".", "type", "in", "DATASOURCE_TYPE", "# Done packets have no dt.", "if", "not", "event", ".", "type", "==", "DATASOURCE_TYPE", ".", "DONE", ":", "assert", "isinstance", "(", "event", ...
Assert that an event meets the protocol for datasource outputs.
[ "Assert", "that", "an", "event", "meets", "the", "protocol", "for", "datasource", "outputs", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/gens/utils.py#L39-L47
train
quantopian/zipline
zipline/gens/utils.py
assert_trade_protocol
def assert_trade_protocol(event): """Assert that an event meets the protocol for datasource TRADE outputs.""" assert_datasource_protocol(event) assert event.type == DATASOURCE_TYPE.TRADE assert isinstance(event.price, numbers.Real) assert isinstance(event.volume, numbers.Integral) assert isinst...
python
def assert_trade_protocol(event): """Assert that an event meets the protocol for datasource TRADE outputs.""" assert_datasource_protocol(event) assert event.type == DATASOURCE_TYPE.TRADE assert isinstance(event.price, numbers.Real) assert isinstance(event.volume, numbers.Integral) assert isinst...
[ "def", "assert_trade_protocol", "(", "event", ")", ":", "assert_datasource_protocol", "(", "event", ")", "assert", "event", ".", "type", "==", "DATASOURCE_TYPE", ".", "TRADE", "assert", "isinstance", "(", "event", ".", "price", ",", "numbers", ".", "Real", ")"...
Assert that an event meets the protocol for datasource TRADE outputs.
[ "Assert", "that", "an", "event", "meets", "the", "protocol", "for", "datasource", "TRADE", "outputs", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/gens/utils.py#L50-L57
train
quantopian/zipline
zipline/gens/composites.py
date_sorted_sources
def date_sorted_sources(*sources): """ Takes an iterable of sources, generating namestrings and piping their output into date_sort. """ sorted_stream = heapq.merge(*(_decorate_source(s) for s in sources)) # Strip out key decoration for _, message in sorted_stream: yield message
python
def date_sorted_sources(*sources): """ Takes an iterable of sources, generating namestrings and piping their output into date_sort. """ sorted_stream = heapq.merge(*(_decorate_source(s) for s in sources)) # Strip out key decoration for _, message in sorted_stream: yield message
[ "def", "date_sorted_sources", "(", "*", "sources", ")", ":", "sorted_stream", "=", "heapq", ".", "merge", "(", "*", "(", "_decorate_source", "(", "s", ")", "for", "s", "in", "sources", ")", ")", "# Strip out key decoration", "for", "_", ",", "message", "in...
Takes an iterable of sources, generating namestrings and piping their output into date_sort.
[ "Takes", "an", "iterable", "of", "sources", "generating", "namestrings", "and", "piping", "their", "output", "into", "date_sort", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/gens/composites.py#L24-L33
train
quantopian/zipline
zipline/utils/factory.py
create_daily_trade_source
def create_daily_trade_source(sids, sim_params, asset_finder, trading_calendar): """ creates trade_count trades for each sid in sids list. first trade will be on sim_params.start_session, and daily thereafter for e...
python
def create_daily_trade_source(sids, sim_params, asset_finder, trading_calendar): """ creates trade_count trades for each sid in sids list. first trade will be on sim_params.start_session, and daily thereafter for e...
[ "def", "create_daily_trade_source", "(", "sids", ",", "sim_params", ",", "asset_finder", ",", "trading_calendar", ")", ":", "return", "create_trade_source", "(", "sids", ",", "timedelta", "(", "days", "=", "1", ")", ",", "sim_params", ",", "asset_finder", ",", ...
creates trade_count trades for each sid in sids list. first trade will be on sim_params.start_session, and daily thereafter for each sid. Thus, two sids should result in two trades per day.
[ "creates", "trade_count", "trades", "for", "each", "sid", "in", "sids", "list", ".", "first", "trade", "will", "be", "on", "sim_params", ".", "start_session", "and", "daily", "thereafter", "for", "each", "sid", ".", "Thus", "two", "sids", "should", "result",...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/factory.py#L115-L131
train
quantopian/zipline
zipline/data/bundles/quandl.py
load_data_table
def load_data_table(file, index_col, show_progress=False): """ Load data table from zip file provided by Quandl. """ with ZipFile(file) as zip_file: file_names = zip_file.namelist() assert len(file_names) == 1, "Expected a single file from Quandl." ...
python
def load_data_table(file, index_col, show_progress=False): """ Load data table from zip file provided by Quandl. """ with ZipFile(file) as zip_file: file_names = zip_file.namelist() assert len(file_names) == 1, "Expected a single file from Quandl." ...
[ "def", "load_data_table", "(", "file", ",", "index_col", ",", "show_progress", "=", "False", ")", ":", "with", "ZipFile", "(", "file", ")", "as", "zip_file", ":", "file_names", "=", "zip_file", ".", "namelist", "(", ")", "assert", "len", "(", "file_names",...
Load data table from zip file provided by Quandl.
[ "Load", "data", "table", "from", "zip", "file", "provided", "by", "Quandl", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/bundles/quandl.py#L38-L75
train
quantopian/zipline
zipline/data/bundles/quandl.py
fetch_data_table
def fetch_data_table(api_key, show_progress, retries): """ Fetch WIKI Prices data table from Quandl """ for _ in range(retries): try: if show_progress: log.info('Downloading WIKI metadata.') metadata = pd.read_csv( ...
python
def fetch_data_table(api_key, show_progress, retries): """ Fetch WIKI Prices data table from Quandl """ for _ in range(retries): try: if show_progress: log.info('Downloading WIKI metadata.') metadata = pd.read_csv( ...
[ "def", "fetch_data_table", "(", "api_key", ",", "show_progress", ",", "retries", ")", ":", "for", "_", "in", "range", "(", "retries", ")", ":", "try", ":", "if", "show_progress", ":", "log", ".", "info", "(", "'Downloading WIKI metadata.'", ")", "metadata", ...
Fetch WIKI Prices data table from Quandl
[ "Fetch", "WIKI", "Prices", "data", "table", "from", "Quandl" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/bundles/quandl.py#L78-L114
train
quantopian/zipline
zipline/data/bundles/quandl.py
quandl_bundle
def quandl_bundle(environ, asset_db_writer, minute_bar_writer, daily_bar_writer, adjustment_writer, calendar, start_session, end_session, cache, show_progress...
python
def quandl_bundle(environ, asset_db_writer, minute_bar_writer, daily_bar_writer, adjustment_writer, calendar, start_session, end_session, cache, show_progress...
[ "def", "quandl_bundle", "(", "environ", ",", "asset_db_writer", ",", "minute_bar_writer", ",", "daily_bar_writer", ",", "adjustment_writer", ",", "calendar", ",", "start_session", ",", "end_session", ",", "cache", ",", "show_progress", ",", "output_dir", ")", ":", ...
quandl_bundle builds a daily dataset using Quandl's WIKI Prices dataset. For more information on Quandl's API and how to obtain an API key, please visit https://docs.quandl.com/docs#section-authentication
[ "quandl_bundle", "builds", "a", "daily", "dataset", "using", "Quandl", "s", "WIKI", "Prices", "dataset", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/bundles/quandl.py#L183-L250
train
quantopian/zipline
zipline/data/bundles/quandl.py
download_with_progress
def download_with_progress(url, chunk_size, **progress_kwargs): """ Download streaming data from a URL, printing progress information to the terminal. Parameters ---------- url : str A URL that can be understood by ``requests.get``. chunk_size : int Number of bytes to read a...
python
def download_with_progress(url, chunk_size, **progress_kwargs): """ Download streaming data from a URL, printing progress information to the terminal. Parameters ---------- url : str A URL that can be understood by ``requests.get``. chunk_size : int Number of bytes to read a...
[ "def", "download_with_progress", "(", "url", ",", "chunk_size", ",", "*", "*", "progress_kwargs", ")", ":", "resp", "=", "requests", ".", "get", "(", "url", ",", "stream", "=", "True", ")", "resp", ".", "raise_for_status", "(", ")", "total_size", "=", "i...
Download streaming data from a URL, printing progress information to the terminal. Parameters ---------- url : str A URL that can be understood by ``requests.get``. chunk_size : int Number of bytes to read at a time from requests. **progress_kwargs Forwarded to click.pro...
[ "Download", "streaming", "data", "from", "a", "URL", "printing", "progress", "information", "to", "the", "terminal", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/bundles/quandl.py#L253-L283
train
quantopian/zipline
zipline/data/bundles/quandl.py
download_without_progress
def download_without_progress(url): """ Download data from a URL, returning a BytesIO containing the loaded data. Parameters ---------- url : str A URL that can be understood by ``requests.get``. Returns ------- data : BytesIO A BytesIO containing the downloaded data. ...
python
def download_without_progress(url): """ Download data from a URL, returning a BytesIO containing the loaded data. Parameters ---------- url : str A URL that can be understood by ``requests.get``. Returns ------- data : BytesIO A BytesIO containing the downloaded data. ...
[ "def", "download_without_progress", "(", "url", ")", ":", "resp", "=", "requests", ".", "get", "(", "url", ")", "resp", ".", "raise_for_status", "(", ")", "return", "BytesIO", "(", "resp", ".", "content", ")" ]
Download data from a URL, returning a BytesIO containing the loaded data. Parameters ---------- url : str A URL that can be understood by ``requests.get``. Returns ------- data : BytesIO A BytesIO containing the downloaded data.
[ "Download", "data", "from", "a", "URL", "returning", "a", "BytesIO", "containing", "the", "loaded", "data", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/bundles/quandl.py#L286-L302
train
quantopian/zipline
zipline/data/resample.py
minute_frame_to_session_frame
def minute_frame_to_session_frame(minute_frame, calendar): """ Resample a DataFrame with minute data into the frame expected by a BcolzDailyBarWriter. Parameters ---------- minute_frame : pd.DataFrame A DataFrame with the columns `open`, `high`, `low`, `close`, `volume`, and `d...
python
def minute_frame_to_session_frame(minute_frame, calendar): """ Resample a DataFrame with minute data into the frame expected by a BcolzDailyBarWriter. Parameters ---------- minute_frame : pd.DataFrame A DataFrame with the columns `open`, `high`, `low`, `close`, `volume`, and `d...
[ "def", "minute_frame_to_session_frame", "(", "minute_frame", ",", "calendar", ")", ":", "how", "=", "OrderedDict", "(", "(", "c", ",", "_MINUTE_TO_SESSION_OHCLV_HOW", "[", "c", "]", ")", "for", "c", "in", "minute_frame", ".", "columns", ")", "labels", "=", "...
Resample a DataFrame with minute data into the frame expected by a BcolzDailyBarWriter. Parameters ---------- minute_frame : pd.DataFrame A DataFrame with the columns `open`, `high`, `low`, `close`, `volume`, and `dt` (minute dts) calendar : trading_calendars.trading_calendar.Tradin...
[ "Resample", "a", "DataFrame", "with", "minute", "data", "into", "the", "frame", "expected", "by", "a", "BcolzDailyBarWriter", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/resample.py#L42-L66
train
quantopian/zipline
zipline/data/resample.py
minute_to_session
def minute_to_session(column, close_locs, data, out): """ Resample an array with minute data into an array with session data. This function assumes that the minute data is the exact length of all minutes in the sessions in the output. Parameters ---------- column : str The `open`, ...
python
def minute_to_session(column, close_locs, data, out): """ Resample an array with minute data into an array with session data. This function assumes that the minute data is the exact length of all minutes in the sessions in the output. Parameters ---------- column : str The `open`, ...
[ "def", "minute_to_session", "(", "column", ",", "close_locs", ",", "data", ",", "out", ")", ":", "if", "column", "==", "'open'", ":", "_minute_to_session_open", "(", "close_locs", ",", "data", ",", "out", ")", "elif", "column", "==", "'high'", ":", "_minut...
Resample an array with minute data into an array with session data. This function assumes that the minute data is the exact length of all minutes in the sessions in the output. Parameters ---------- column : str The `open`, `high`, `low`, `close`, or `volume` column. close_locs : array...
[ "Resample", "an", "array", "with", "minute", "data", "into", "an", "array", "with", "session", "data", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/resample.py#L69-L100
train
quantopian/zipline
zipline/data/resample.py
DailyHistoryAggregator.opens
def opens(self, assets, dt): """ The open field's aggregation returns the first value that occurs for the day, if there has been no data on or before the `dt` the open is `nan`. Once the first non-nan open is seen, that value remains constant per asset for the remainder ...
python
def opens(self, assets, dt): """ The open field's aggregation returns the first value that occurs for the day, if there has been no data on or before the `dt` the open is `nan`. Once the first non-nan open is seen, that value remains constant per asset for the remainder ...
[ "def", "opens", "(", "self", ",", "assets", ",", "dt", ")", ":", "market_open", ",", "prev_dt", ",", "dt_value", ",", "entries", "=", "self", ".", "_prelude", "(", "dt", ",", "'open'", ")", "opens", "=", "[", "]", "session_label", "=", "self", ".", ...
The open field's aggregation returns the first value that occurs for the day, if there has been no data on or before the `dt` the open is `nan`. Once the first non-nan open is seen, that value remains constant per asset for the remainder of the day. Returns ------- ...
[ "The", "open", "field", "s", "aggregation", "returns", "the", "first", "value", "that", "occurs", "for", "the", "day", "if", "there", "has", "been", "no", "data", "on", "or", "before", "the", "dt", "the", "open", "is", "nan", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/resample.py#L167-L237
train
quantopian/zipline
zipline/data/resample.py
DailyHistoryAggregator.highs
def highs(self, assets, dt): """ The high field's aggregation returns the largest high seen between the market open and the current dt. If there has been no data on or before the `dt` the high is `nan`. Returns ------- np.array with dtype=float64, in order of ass...
python
def highs(self, assets, dt): """ The high field's aggregation returns the largest high seen between the market open and the current dt. If there has been no data on or before the `dt` the high is `nan`. Returns ------- np.array with dtype=float64, in order of ass...
[ "def", "highs", "(", "self", ",", "assets", ",", "dt", ")", ":", "market_open", ",", "prev_dt", ",", "dt_value", ",", "entries", "=", "self", ".", "_prelude", "(", "dt", ",", "'high'", ")", "highs", "=", "[", "]", "session_label", "=", "self", ".", ...
The high field's aggregation returns the largest high seen between the market open and the current dt. If there has been no data on or before the `dt` the high is `nan`. Returns ------- np.array with dtype=float64, in order of assets parameter.
[ "The", "high", "field", "s", "aggregation", "returns", "the", "largest", "high", "seen", "between", "the", "market", "open", "and", "the", "current", "dt", ".", "If", "there", "has", "been", "no", "data", "on", "or", "before", "the", "dt", "the", "high",...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/resample.py#L239-L306
train
quantopian/zipline
zipline/data/resample.py
DailyHistoryAggregator.lows
def lows(self, assets, dt): """ The low field's aggregation returns the smallest low seen between the market open and the current dt. If there has been no data on or before the `dt` the low is `nan`. Returns ------- np.array with dtype=float64, in order of assets...
python
def lows(self, assets, dt): """ The low field's aggregation returns the smallest low seen between the market open and the current dt. If there has been no data on or before the `dt` the low is `nan`. Returns ------- np.array with dtype=float64, in order of assets...
[ "def", "lows", "(", "self", ",", "assets", ",", "dt", ")", ":", "market_open", ",", "prev_dt", ",", "dt_value", ",", "entries", "=", "self", ".", "_prelude", "(", "dt", ",", "'low'", ")", "lows", "=", "[", "]", "session_label", "=", "self", ".", "_...
The low field's aggregation returns the smallest low seen between the market open and the current dt. If there has been no data on or before the `dt` the low is `nan`. Returns ------- np.array with dtype=float64, in order of assets parameter.
[ "The", "low", "field", "s", "aggregation", "returns", "the", "smallest", "low", "seen", "between", "the", "market", "open", "and", "the", "current", "dt", ".", "If", "there", "has", "been", "no", "data", "on", "or", "before", "the", "dt", "the", "low", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/resample.py#L308-L370
train
quantopian/zipline
zipline/data/resample.py
DailyHistoryAggregator.closes
def closes(self, assets, dt): """ The close field's aggregation returns the latest close at the given dt. If the close for the given dt is `nan`, the most recent non-nan `close` is used. If there has been no data on or before the `dt` the close is `nan`. Returns ...
python
def closes(self, assets, dt): """ The close field's aggregation returns the latest close at the given dt. If the close for the given dt is `nan`, the most recent non-nan `close` is used. If there has been no data on or before the `dt` the close is `nan`. Returns ...
[ "def", "closes", "(", "self", ",", "assets", ",", "dt", ")", ":", "market_open", ",", "prev_dt", ",", "dt_value", ",", "entries", "=", "self", ".", "_prelude", "(", "dt", ",", "'close'", ")", "closes", "=", "[", "]", "session_label", "=", "self", "."...
The close field's aggregation returns the latest close at the given dt. If the close for the given dt is `nan`, the most recent non-nan `close` is used. If there has been no data on or before the `dt` the close is `nan`. Returns ------- np.array with dtype=float6...
[ "The", "close", "field", "s", "aggregation", "returns", "the", "latest", "close", "at", "the", "given", "dt", ".", "If", "the", "close", "for", "the", "given", "dt", "is", "nan", "the", "most", "recent", "non", "-", "nan", "close", "is", "used", ".", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/resample.py#L372-L446
train
quantopian/zipline
zipline/data/resample.py
DailyHistoryAggregator.volumes
def volumes(self, assets, dt): """ The volume field's aggregation returns the sum of all volumes between the market open and the `dt` If there has been no data on or before the `dt` the volume is 0. Returns ------- np.array with dtype=int64, in order of assets pa...
python
def volumes(self, assets, dt): """ The volume field's aggregation returns the sum of all volumes between the market open and the `dt` If there has been no data on or before the `dt` the volume is 0. Returns ------- np.array with dtype=int64, in order of assets pa...
[ "def", "volumes", "(", "self", ",", "assets", ",", "dt", ")", ":", "market_open", ",", "prev_dt", ",", "dt_value", ",", "entries", "=", "self", ".", "_prelude", "(", "dt", ",", "'volume'", ")", "volumes", "=", "[", "]", "session_label", "=", "self", ...
The volume field's aggregation returns the sum of all volumes between the market open and the `dt` If there has been no data on or before the `dt` the volume is 0. Returns ------- np.array with dtype=int64, in order of assets parameter.
[ "The", "volume", "field", "s", "aggregation", "returns", "the", "sum", "of", "all", "volumes", "between", "the", "market", "open", "and", "the", "dt", "If", "there", "has", "been", "no", "data", "on", "or", "before", "the", "dt", "the", "volume", "is", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/resample.py#L448-L510
train