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/pipeline/domain.py
infer_domain
def infer_domain(terms): """ Infer the domain from a collection of terms. The algorithm for inferring domains is as follows: - If all input terms have a domain of GENERIC, the result is GENERIC. - If there is exactly one non-generic domain in the input terms, the result is that domain. ...
python
def infer_domain(terms): """ Infer the domain from a collection of terms. The algorithm for inferring domains is as follows: - If all input terms have a domain of GENERIC, the result is GENERIC. - If there is exactly one non-generic domain in the input terms, the result is that domain. ...
[ "def", "infer_domain", "(", "terms", ")", ":", "domains", "=", "{", "t", ".", "domain", "for", "t", "in", "terms", "}", "num_domains", "=", "len", "(", "domains", ")", "if", "num_domains", "==", "0", ":", "return", "GENERIC", "elif", "num_domains", "==...
Infer the domain from a collection of terms. The algorithm for inferring domains is as follows: - If all input terms have a domain of GENERIC, the result is GENERIC. - If there is exactly one non-generic domain in the input terms, the result is that domain. - Otherwise, an AmbiguousDomain erro...
[ "Infer", "the", "domain", "from", "a", "collection", "of", "terms", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/domain.py#L274-L314
train
quantopian/zipline
zipline/pipeline/domain.py
IDomain.roll_forward
def roll_forward(self, dt): """ Given a date, align it to the calendar of the pipeline's domain. Parameters ---------- dt : pd.Timestamp Returns ------- pd.Timestamp """ dt = pd.Timestamp(dt, tz='UTC') trading_days = self.all_ses...
python
def roll_forward(self, dt): """ Given a date, align it to the calendar of the pipeline's domain. Parameters ---------- dt : pd.Timestamp Returns ------- pd.Timestamp """ dt = pd.Timestamp(dt, tz='UTC') trading_days = self.all_ses...
[ "def", "roll_forward", "(", "self", ",", "dt", ")", ":", "dt", "=", "pd", ".", "Timestamp", "(", "dt", ",", "tz", "=", "'UTC'", ")", "trading_days", "=", "self", ".", "all_sessions", "(", ")", "try", ":", "return", "trading_days", "[", "trading_days", ...
Given a date, align it to the calendar of the pipeline's domain. Parameters ---------- dt : pd.Timestamp Returns ------- pd.Timestamp
[ "Given", "a", "date", "align", "it", "to", "the", "calendar", "of", "the", "pipeline", "s", "domain", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/domain.py#L77-L102
train
quantopian/zipline
zipline/data/hdf5_daily_bars.py
days_and_sids_for_frames
def days_and_sids_for_frames(frames): """ Returns the date index and sid columns shared by a list of dataframes, ensuring they all match. Parameters ---------- frames : list[pd.DataFrame] A list of dataframes indexed by day, with a column per sid. Returns ------- days : np....
python
def days_and_sids_for_frames(frames): """ Returns the date index and sid columns shared by a list of dataframes, ensuring they all match. Parameters ---------- frames : list[pd.DataFrame] A list of dataframes indexed by day, with a column per sid. Returns ------- days : np....
[ "def", "days_and_sids_for_frames", "(", "frames", ")", ":", "if", "not", "frames", ":", "days", "=", "np", ".", "array", "(", "[", "]", ",", "dtype", "=", "'datetime64[ns]'", ")", "sids", "=", "np", ".", "array", "(", "[", "]", ",", "dtype", "=", "...
Returns the date index and sid columns shared by a list of dataframes, ensuring they all match. Parameters ---------- frames : list[pd.DataFrame] A list of dataframes indexed by day, with a column per sid. Returns ------- days : np.array[datetime64[ns]] The days in these da...
[ "Returns", "the", "date", "index", "and", "sid", "columns", "shared", "by", "a", "list", "of", "dataframes", "ensuring", "they", "all", "match", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/hdf5_daily_bars.py#L154-L192
train
quantopian/zipline
zipline/data/hdf5_daily_bars.py
compute_asset_lifetimes
def compute_asset_lifetimes(frames): """ Parameters ---------- frames : dict[str, pd.DataFrame] A dict mapping each OHLCV field to a dataframe with a row for each date and a column for each sid, as passed to write(). Returns ------- start_date_ixs : np.array[int64] T...
python
def compute_asset_lifetimes(frames): """ Parameters ---------- frames : dict[str, pd.DataFrame] A dict mapping each OHLCV field to a dataframe with a row for each date and a column for each sid, as passed to write(). Returns ------- start_date_ixs : np.array[int64] T...
[ "def", "compute_asset_lifetimes", "(", "frames", ")", ":", "# Build a 2D array (dates x sids), where an entry is True if all", "# fields are nan for the given day and sid.", "is_null_matrix", "=", "np", ".", "logical_and", ".", "reduce", "(", "[", "frames", "[", "field", "]",...
Parameters ---------- frames : dict[str, pd.DataFrame] A dict mapping each OHLCV field to a dataframe with a row for each date and a column for each sid, as passed to write(). Returns ------- start_date_ixs : np.array[int64] The index of the first date with non-nan values, f...
[ "Parameters", "----------", "frames", ":", "dict", "[", "str", "pd", ".", "DataFrame", "]", "A", "dict", "mapping", "each", "OHLCV", "field", "to", "a", "dataframe", "with", "a", "row", "for", "each", "date", "and", "a", "column", "for", "each", "sid", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/hdf5_daily_bars.py#L360-L391
train
quantopian/zipline
zipline/data/hdf5_daily_bars.py
HDF5DailyBarWriter.write
def write(self, country_code, frames, scaling_factors=None): """Write the OHLCV data for one country to the HDF5 file. Parameters ---------- country_code : str The ISO 3166 alpha-2 country code for this country. frames : dict[str, pd.DataFrame] A dict map...
python
def write(self, country_code, frames, scaling_factors=None): """Write the OHLCV data for one country to the HDF5 file. Parameters ---------- country_code : str The ISO 3166 alpha-2 country code for this country. frames : dict[str, pd.DataFrame] A dict map...
[ "def", "write", "(", "self", ",", "country_code", ",", "frames", ",", "scaling_factors", "=", "None", ")", ":", "if", "scaling_factors", "is", "None", ":", "scaling_factors", "=", "DEFAULT_SCALING_FACTORS", "with", "self", ".", "h5_file", "(", "mode", "=", "...
Write the OHLCV data for one country to the HDF5 file. Parameters ---------- country_code : str The ISO 3166 alpha-2 country code for this country. frames : dict[str, pd.DataFrame] A dict mapping each OHLCV field to a dataframe with a row for each dat...
[ "Write", "the", "OHLCV", "data", "for", "one", "country", "to", "the", "HDF5", "file", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/hdf5_daily_bars.py#L220-L307
train
quantopian/zipline
zipline/data/hdf5_daily_bars.py
HDF5DailyBarWriter.write_from_sid_df_pairs
def write_from_sid_df_pairs(self, country_code, data, scaling_factors=None): """ Parameters ---------- country_code : str The ISO 3166 alpha-2 country code for this country. ...
python
def write_from_sid_df_pairs(self, country_code, data, scaling_factors=None): """ Parameters ---------- country_code : str The ISO 3166 alpha-2 country code for this country. ...
[ "def", "write_from_sid_df_pairs", "(", "self", ",", "country_code", ",", "data", ",", "scaling_factors", "=", "None", ")", ":", "data", "=", "list", "(", "data", ")", "if", "not", "data", ":", "empty_frame", "=", "pd", ".", "DataFrame", "(", "data", "=",...
Parameters ---------- country_code : str The ISO 3166 alpha-2 country code for this country. data : iterable[tuple[int, pandas.DataFrame]] The data chunks to write. Each chunk should be a tuple of sid and the data for that asset. scaling_factors : dict...
[ "Parameters", "----------", "country_code", ":", "str", "The", "ISO", "3166", "alpha", "-", "2", "country", "code", "for", "this", "country", ".", "data", ":", "iterable", "[", "tuple", "[", "int", "pandas", ".", "DataFrame", "]]", "The", "data", "chunks",...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/hdf5_daily_bars.py#L309-L357
train
quantopian/zipline
zipline/data/hdf5_daily_bars.py
HDF5DailyBarReader.from_file
def from_file(cls, h5_file, country_code): """ Construct from an h5py.File and a country code. Parameters ---------- h5_file : h5py.File An HDF5 daily pricing file. country_code : str The ISO 3166 alpha-2 country code for the country to read. ...
python
def from_file(cls, h5_file, country_code): """ Construct from an h5py.File and a country code. Parameters ---------- h5_file : h5py.File An HDF5 daily pricing file. country_code : str The ISO 3166 alpha-2 country code for the country to read. ...
[ "def", "from_file", "(", "cls", ",", "h5_file", ",", "country_code", ")", ":", "if", "h5_file", ".", "attrs", "[", "'version'", "]", "!=", "VERSION", ":", "raise", "ValueError", "(", "'mismatched version: file is of version %s, expected %s'", "%", "(", "h5_file", ...
Construct from an h5py.File and a country code. Parameters ---------- h5_file : h5py.File An HDF5 daily pricing file. country_code : str The ISO 3166 alpha-2 country code for the country to read.
[ "Construct", "from", "an", "h5py", ".", "File", "and", "a", "country", "code", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/hdf5_daily_bars.py#L424-L443
train
quantopian/zipline
zipline/data/hdf5_daily_bars.py
HDF5DailyBarReader.from_path
def from_path(cls, path, country_code): """ Construct from a file path and a country code. Parameters ---------- path : str The path to an HDF5 daily pricing file. country_code : str The ISO 3166 alpha-2 country code for the country to read. ...
python
def from_path(cls, path, country_code): """ Construct from a file path and a country code. Parameters ---------- path : str The path to an HDF5 daily pricing file. country_code : str The ISO 3166 alpha-2 country code for the country to read. ...
[ "def", "from_path", "(", "cls", ",", "path", ",", "country_code", ")", ":", "return", "cls", ".", "from_file", "(", "h5py", ".", "File", "(", "path", ")", ",", "country_code", ")" ]
Construct from a file path and a country code. Parameters ---------- path : str The path to an HDF5 daily pricing file. country_code : str The ISO 3166 alpha-2 country code for the country to read.
[ "Construct", "from", "a", "file", "path", "and", "a", "country", "code", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/hdf5_daily_bars.py#L446-L457
train
quantopian/zipline
zipline/data/hdf5_daily_bars.py
HDF5DailyBarReader.load_raw_arrays
def load_raw_arrays(self, columns, start_date, end_date, assets): """ Parameters ---------- columns : list of str 'open', 'high', 'low', 'close', or 'volume' start_date: Tim...
python
def load_raw_arrays(self, columns, start_date, end_date, assets): """ Parameters ---------- columns : list of str 'open', 'high', 'low', 'close', or 'volume' start_date: Tim...
[ "def", "load_raw_arrays", "(", "self", ",", "columns", ",", "start_date", ",", "end_date", ",", "assets", ")", ":", "self", ".", "_validate_timestamp", "(", "start_date", ")", "self", ".", "_validate_timestamp", "(", "end_date", ")", "start", "=", "start_date"...
Parameters ---------- columns : list of str 'open', 'high', 'low', 'close', or 'volume' start_date: Timestamp Beginning of the window range. end_date: Timestamp End of the window range. assets : list of int The asset identifiers in the ...
[ "Parameters", "----------", "columns", ":", "list", "of", "str", "open", "high", "low", "close", "or", "volume", "start_date", ":", "Timestamp", "Beginning", "of", "the", "window", "range", ".", "end_date", ":", "Timestamp", "End", "of", "the", "window", "ra...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/hdf5_daily_bars.py#L462-L528
train
quantopian/zipline
zipline/data/hdf5_daily_bars.py
HDF5DailyBarReader._make_sid_selector
def _make_sid_selector(self, assets): """ Build an indexer mapping ``self.sids`` to ``assets``. Parameters ---------- assets : list[int] List of assets requested by a caller of ``load_raw_arrays``. Returns ------- index : np.array[int64] ...
python
def _make_sid_selector(self, assets): """ Build an indexer mapping ``self.sids`` to ``assets``. Parameters ---------- assets : list[int] List of assets requested by a caller of ``load_raw_arrays``. Returns ------- index : np.array[int64] ...
[ "def", "_make_sid_selector", "(", "self", ",", "assets", ")", ":", "assets", "=", "np", ".", "array", "(", "assets", ")", "sid_selector", "=", "self", ".", "sids", ".", "searchsorted", "(", "assets", ")", "unknown", "=", "np", ".", "in1d", "(", "assets...
Build an indexer mapping ``self.sids`` to ``assets``. Parameters ---------- assets : list[int] List of assets requested by a caller of ``load_raw_arrays``. Returns ------- index : np.array[int64] Index array containing the index in ``self.sids`` ...
[ "Build", "an", "indexer", "mapping", "self", ".", "sids", "to", "assets", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/hdf5_daily_bars.py#L530-L551
train
quantopian/zipline
zipline/data/hdf5_daily_bars.py
HDF5DailyBarReader._validate_assets
def _validate_assets(self, assets): """Validate that asset identifiers are contained in the daily bars. Parameters ---------- assets : array-like[int] The asset identifiers to validate. Raises ------ NoDataForSid If one or more of the prov...
python
def _validate_assets(self, assets): """Validate that asset identifiers are contained in the daily bars. Parameters ---------- assets : array-like[int] The asset identifiers to validate. Raises ------ NoDataForSid If one or more of the prov...
[ "def", "_validate_assets", "(", "self", ",", "assets", ")", ":", "missing_sids", "=", "np", ".", "setdiff1d", "(", "assets", ",", "self", ".", "sids", ")", "if", "len", "(", "missing_sids", ")", ":", "raise", "NoDataForSid", "(", "'Assets not contained in da...
Validate that asset identifiers are contained in the daily bars. Parameters ---------- assets : array-like[int] The asset identifiers to validate. Raises ------ NoDataForSid If one or more of the provided asset identifiers are not cont...
[ "Validate", "that", "asset", "identifiers", "are", "contained", "in", "the", "daily", "bars", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/hdf5_daily_bars.py#L562-L583
train
quantopian/zipline
zipline/data/hdf5_daily_bars.py
HDF5DailyBarReader.get_value
def get_value(self, sid, dt, field): """ Retrieve the value at the given coordinates. Parameters ---------- sid : int The asset identifier. dt : pd.Timestamp The timestamp for the desired data point. field : string The OHLVC na...
python
def get_value(self, sid, dt, field): """ Retrieve the value at the given coordinates. Parameters ---------- sid : int The asset identifier. dt : pd.Timestamp The timestamp for the desired data point. field : string The OHLVC na...
[ "def", "get_value", "(", "self", ",", "sid", ",", "dt", ",", "field", ")", ":", "self", ".", "_validate_assets", "(", "[", "sid", "]", ")", "self", ".", "_validate_timestamp", "(", "dt", ")", "sid_ix", "=", "self", ".", "sids", ".", "searchsorted", "...
Retrieve the value at the given coordinates. Parameters ---------- sid : int The asset identifier. dt : pd.Timestamp The timestamp for the desired data point. field : string The OHLVC name for the desired data point. Returns -...
[ "Retrieve", "the", "value", "at", "the", "given", "coordinates", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/hdf5_daily_bars.py#L647-L693
train
quantopian/zipline
zipline/data/hdf5_daily_bars.py
HDF5DailyBarReader.get_last_traded_dt
def get_last_traded_dt(self, asset, dt): """ Get the latest day on or before ``dt`` in which ``asset`` traded. If there are no trades on or before ``dt``, returns ``pd.NaT``. Parameters ---------- asset : zipline.asset.Asset The asset for which to get the la...
python
def get_last_traded_dt(self, asset, dt): """ Get the latest day on or before ``dt`` in which ``asset`` traded. If there are no trades on or before ``dt``, returns ``pd.NaT``. Parameters ---------- asset : zipline.asset.Asset The asset for which to get the la...
[ "def", "get_last_traded_dt", "(", "self", ",", "asset", ",", "dt", ")", ":", "sid_ix", "=", "self", ".", "sids", ".", "searchsorted", "(", "asset", ".", "sid", ")", "# Used to get a slice of all dates up to and including ``dt``.", "dt_limit_ix", "=", "self", ".", ...
Get the latest day on or before ``dt`` in which ``asset`` traded. If there are no trades on or before ``dt``, returns ``pd.NaT``. Parameters ---------- asset : zipline.asset.Asset The asset for which to get the last traded day. dt : pd.Timestamp The dt a...
[ "Get", "the", "latest", "day", "on", "or", "before", "dt", "in", "which", "asset", "traded", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/hdf5_daily_bars.py#L695-L726
train
quantopian/zipline
zipline/data/hdf5_daily_bars.py
MultiCountryDailyBarReader.from_file
def from_file(cls, h5_file): """ Construct from an h5py.File. Parameters ---------- h5_file : h5py.File An HDF5 daily pricing file. """ return cls({ country: HDF5DailyBarReader.from_file(h5_file, country) for country in h5_file...
python
def from_file(cls, h5_file): """ Construct from an h5py.File. Parameters ---------- h5_file : h5py.File An HDF5 daily pricing file. """ return cls({ country: HDF5DailyBarReader.from_file(h5_file, country) for country in h5_file...
[ "def", "from_file", "(", "cls", ",", "h5_file", ")", ":", "return", "cls", "(", "{", "country", ":", "HDF5DailyBarReader", ".", "from_file", "(", "h5_file", ",", "country", ")", "for", "country", "in", "h5_file", ".", "keys", "(", ")", "}", ")" ]
Construct from an h5py.File. Parameters ---------- h5_file : h5py.File An HDF5 daily pricing file.
[ "Construct", "from", "an", "h5py", ".", "File", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/hdf5_daily_bars.py#L745-L757
train
quantopian/zipline
zipline/data/hdf5_daily_bars.py
MultiCountryDailyBarReader.load_raw_arrays
def load_raw_arrays(self, columns, start_date, end_date, assets): """ Parameters ---------- columns : list of str 'open', 'high', 'low', 'close', or 'volume' start_date: Tim...
python
def load_raw_arrays(self, columns, start_date, end_date, assets): """ Parameters ---------- columns : list of str 'open', 'high', 'low', 'close', or 'volume' start_date: Tim...
[ "def", "load_raw_arrays", "(", "self", ",", "columns", ",", "start_date", ",", "end_date", ",", "assets", ")", ":", "country_code", "=", "self", ".", "_country_code_for_assets", "(", "assets", ")", "return", "self", ".", "_readers", "[", "country_code", "]", ...
Parameters ---------- columns : list of str 'open', 'high', 'low', 'close', or 'volume' start_date: Timestamp Beginning of the window range. end_date: Timestamp End of the window range. assets : list of int The asset identifiers in the ...
[ "Parameters", "----------", "columns", ":", "list", "of", "str", "open", "high", "low", "close", "or", "volume", "start_date", ":", "Timestamp", "Beginning", "of", "the", "window", "range", ".", "end_date", ":", "Timestamp", "End", "of", "the", "window", "ra...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/hdf5_daily_bars.py#L800-L831
train
quantopian/zipline
zipline/data/hdf5_daily_bars.py
MultiCountryDailyBarReader.sessions
def sessions(self): """ Returns ------- sessions : DatetimeIndex All session labels (unioning the range for all assets) which the reader can provide. """ return pd.to_datetime( reduce( np.union1d, (reader.d...
python
def sessions(self): """ Returns ------- sessions : DatetimeIndex All session labels (unioning the range for all assets) which the reader can provide. """ return pd.to_datetime( reduce( np.union1d, (reader.d...
[ "def", "sessions", "(", "self", ")", ":", "return", "pd", ".", "to_datetime", "(", "reduce", "(", "np", ".", "union1d", ",", "(", "reader", ".", "dates", "for", "reader", "in", "self", ".", "_readers", ".", "values", "(", ")", ")", ",", ")", ",", ...
Returns ------- sessions : DatetimeIndex All session labels (unioning the range for all assets) which the reader can provide.
[ "Returns", "-------", "sessions", ":", "DatetimeIndex", "All", "session", "labels", "(", "unioning", "the", "range", "for", "all", "assets", ")", "which", "the", "reader", "can", "provide", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/hdf5_daily_bars.py#L869-L883
train
quantopian/zipline
zipline/data/hdf5_daily_bars.py
MultiCountryDailyBarReader.get_value
def get_value(self, sid, dt, field): """ Retrieve the value at the given coordinates. Parameters ---------- sid : int The asset identifier. dt : pd.Timestamp The timestamp for the desired data point. field : string The OHLVC na...
python
def get_value(self, sid, dt, field): """ Retrieve the value at the given coordinates. Parameters ---------- sid : int The asset identifier. dt : pd.Timestamp The timestamp for the desired data point. field : string The OHLVC na...
[ "def", "get_value", "(", "self", ",", "sid", ",", "dt", ",", "field", ")", ":", "try", ":", "country_code", "=", "self", ".", "_country_code_for_assets", "(", "[", "sid", "]", ")", "except", "ValueError", "as", "exc", ":", "raise_from", "(", "NoDataForSi...
Retrieve the value at the given coordinates. Parameters ---------- sid : int The asset identifier. dt : pd.Timestamp The timestamp for the desired data point. field : string The OHLVC name for the desired data point. Returns -...
[ "Retrieve", "the", "value", "at", "the", "given", "coordinates", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/hdf5_daily_bars.py#L885-L921
train
quantopian/zipline
zipline/data/hdf5_daily_bars.py
MultiCountryDailyBarReader.get_last_traded_dt
def get_last_traded_dt(self, asset, dt): """ Get the latest day on or before ``dt`` in which ``asset`` traded. If there are no trades on or before ``dt``, returns ``pd.NaT``. Parameters ---------- asset : zipline.asset.Asset The asset for which to get the la...
python
def get_last_traded_dt(self, asset, dt): """ Get the latest day on or before ``dt`` in which ``asset`` traded. If there are no trades on or before ``dt``, returns ``pd.NaT``. Parameters ---------- asset : zipline.asset.Asset The asset for which to get the la...
[ "def", "get_last_traded_dt", "(", "self", ",", "asset", ",", "dt", ")", ":", "country_code", "=", "self", ".", "_country_code_for_assets", "(", "[", "asset", ".", "sid", "]", ")", "return", "self", ".", "_readers", "[", "country_code", "]", ".", "get_last_...
Get the latest day on or before ``dt`` in which ``asset`` traded. If there are no trades on or before ``dt``, returns ``pd.NaT``. Parameters ---------- asset : zipline.asset.Asset The asset for which to get the last traded day. dt : pd.Timestamp The dt a...
[ "Get", "the", "latest", "day", "on", "or", "before", "dt", "in", "which", "asset", "traded", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/hdf5_daily_bars.py#L923-L943
train
quantopian/zipline
zipline/assets/asset_writer.py
_normalize_index_columns_in_place
def _normalize_index_columns_in_place(equities, equity_supplementary_mappings, futures, exchanges, root_symbols): """ Update dataframes in place to set indentif...
python
def _normalize_index_columns_in_place(equities, equity_supplementary_mappings, futures, exchanges, root_symbols): """ Update dataframes in place to set indentif...
[ "def", "_normalize_index_columns_in_place", "(", "equities", ",", "equity_supplementary_mappings", ",", "futures", ",", "exchanges", ",", "root_symbols", ")", ":", "for", "frame", ",", "column_name", "in", "(", "(", "equities", ",", "'sid'", ")", ",", "(", "equi...
Update dataframes in place to set indentifier columns as indices. For each input frame, if the frame has a column with the same name as its associated index column, set that column as the index. Otherwise, assume the index already contains identifiers. If frames are passed as None, they're ignored.
[ "Update", "dataframes", "in", "place", "to", "set", "indentifier", "columns", "as", "indices", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/asset_writer.py#L74-L95
train
quantopian/zipline
zipline/assets/asset_writer.py
split_delimited_symbol
def split_delimited_symbol(symbol): """ Takes in a symbol that may be delimited and splits it in to a company symbol and share class symbol. Also returns the fuzzy symbol, which is the symbol without any fuzzy characters at all. Parameters ---------- symbol : str The possibly-delimi...
python
def split_delimited_symbol(symbol): """ Takes in a symbol that may be delimited and splits it in to a company symbol and share class symbol. Also returns the fuzzy symbol, which is the symbol without any fuzzy characters at all. Parameters ---------- symbol : str The possibly-delimi...
[ "def", "split_delimited_symbol", "(", "symbol", ")", ":", "# return blank strings for any bad fuzzy symbols, like NaN or None", "if", "symbol", "in", "_delimited_symbol_default_triggers", ":", "return", "''", ",", "''", "symbol", "=", "symbol", ".", "upper", "(", ")", "...
Takes in a symbol that may be delimited and splits it in to a company symbol and share class symbol. Also returns the fuzzy symbol, which is the symbol without any fuzzy characters at all. Parameters ---------- symbol : str The possibly-delimited symbol to be split Returns ------- ...
[ "Takes", "in", "a", "symbol", "that", "may", "be", "delimited", "and", "splits", "it", "in", "to", "a", "company", "symbol", "and", "share", "class", "symbol", ".", "Also", "returns", "the", "fuzzy", "symbol", "which", "is", "the", "symbol", "without", "...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/asset_writer.py#L175-L213
train
quantopian/zipline
zipline/assets/asset_writer.py
_generate_output_dataframe
def _generate_output_dataframe(data_subset, defaults): """ Generates an output dataframe from the given subset of user-provided data, the given column names, and the given default values. Parameters ---------- data_subset : DataFrame A DataFrame, usually from an AssetData object, ...
python
def _generate_output_dataframe(data_subset, defaults): """ Generates an output dataframe from the given subset of user-provided data, the given column names, and the given default values. Parameters ---------- data_subset : DataFrame A DataFrame, usually from an AssetData object, ...
[ "def", "_generate_output_dataframe", "(", "data_subset", ",", "defaults", ")", ":", "# The columns provided.", "cols", "=", "set", "(", "data_subset", ".", "columns", ")", "desired_cols", "=", "set", "(", "defaults", ")", "# Drop columns with unrecognised headers.", "...
Generates an output dataframe from the given subset of user-provided data, the given column names, and the given default values. Parameters ---------- data_subset : DataFrame A DataFrame, usually from an AssetData object, that contains the user's input metadata for the asset type being ...
[ "Generates", "an", "output", "dataframe", "from", "the", "given", "subset", "of", "user", "-", "provided", "data", "the", "given", "column", "names", "and", "the", "given", "default", "values", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/asset_writer.py#L216-L254
train
quantopian/zipline
zipline/assets/asset_writer.py
_check_symbol_mappings
def _check_symbol_mappings(df, exchanges, asset_exchange): """Check that there are no cases where multiple symbols resolve to the same asset at the same time in the same country. Parameters ---------- df : pd.DataFrame The equity symbol mappings table. exchanges : pd.DataFrame T...
python
def _check_symbol_mappings(df, exchanges, asset_exchange): """Check that there are no cases where multiple symbols resolve to the same asset at the same time in the same country. Parameters ---------- df : pd.DataFrame The equity symbol mappings table. exchanges : pd.DataFrame T...
[ "def", "_check_symbol_mappings", "(", "df", ",", "exchanges", ",", "asset_exchange", ")", ":", "mappings", "=", "df", ".", "set_index", "(", "'sid'", ")", "[", "list", "(", "mapping_columns", ")", "]", ".", "copy", "(", ")", "mappings", "[", "'country_code...
Check that there are no cases where multiple symbols resolve to the same asset at the same time in the same country. Parameters ---------- df : pd.DataFrame The equity symbol mappings table. exchanges : pd.DataFrame The exchanges table. asset_exchange : pd.Series A serie...
[ "Check", "that", "there", "are", "no", "cases", "where", "multiple", "symbols", "resolve", "to", "the", "same", "asset", "at", "the", "same", "time", "in", "the", "same", "country", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/asset_writer.py#L272-L332
train
quantopian/zipline
zipline/assets/asset_writer.py
_split_symbol_mappings
def _split_symbol_mappings(df, exchanges): """Split out the symbol: sid mappings from the raw data. Parameters ---------- df : pd.DataFrame The dataframe with multiple rows for each symbol: sid pair. exchanges : pd.DataFrame The exchanges table. Returns ------- asset_in...
python
def _split_symbol_mappings(df, exchanges): """Split out the symbol: sid mappings from the raw data. Parameters ---------- df : pd.DataFrame The dataframe with multiple rows for each symbol: sid pair. exchanges : pd.DataFrame The exchanges table. Returns ------- asset_in...
[ "def", "_split_symbol_mappings", "(", "df", ",", "exchanges", ")", ":", "mappings", "=", "df", "[", "list", "(", "mapping_columns", ")", "]", "with", "pd", ".", "option_context", "(", "'mode.chained_assignment'", ",", "None", ")", ":", "mappings", "[", "'sid...
Split out the symbol: sid mappings from the raw data. Parameters ---------- df : pd.DataFrame The dataframe with multiple rows for each symbol: sid pair. exchanges : pd.DataFrame The exchanges table. Returns ------- asset_info : pd.DataFrame The asset info with one ...
[ "Split", "out", "the", "symbol", ":", "sid", "mappings", "from", "the", "raw", "data", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/asset_writer.py#L335-L368
train
quantopian/zipline
zipline/assets/asset_writer.py
_dt_to_epoch_ns
def _dt_to_epoch_ns(dt_series): """Convert a timeseries into an Int64Index of nanoseconds since the epoch. Parameters ---------- dt_series : pd.Series The timeseries to convert. Returns ------- idx : pd.Int64Index The index converted to nanoseconds since the epoch. """ ...
python
def _dt_to_epoch_ns(dt_series): """Convert a timeseries into an Int64Index of nanoseconds since the epoch. Parameters ---------- dt_series : pd.Series The timeseries to convert. Returns ------- idx : pd.Int64Index The index converted to nanoseconds since the epoch. """ ...
[ "def", "_dt_to_epoch_ns", "(", "dt_series", ")", ":", "index", "=", "pd", ".", "to_datetime", "(", "dt_series", ".", "values", ")", "if", "index", ".", "tzinfo", "is", "None", ":", "index", "=", "index", ".", "tz_localize", "(", "'UTC'", ")", "else", "...
Convert a timeseries into an Int64Index of nanoseconds since the epoch. Parameters ---------- dt_series : pd.Series The timeseries to convert. Returns ------- idx : pd.Int64Index The index converted to nanoseconds since the epoch.
[ "Convert", "a", "timeseries", "into", "an", "Int64Index", "of", "nanoseconds", "since", "the", "epoch", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/asset_writer.py#L371-L389
train
quantopian/zipline
zipline/assets/asset_writer.py
check_version_info
def check_version_info(conn, version_table, expected_version): """ Checks for a version value in the version table. Parameters ---------- conn : sa.Connection The connection to use to perform the check. version_table : sa.Table The version table of the asset database expecte...
python
def check_version_info(conn, version_table, expected_version): """ Checks for a version value in the version table. Parameters ---------- conn : sa.Connection The connection to use to perform the check. version_table : sa.Table The version table of the asset database expecte...
[ "def", "check_version_info", "(", "conn", ",", "version_table", ",", "expected_version", ")", ":", "# Read the version out of the table", "version_from_table", "=", "conn", ".", "execute", "(", "sa", ".", "select", "(", "(", "version_table", ".", "c", ".", "versio...
Checks for a version value in the version table. Parameters ---------- conn : sa.Connection The connection to use to perform the check. version_table : sa.Table The version table of the asset database expected_version : int The expected version of the asset database Rai...
[ "Checks", "for", "a", "version", "value", "in", "the", "version", "table", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/asset_writer.py#L392-L423
train
quantopian/zipline
zipline/assets/asset_writer.py
write_version_info
def write_version_info(conn, version_table, version_value): """ Inserts the version value in to the version table. Parameters ---------- conn : sa.Connection The connection to use to execute the insert. version_table : sa.Table The version table of the asset database version...
python
def write_version_info(conn, version_table, version_value): """ Inserts the version value in to the version table. Parameters ---------- conn : sa.Connection The connection to use to execute the insert. version_table : sa.Table The version table of the asset database version...
[ "def", "write_version_info", "(", "conn", ",", "version_table", ",", "version_value", ")", ":", "conn", ".", "execute", "(", "sa", ".", "insert", "(", "version_table", ",", "values", "=", "{", "'version'", ":", "version_value", "}", ")", ")" ]
Inserts the version value in to the version table. Parameters ---------- conn : sa.Connection The connection to use to execute the insert. version_table : sa.Table The version table of the asset database version_value : int The version to write in to the database
[ "Inserts", "the", "version", "value", "in", "to", "the", "version", "table", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/asset_writer.py#L426-L440
train
quantopian/zipline
zipline/assets/asset_writer.py
AssetDBWriter.write_direct
def write_direct(self, equities=None, equity_symbol_mappings=None, equity_supplementary_mappings=None, futures=None, exchanges=None, root_symbols=None, chunk_size=DEFAULT_CH...
python
def write_direct(self, equities=None, equity_symbol_mappings=None, equity_supplementary_mappings=None, futures=None, exchanges=None, root_symbols=None, chunk_size=DEFAULT_CH...
[ "def", "write_direct", "(", "self", ",", "equities", "=", "None", ",", "equity_symbol_mappings", "=", "None", ",", "equity_supplementary_mappings", "=", "None", ",", "futures", "=", "None", ",", "exchanges", "=", "None", ",", "root_symbols", "=", "None", ",", ...
Write asset metadata to a sqlite database in the format that it is stored in the assets db. Parameters ---------- equities : pd.DataFrame, optional The equity metadata. The columns for this dataframe are: symbol : str The ticker symbol for th...
[ "Write", "asset", "metadata", "to", "a", "sqlite", "database", "in", "the", "format", "that", "it", "is", "stored", "in", "the", "assets", "db", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/asset_writer.py#L514-L668
train
quantopian/zipline
zipline/assets/asset_writer.py
AssetDBWriter.write
def write(self, equities=None, futures=None, exchanges=None, root_symbols=None, equity_supplementary_mappings=None, chunk_size=DEFAULT_CHUNK_SIZE): """Write asset metadata to a sqlite database. Parameters ------...
python
def write(self, equities=None, futures=None, exchanges=None, root_symbols=None, equity_supplementary_mappings=None, chunk_size=DEFAULT_CHUNK_SIZE): """Write asset metadata to a sqlite database. Parameters ------...
[ "def", "write", "(", "self", ",", "equities", "=", "None", ",", "futures", "=", "None", ",", "exchanges", "=", "None", ",", "root_symbols", "=", "None", ",", "equity_supplementary_mappings", "=", "None", ",", "chunk_size", "=", "DEFAULT_CHUNK_SIZE", ")", ":"...
Write asset metadata to a sqlite database. Parameters ---------- equities : pd.DataFrame, optional The equity metadata. The columns for this dataframe are: symbol : str The ticker symbol for this equity. asset_name : str ...
[ "Write", "asset", "metadata", "to", "a", "sqlite", "database", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/asset_writer.py#L670-L797
train
quantopian/zipline
zipline/assets/asset_writer.py
AssetDBWriter._all_tables_present
def _all_tables_present(self, txn): """ Checks if any tables are present in the current assets database. Parameters ---------- txn : Transaction The open transaction to check in. Returns ------- has_tables : bool True if any table...
python
def _all_tables_present(self, txn): """ Checks if any tables are present in the current assets database. Parameters ---------- txn : Transaction The open transaction to check in. Returns ------- has_tables : bool True if any table...
[ "def", "_all_tables_present", "(", "self", ",", "txn", ")", ":", "conn", "=", "txn", ".", "connect", "(", ")", "for", "table_name", "in", "asset_db_table_names", ":", "if", "txn", ".", "dialect", ".", "has_table", "(", "conn", ",", "table_name", ")", ":"...
Checks if any tables are present in the current assets database. Parameters ---------- txn : Transaction The open transaction to check in. Returns ------- has_tables : bool True if any tables are present, otherwise False.
[ "Checks", "if", "any", "tables", "are", "present", "in", "the", "current", "assets", "database", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/asset_writer.py#L856-L874
train
quantopian/zipline
zipline/assets/asset_writer.py
AssetDBWriter.init_db
def init_db(self, txn=None): """Connect to database and create tables. Parameters ---------- txn : sa.engine.Connection, optional The transaction to execute in. If this is not provided, a new transaction will be started with the engine provided. Returns ...
python
def init_db(self, txn=None): """Connect to database and create tables. Parameters ---------- txn : sa.engine.Connection, optional The transaction to execute in. If this is not provided, a new transaction will be started with the engine provided. Returns ...
[ "def", "init_db", "(", "self", ",", "txn", "=", "None", ")", ":", "with", "ExitStack", "(", ")", "as", "stack", ":", "if", "txn", "is", "None", ":", "txn", "=", "stack", ".", "enter_context", "(", "self", ".", "engine", ".", "begin", "(", ")", ")...
Connect to database and create tables. Parameters ---------- txn : sa.engine.Connection, optional The transaction to execute in. If this is not provided, a new transaction will be started with the engine provided. Returns ------- metadata : sa.Me...
[ "Connect", "to", "database", "and", "create", "tables", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/asset_writer.py#L876-L902
train
quantopian/zipline
zipline/assets/asset_writer.py
AssetDBWriter._load_data
def _load_data(self, equities, futures, exchanges, root_symbols, equity_supplementary_mappings): """ Returns a standard set of pandas.DataFrames: equities, futures, exchanges, root_symbols """ ...
python
def _load_data(self, equities, futures, exchanges, root_symbols, equity_supplementary_mappings): """ Returns a standard set of pandas.DataFrames: equities, futures, exchanges, root_symbols """ ...
[ "def", "_load_data", "(", "self", ",", "equities", ",", "futures", ",", "exchanges", ",", "root_symbols", ",", "equity_supplementary_mappings", ")", ":", "# Set named identifier columns as indices, if provided.", "_normalize_index_columns_in_place", "(", "equities", "=", "e...
Returns a standard set of pandas.DataFrames: equities, futures, exchanges, root_symbols
[ "Returns", "a", "standard", "set", "of", "pandas", ".", "DataFrames", ":", "equities", "futures", "exchanges", "root_symbols" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/asset_writer.py#L970-L1019
train
quantopian/zipline
zipline/pipeline/loaders/blaze/utils.py
load_raw_data
def load_raw_data(assets, data_query_cutoff_times, expr, odo_kwargs, checkpoints=None): """ Given an expression representing data to load, perform normalization and forward-filling and return the data, materialized. Only accepts data wi...
python
def load_raw_data(assets, data_query_cutoff_times, expr, odo_kwargs, checkpoints=None): """ Given an expression representing data to load, perform normalization and forward-filling and return the data, materialized. Only accepts data wi...
[ "def", "load_raw_data", "(", "assets", ",", "data_query_cutoff_times", ",", "expr", ",", "odo_kwargs", ",", "checkpoints", "=", "None", ")", ":", "lower_dt", ",", "upper_dt", "=", "data_query_cutoff_times", "[", "[", "0", ",", "-", "1", "]", "]", "raw", "=...
Given an expression representing data to load, perform normalization and forward-filling and return the data, materialized. Only accepts data with a `sid` field. Parameters ---------- assets : pd.int64index the assets to load data for. data_query_cutoff_times : pd.DatetimeIndex ...
[ "Given", "an", "expression", "representing", "data", "to", "load", "perform", "normalization", "and", "forward", "-", "filling", "and", "return", "the", "data", "materialized", ".", "Only", "accepts", "data", "with", "a", "sid", "field", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/blaze/utils.py#L5-L48
train
quantopian/zipline
zipline/utils/range.py
from_tuple
def from_tuple(tup): """Convert a tuple into a range with error handling. Parameters ---------- tup : tuple (len 2 or 3) The tuple to turn into a range. Returns ------- range : range The range from the tuple. Raises ------ ValueError Raised when the tup...
python
def from_tuple(tup): """Convert a tuple into a range with error handling. Parameters ---------- tup : tuple (len 2 or 3) The tuple to turn into a range. Returns ------- range : range The range from the tuple. Raises ------ ValueError Raised when the tup...
[ "def", "from_tuple", "(", "tup", ")", ":", "if", "len", "(", "tup", ")", "not", "in", "(", "2", ",", "3", ")", ":", "raise", "ValueError", "(", "'tuple must contain 2 or 3 elements, not: %d (%r'", "%", "(", "len", "(", "tup", ")", ",", "tup", ",", ")",...
Convert a tuple into a range with error handling. Parameters ---------- tup : tuple (len 2 or 3) The tuple to turn into a range. Returns ------- range : range The range from the tuple. Raises ------ ValueError Raised when the tuple length is not 2 or 3.
[ "Convert", "a", "tuple", "into", "a", "range", "with", "error", "handling", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/range.py#L151-L176
train
quantopian/zipline
zipline/utils/range.py
maybe_from_tuple
def maybe_from_tuple(tup_or_range): """Convert a tuple into a range but pass ranges through silently. This is useful to ensure that input is a range so that attributes may be accessed with `.start`, `.stop` or so that containment checks are constant time. Parameters ---------- tup_or_range...
python
def maybe_from_tuple(tup_or_range): """Convert a tuple into a range but pass ranges through silently. This is useful to ensure that input is a range so that attributes may be accessed with `.start`, `.stop` or so that containment checks are constant time. Parameters ---------- tup_or_range...
[ "def", "maybe_from_tuple", "(", "tup_or_range", ")", ":", "if", "isinstance", "(", "tup_or_range", ",", "tuple", ")", ":", "return", "from_tuple", "(", "tup_or_range", ")", "elif", "isinstance", "(", "tup_or_range", ",", "range", ")", ":", "return", "tup_or_ra...
Convert a tuple into a range but pass ranges through silently. This is useful to ensure that input is a range so that attributes may be accessed with `.start`, `.stop` or so that containment checks are constant time. Parameters ---------- tup_or_range : tuple or range A tuple to pass t...
[ "Convert", "a", "tuple", "into", "a", "range", "but", "pass", "ranges", "through", "silently", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/range.py#L179-L212
train
quantopian/zipline
zipline/utils/range.py
_check_steps
def _check_steps(a, b): """Check that the steps of ``a`` and ``b`` are both 1. Parameters ---------- a : range The first range to check. b : range The second range to check. Raises ------ ValueError Raised when either step is not 1. """ if a.step != 1: ...
python
def _check_steps(a, b): """Check that the steps of ``a`` and ``b`` are both 1. Parameters ---------- a : range The first range to check. b : range The second range to check. Raises ------ ValueError Raised when either step is not 1. """ if a.step != 1: ...
[ "def", "_check_steps", "(", "a", ",", "b", ")", ":", "if", "a", ".", "step", "!=", "1", ":", "raise", "ValueError", "(", "'a.step must be equal to 1, got: %s'", "%", "a", ".", "step", ")", "if", "b", ".", "step", "!=", "1", ":", "raise", "ValueError", ...
Check that the steps of ``a`` and ``b`` are both 1. Parameters ---------- a : range The first range to check. b : range The second range to check. Raises ------ ValueError Raised when either step is not 1.
[ "Check", "that", "the", "steps", "of", "a", "and", "b", "are", "both", "1", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/range.py#L215-L233
train
quantopian/zipline
zipline/utils/range.py
overlap
def overlap(a, b): """Check if two ranges overlap. Parameters ---------- a : range The first range. b : range The second range. Returns ------- overlaps : bool Do these ranges overlap. Notes ----- This function does not support ranges with step != ...
python
def overlap(a, b): """Check if two ranges overlap. Parameters ---------- a : range The first range. b : range The second range. Returns ------- overlaps : bool Do these ranges overlap. Notes ----- This function does not support ranges with step != ...
[ "def", "overlap", "(", "a", ",", "b", ")", ":", "_check_steps", "(", "a", ",", "b", ")", "return", "a", ".", "stop", ">=", "b", ".", "start", "and", "b", ".", "stop", ">=", "a", ".", "start" ]
Check if two ranges overlap. Parameters ---------- a : range The first range. b : range The second range. Returns ------- overlaps : bool Do these ranges overlap. Notes ----- This function does not support ranges with step != 1.
[ "Check", "if", "two", "ranges", "overlap", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/range.py#L236-L256
train
quantopian/zipline
zipline/utils/range.py
merge
def merge(a, b): """Merge two ranges with step == 1. Parameters ---------- a : range The first range. b : range The second range. """ _check_steps(a, b) return range(min(a.start, b.start), max(a.stop, b.stop))
python
def merge(a, b): """Merge two ranges with step == 1. Parameters ---------- a : range The first range. b : range The second range. """ _check_steps(a, b) return range(min(a.start, b.start), max(a.stop, b.stop))
[ "def", "merge", "(", "a", ",", "b", ")", ":", "_check_steps", "(", "a", ",", "b", ")", "return", "range", "(", "min", "(", "a", ".", "start", ",", "b", ".", "start", ")", ",", "max", "(", "a", ".", "stop", ",", "b", ".", "stop", ")", ")" ]
Merge two ranges with step == 1. Parameters ---------- a : range The first range. b : range The second range.
[ "Merge", "two", "ranges", "with", "step", "==", "1", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/range.py#L259-L270
train
quantopian/zipline
zipline/utils/range.py
_combine
def _combine(n, rs): """helper for ``_group_ranges`` """ try: r, rs = peek(rs) except StopIteration: yield n return if overlap(n, r): yield merge(n, r) next(rs) for r in rs: yield r else: yield n for r in rs: ...
python
def _combine(n, rs): """helper for ``_group_ranges`` """ try: r, rs = peek(rs) except StopIteration: yield n return if overlap(n, r): yield merge(n, r) next(rs) for r in rs: yield r else: yield n for r in rs: ...
[ "def", "_combine", "(", "n", ",", "rs", ")", ":", "try", ":", "r", ",", "rs", "=", "peek", "(", "rs", ")", "except", "StopIteration", ":", "yield", "n", "return", "if", "overlap", "(", "n", ",", "r", ")", ":", "yield", "merge", "(", "n", ",", ...
helper for ``_group_ranges``
[ "helper", "for", "_group_ranges" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/range.py#L273-L290
train
quantopian/zipline
zipline/utils/range.py
intersecting_ranges
def intersecting_ranges(ranges): """Return any ranges that intersect. Parameters ---------- ranges : iterable[ranges] A sequence of ranges to check for intersections. Returns ------- intersections : iterable[ranges] A sequence of all of the ranges that intersected in ``rang...
python
def intersecting_ranges(ranges): """Return any ranges that intersect. Parameters ---------- ranges : iterable[ranges] A sequence of ranges to check for intersections. Returns ------- intersections : iterable[ranges] A sequence of all of the ranges that intersected in ``rang...
[ "def", "intersecting_ranges", "(", "ranges", ")", ":", "ranges", "=", "sorted", "(", "ranges", ",", "key", "=", "op", ".", "attrgetter", "(", "'start'", ")", ")", "return", "sorted_diff", "(", "ranges", ",", "group_ranges", "(", "ranges", ")", ")" ]
Return any ranges that intersect. Parameters ---------- ranges : iterable[ranges] A sequence of ranges to check for intersections. Returns ------- intersections : iterable[ranges] A sequence of all of the ranges that intersected in ``ranges``. Examples -------- >>>...
[ "Return", "any", "ranges", "that", "intersect", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/range.py#L336-L364
train
quantopian/zipline
zipline/data/loader.py
get_data_filepath
def get_data_filepath(name, environ=None): """ Returns a handle to data file. Creates containing directory, if needed. """ dr = data_root(environ) if not os.path.exists(dr): os.makedirs(dr) return os.path.join(dr, name)
python
def get_data_filepath(name, environ=None): """ Returns a handle to data file. Creates containing directory, if needed. """ dr = data_root(environ) if not os.path.exists(dr): os.makedirs(dr) return os.path.join(dr, name)
[ "def", "get_data_filepath", "(", "name", ",", "environ", "=", "None", ")", ":", "dr", "=", "data_root", "(", "environ", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "dr", ")", ":", "os", ".", "makedirs", "(", "dr", ")", "return", "os", ...
Returns a handle to data file. Creates containing directory, if needed.
[ "Returns", "a", "handle", "to", "data", "file", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/loader.py#L52-L63
train
quantopian/zipline
zipline/data/loader.py
has_data_for_dates
def has_data_for_dates(series_or_df, first_date, last_date): """ Does `series_or_df` have data on or before first_date and on or after last_date? """ dts = series_or_df.index if not isinstance(dts, pd.DatetimeIndex): raise TypeError("Expected a DatetimeIndex, but got %s." % type(dts)) ...
python
def has_data_for_dates(series_or_df, first_date, last_date): """ Does `series_or_df` have data on or before first_date and on or after last_date? """ dts = series_or_df.index if not isinstance(dts, pd.DatetimeIndex): raise TypeError("Expected a DatetimeIndex, but got %s." % type(dts)) ...
[ "def", "has_data_for_dates", "(", "series_or_df", ",", "first_date", ",", "last_date", ")", ":", "dts", "=", "series_or_df", ".", "index", "if", "not", "isinstance", "(", "dts", ",", "pd", ".", "DatetimeIndex", ")", ":", "raise", "TypeError", "(", "\"Expecte...
Does `series_or_df` have data on or before first_date and on or after last_date?
[ "Does", "series_or_df", "have", "data", "on", "or", "before", "first_date", "and", "on", "or", "after", "last_date?" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/loader.py#L78-L87
train
quantopian/zipline
zipline/data/loader.py
load_market_data
def load_market_data(trading_day=None, trading_days=None, bm_symbol='SPY', environ=None): """ Load benchmark returns and treasury yield curves for the given calendar and benchmark symbol. Benchmarks are downloaded as a Series from IEX Trading. Treasury curves are US Treasury B...
python
def load_market_data(trading_day=None, trading_days=None, bm_symbol='SPY', environ=None): """ Load benchmark returns and treasury yield curves for the given calendar and benchmark symbol. Benchmarks are downloaded as a Series from IEX Trading. Treasury curves are US Treasury B...
[ "def", "load_market_data", "(", "trading_day", "=", "None", ",", "trading_days", "=", "None", ",", "bm_symbol", "=", "'SPY'", ",", "environ", "=", "None", ")", ":", "if", "trading_day", "is", "None", ":", "trading_day", "=", "get_calendar", "(", "'XNYS'", ...
Load benchmark returns and treasury yield curves for the given calendar and benchmark symbol. Benchmarks are downloaded as a Series from IEX Trading. Treasury curves are US Treasury Bond rates and are downloaded from 'www.federalreserve.gov' by default. For Canadian exchanges, a loader for Canadian b...
[ "Load", "benchmark", "returns", "and", "treasury", "yield", "curves", "for", "the", "given", "calendar", "and", "benchmark", "symbol", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/loader.py#L90-L166
train
quantopian/zipline
zipline/data/loader.py
ensure_benchmark_data
def ensure_benchmark_data(symbol, first_date, last_date, now, trading_day, environ=None): """ Ensure we have benchmark data for `symbol` from `first_date` to `last_date` Parameters ---------- symbol : str The symbol for the benchmark to load. first_date : pd.Ti...
python
def ensure_benchmark_data(symbol, first_date, last_date, now, trading_day, environ=None): """ Ensure we have benchmark data for `symbol` from `first_date` to `last_date` Parameters ---------- symbol : str The symbol for the benchmark to load. first_date : pd.Ti...
[ "def", "ensure_benchmark_data", "(", "symbol", ",", "first_date", ",", "last_date", ",", "now", ",", "trading_day", ",", "environ", "=", "None", ")", ":", "filename", "=", "get_benchmark_filename", "(", "symbol", ")", "data", "=", "_load_cached_data", "(", "fi...
Ensure we have benchmark data for `symbol` from `first_date` to `last_date` Parameters ---------- symbol : str The symbol for the benchmark to load. first_date : pd.Timestamp First required date for the cache. last_date : pd.Timestamp Last required date for the cache. no...
[ "Ensure", "we", "have", "benchmark", "data", "for", "symbol", "from", "first_date", "to", "last_date" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/loader.py#L169-L229
train
quantopian/zipline
zipline/data/loader.py
ensure_treasury_data
def ensure_treasury_data(symbol, first_date, last_date, now, environ=None): """ Ensure we have treasury data from treasury module associated with `symbol`. Parameters ---------- symbol : str Benchmark symbol for which we're loading associated treasury curves. first_date : pd.Timesta...
python
def ensure_treasury_data(symbol, first_date, last_date, now, environ=None): """ Ensure we have treasury data from treasury module associated with `symbol`. Parameters ---------- symbol : str Benchmark symbol for which we're loading associated treasury curves. first_date : pd.Timesta...
[ "def", "ensure_treasury_data", "(", "symbol", ",", "first_date", ",", "last_date", ",", "now", ",", "environ", "=", "None", ")", ":", "loader_module", ",", "filename", ",", "source", "=", "INDEX_MAPPING", ".", "get", "(", "symbol", ",", "INDEX_MAPPING", "[",...
Ensure we have treasury data from treasury module associated with `symbol`. Parameters ---------- symbol : str Benchmark symbol for which we're loading associated treasury curves. first_date : pd.Timestamp First date required to be in the cache. last_date : pd.Timestamp ...
[ "Ensure", "we", "have", "treasury", "data", "from", "treasury", "module", "associated", "with", "symbol", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/loader.py#L232-L292
train
quantopian/zipline
zipline/pipeline/graph.py
maybe_specialize
def maybe_specialize(term, domain): """Specialize a term if it's loadable. """ if isinstance(term, LoadableTerm): return term.specialize(domain) return term
python
def maybe_specialize(term, domain): """Specialize a term if it's loadable. """ if isinstance(term, LoadableTerm): return term.specialize(domain) return term
[ "def", "maybe_specialize", "(", "term", ",", "domain", ")", ":", "if", "isinstance", "(", "term", ",", "LoadableTerm", ")", ":", "return", "term", ".", "specialize", "(", "domain", ")", "return", "term" ]
Specialize a term if it's loadable.
[ "Specialize", "a", "term", "if", "it", "s", "loadable", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/graph.py#L498-L503
train
quantopian/zipline
zipline/pipeline/graph.py
TermGraph._add_to_graph
def _add_to_graph(self, term, parents): """ Add a term and all its children to ``graph``. ``parents`` is the set of all the parents of ``term` that we've added so far. It is only used to detect dependency cycles. """ if self._frozen: raise ValueError( ...
python
def _add_to_graph(self, term, parents): """ Add a term and all its children to ``graph``. ``parents`` is the set of all the parents of ``term` that we've added so far. It is only used to detect dependency cycles. """ if self._frozen: raise ValueError( ...
[ "def", "_add_to_graph", "(", "self", ",", "term", ",", "parents", ")", ":", "if", "self", ".", "_frozen", ":", "raise", "ValueError", "(", "\"Can't mutate %s after construction.\"", "%", "type", "(", "self", ")", ".", "__name__", ")", "# If we've seen this node ...
Add a term and all its children to ``graph``. ``parents`` is the set of all the parents of ``term` that we've added so far. It is only used to detect dependency cycles.
[ "Add", "a", "term", "and", "all", "its", "children", "to", "graph", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/graph.py#L69-L95
train
quantopian/zipline
zipline/pipeline/graph.py
TermGraph.execution_order
def execution_order(self, refcounts): """ Return a topologically-sorted iterator over the terms in ``self`` which need to be computed. """ return iter(nx.topological_sort( self.graph.subgraph( {term for term, refcount in refcounts.items() if refcount >...
python
def execution_order(self, refcounts): """ Return a topologically-sorted iterator over the terms in ``self`` which need to be computed. """ return iter(nx.topological_sort( self.graph.subgraph( {term for term, refcount in refcounts.items() if refcount >...
[ "def", "execution_order", "(", "self", ",", "refcounts", ")", ":", "return", "iter", "(", "nx", ".", "topological_sort", "(", "self", ".", "graph", ".", "subgraph", "(", "{", "term", "for", "term", ",", "refcount", "in", "refcounts", ".", "items", "(", ...
Return a topologically-sorted iterator over the terms in ``self`` which need to be computed.
[ "Return", "a", "topologically", "-", "sorted", "iterator", "over", "the", "terms", "in", "self", "which", "need", "to", "be", "computed", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/graph.py#L110-L119
train
quantopian/zipline
zipline/pipeline/graph.py
TermGraph.initial_refcounts
def initial_refcounts(self, initial_terms): """ Calculate initial refcounts for execution of this graph. Parameters ---------- initial_terms : iterable[Term] An iterable of terms that were pre-computed before graph execution. Each node starts with a refcount...
python
def initial_refcounts(self, initial_terms): """ Calculate initial refcounts for execution of this graph. Parameters ---------- initial_terms : iterable[Term] An iterable of terms that were pre-computed before graph execution. Each node starts with a refcount...
[ "def", "initial_refcounts", "(", "self", ",", "initial_terms", ")", ":", "refcounts", "=", "self", ".", "graph", ".", "out_degree", "(", ")", "for", "t", "in", "self", ".", "outputs", ".", "values", "(", ")", ":", "refcounts", "[", "t", "]", "+=", "1...
Calculate initial refcounts for execution of this graph. Parameters ---------- initial_terms : iterable[Term] An iterable of terms that were pre-computed before graph execution. Each node starts with a refcount equal to its outdegree, and output nodes get one extra ...
[ "Calculate", "initial", "refcounts", "for", "execution", "of", "this", "graph", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/graph.py#L143-L163
train
quantopian/zipline
zipline/pipeline/graph.py
TermGraph._decref_dependencies_recursive
def _decref_dependencies_recursive(self, term, refcounts, garbage): """ Decrement terms recursively. Notes ----- This should only be used to build the initial workspace, after that we should use: :meth:`~zipline.pipeline.graph.TermGraph.decref_dependencies` ...
python
def _decref_dependencies_recursive(self, term, refcounts, garbage): """ Decrement terms recursively. Notes ----- This should only be used to build the initial workspace, after that we should use: :meth:`~zipline.pipeline.graph.TermGraph.decref_dependencies` ...
[ "def", "_decref_dependencies_recursive", "(", "self", ",", "term", ",", "refcounts", ",", "garbage", ")", ":", "# Edges are tuple of (from, to).", "for", "parent", ",", "_", "in", "self", ".", "graph", ".", "in_edges", "(", "[", "term", "]", ")", ":", "refco...
Decrement terms recursively. Notes ----- This should only be used to build the initial workspace, after that we should use: :meth:`~zipline.pipeline.graph.TermGraph.decref_dependencies`
[ "Decrement", "terms", "recursively", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/graph.py#L165-L182
train
quantopian/zipline
zipline/pipeline/graph.py
TermGraph.decref_dependencies
def decref_dependencies(self, term, refcounts): """ Decrement in-edges for ``term`` after computation. Parameters ---------- term : zipline.pipeline.Term The term whose parents should be decref'ed. refcounts : dict[Term -> int] Dictionary of refco...
python
def decref_dependencies(self, term, refcounts): """ Decrement in-edges for ``term`` after computation. Parameters ---------- term : zipline.pipeline.Term The term whose parents should be decref'ed. refcounts : dict[Term -> int] Dictionary of refco...
[ "def", "decref_dependencies", "(", "self", ",", "term", ",", "refcounts", ")", ":", "garbage", "=", "set", "(", ")", "# Edges are tuple of (from, to).", "for", "parent", ",", "_", "in", "self", ".", "graph", ".", "in_edges", "(", "[", "term", "]", ")", "...
Decrement in-edges for ``term`` after computation. Parameters ---------- term : zipline.pipeline.Term The term whose parents should be decref'ed. refcounts : dict[Term -> int] Dictionary of refcounts. Return ------ garbage : set[Term] ...
[ "Decrement", "in", "-", "edges", "for", "term", "after", "computation", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/graph.py#L184-L208
train
quantopian/zipline
zipline/pipeline/graph.py
ExecutionPlan.offset
def offset(self): """ For all pairs (term, input) such that `input` is an input to `term`, compute a mapping:: (term, input) -> offset(term, input) where ``offset(term, input)`` is the number of rows that ``term`` should truncate off the raw array produced for ``inp...
python
def offset(self): """ For all pairs (term, input) such that `input` is an input to `term`, compute a mapping:: (term, input) -> offset(term, input) where ``offset(term, input)`` is the number of rows that ``term`` should truncate off the raw array produced for ``inp...
[ "def", "offset", "(", "self", ")", ":", "extra", "=", "self", ".", "extra_rows", "out", "=", "{", "}", "for", "term", "in", "self", ".", "graph", ":", "for", "dep", ",", "requested_extra_rows", "in", "term", ".", "dependencies", ".", "items", "(", ")...
For all pairs (term, input) such that `input` is an input to `term`, compute a mapping:: (term, input) -> offset(term, input) where ``offset(term, input)`` is the number of rows that ``term`` should truncate off the raw array produced for ``input`` before using it. We compu...
[ "For", "all", "pairs", "(", "term", "input", ")", "such", "that", "input", "is", "an", "input", "to", "term", "compute", "a", "mapping", "::" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/graph.py#L324-L403
train
quantopian/zipline
zipline/pipeline/graph.py
ExecutionPlan.extra_rows
def extra_rows(self): """ A dict mapping `term` -> `# of extra rows to load/compute of `term`. Notes ---- This value depends on the other terms in the graph that require `term` **as an input**. This is not to be confused with `term.dependencies`, which describes...
python
def extra_rows(self): """ A dict mapping `term` -> `# of extra rows to load/compute of `term`. Notes ---- This value depends on the other terms in the graph that require `term` **as an input**. This is not to be confused with `term.dependencies`, which describes...
[ "def", "extra_rows", "(", "self", ")", ":", "return", "{", "term", ":", "attrs", "[", "'extra_rows'", "]", "for", "term", ",", "attrs", "in", "iteritems", "(", "self", ".", "graph", ".", "node", ")", "}" ]
A dict mapping `term` -> `# of extra rows to load/compute of `term`. Notes ---- This value depends on the other terms in the graph that require `term` **as an input**. This is not to be confused with `term.dependencies`, which describes how many additional rows of `term`'s inpu...
[ "A", "dict", "mapping", "term", "-", ">", "#", "of", "extra", "rows", "to", "load", "/", "compute", "of", "term", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/graph.py#L406-L442
train
quantopian/zipline
zipline/pipeline/graph.py
ExecutionPlan._ensure_extra_rows
def _ensure_extra_rows(self, term, N): """ Ensure that we're going to compute at least N extra rows of `term`. """ attrs = self.graph.node[term] attrs['extra_rows'] = max(N, attrs.get('extra_rows', 0))
python
def _ensure_extra_rows(self, term, N): """ Ensure that we're going to compute at least N extra rows of `term`. """ attrs = self.graph.node[term] attrs['extra_rows'] = max(N, attrs.get('extra_rows', 0))
[ "def", "_ensure_extra_rows", "(", "self", ",", "term", ",", "N", ")", ":", "attrs", "=", "self", ".", "graph", ".", "node", "[", "term", "]", "attrs", "[", "'extra_rows'", "]", "=", "max", "(", "N", ",", "attrs", ".", "get", "(", "'extra_rows'", ",...
Ensure that we're going to compute at least N extra rows of `term`.
[ "Ensure", "that", "we", "re", "going", "to", "compute", "at", "least", "N", "extra", "rows", "of", "term", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/graph.py#L444-L449
train
quantopian/zipline
zipline/pipeline/graph.py
ExecutionPlan.mask_and_dates_for_term
def mask_and_dates_for_term(self, term, root_mask_term, workspace, all_dates): """ Load mask and mask row labels for term. Parameters ---------- term :...
python
def mask_and_dates_for_term(self, term, root_mask_term, workspace, all_dates): """ Load mask and mask row labels for term. Parameters ---------- term :...
[ "def", "mask_and_dates_for_term", "(", "self", ",", "term", ",", "root_mask_term", ",", "workspace", ",", "all_dates", ")", ":", "mask", "=", "term", ".", "mask", "mask_offset", "=", "self", ".", "extra_rows", "[", "mask", "]", "-", "self", ".", "extra_row...
Load mask and mask row labels for term. Parameters ---------- term : Term The term to load the mask and labels for. root_mask_term : Term The term that represents the root asset exists mask. workspace : dict[Term, any] The values that have bee...
[ "Load", "mask", "and", "mask", "row", "labels", "for", "term", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/graph.py#L451-L486
train
quantopian/zipline
zipline/pipeline/graph.py
ExecutionPlan._assert_all_loadable_terms_specialized_to
def _assert_all_loadable_terms_specialized_to(self, domain): """Make sure that we've specialized all loadable terms in the graph. """ for term in self.graph.node: if isinstance(term, LoadableTerm): assert term.domain is domain
python
def _assert_all_loadable_terms_specialized_to(self, domain): """Make sure that we've specialized all loadable terms in the graph. """ for term in self.graph.node: if isinstance(term, LoadableTerm): assert term.domain is domain
[ "def", "_assert_all_loadable_terms_specialized_to", "(", "self", ",", "domain", ")", ":", "for", "term", "in", "self", ".", "graph", ".", "node", ":", "if", "isinstance", "(", "term", ",", "LoadableTerm", ")", ":", "assert", "term", ".", "domain", "is", "d...
Make sure that we've specialized all loadable terms in the graph.
[ "Make", "sure", "that", "we", "ve", "specialized", "all", "loadable", "terms", "in", "the", "graph", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/graph.py#L488-L493
train
quantopian/zipline
setup.py
window_specialization
def window_specialization(typename): """Make an extension for an AdjustedArrayWindow specialization.""" return Extension( 'zipline.lib._{name}window'.format(name=typename), ['zipline/lib/_{name}window.pyx'.format(name=typename)], depends=['zipline/lib/_windowtemplate.pxi'], )
python
def window_specialization(typename): """Make an extension for an AdjustedArrayWindow specialization.""" return Extension( 'zipline.lib._{name}window'.format(name=typename), ['zipline/lib/_{name}window.pyx'.format(name=typename)], depends=['zipline/lib/_windowtemplate.pxi'], )
[ "def", "window_specialization", "(", "typename", ")", ":", "return", "Extension", "(", "'zipline.lib._{name}window'", ".", "format", "(", "name", "=", "typename", ")", ",", "[", "'zipline/lib/_{name}window.pyx'", ".", "format", "(", "name", "=", "typename", ")", ...
Make an extension for an AdjustedArrayWindow specialization.
[ "Make", "an", "extension", "for", "an", "AdjustedArrayWindow", "specialization", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/setup.py#L81-L87
train
quantopian/zipline
setup.py
read_requirements
def read_requirements(path, strict_bounds, conda_format=False, filter_names=None): """ Read a requirements.txt file, expressed as a path relative to Zipline root. Returns requirements with the pinned versions as lower bounds if `strict_b...
python
def read_requirements(path, strict_bounds, conda_format=False, filter_names=None): """ Read a requirements.txt file, expressed as a path relative to Zipline root. Returns requirements with the pinned versions as lower bounds if `strict_b...
[ "def", "read_requirements", "(", "path", ",", "strict_bounds", ",", "conda_format", "=", "False", ",", "filter_names", "=", "None", ")", ":", "real_path", "=", "join", "(", "dirname", "(", "abspath", "(", "__file__", ")", ")", ",", "path", ")", "with", "...
Read a requirements.txt file, expressed as a path relative to Zipline root. Returns requirements with the pinned versions as lower bounds if `strict_bounds` is falsey.
[ "Read", "a", "requirements", ".", "txt", "file", "expressed", "as", "a", "path", "relative", "to", "Zipline", "root", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/setup.py#L217-L238
train
quantopian/zipline
zipline/utils/events.py
ensure_utc
def ensure_utc(time, tz='UTC'): """ Normalize a time. If the time is tz-naive, assume it is UTC. """ if not time.tzinfo: time = time.replace(tzinfo=pytz.timezone(tz)) return time.replace(tzinfo=pytz.utc)
python
def ensure_utc(time, tz='UTC'): """ Normalize a time. If the time is tz-naive, assume it is UTC. """ if not time.tzinfo: time = time.replace(tzinfo=pytz.timezone(tz)) return time.replace(tzinfo=pytz.utc)
[ "def", "ensure_utc", "(", "time", ",", "tz", "=", "'UTC'", ")", ":", "if", "not", "time", ".", "tzinfo", ":", "time", "=", "time", ".", "replace", "(", "tzinfo", "=", "pytz", ".", "timezone", "(", "tz", ")", ")", "return", "time", ".", "replace", ...
Normalize a time. If the time is tz-naive, assume it is UTC.
[ "Normalize", "a", "time", ".", "If", "the", "time", "is", "tz", "-", "naive", "assume", "it", "is", "UTC", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/events.py#L72-L78
train
quantopian/zipline
zipline/utils/events.py
_build_offset
def _build_offset(offset, kwargs, default): """ Builds the offset argument for event rules. """ if offset is None: if not kwargs: return default # use the default. else: return _td_check(datetime.timedelta(**kwargs)) elif kwargs: raise ValueError('Can...
python
def _build_offset(offset, kwargs, default): """ Builds the offset argument for event rules. """ if offset is None: if not kwargs: return default # use the default. else: return _td_check(datetime.timedelta(**kwargs)) elif kwargs: raise ValueError('Can...
[ "def", "_build_offset", "(", "offset", ",", "kwargs", ",", "default", ")", ":", "if", "offset", "is", "None", ":", "if", "not", "kwargs", ":", "return", "default", "# use the default.", "else", ":", "return", "_td_check", "(", "datetime", ".", "timedelta", ...
Builds the offset argument for event rules.
[ "Builds", "the", "offset", "argument", "for", "event", "rules", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/events.py#L108-L122
train
quantopian/zipline
zipline/utils/events.py
_build_date
def _build_date(date, kwargs): """ Builds the date argument for event rules. """ if date is None: if not kwargs: raise ValueError('Must pass a date or kwargs') else: return datetime.date(**kwargs) elif kwargs: raise ValueError('Cannot pass kwargs and ...
python
def _build_date(date, kwargs): """ Builds the date argument for event rules. """ if date is None: if not kwargs: raise ValueError('Must pass a date or kwargs') else: return datetime.date(**kwargs) elif kwargs: raise ValueError('Cannot pass kwargs and ...
[ "def", "_build_date", "(", "date", ",", "kwargs", ")", ":", "if", "date", "is", "None", ":", "if", "not", "kwargs", ":", "raise", "ValueError", "(", "'Must pass a date or kwargs'", ")", "else", ":", "return", "datetime", ".", "date", "(", "*", "*", "kwar...
Builds the date argument for event rules.
[ "Builds", "the", "date", "argument", "for", "event", "rules", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/events.py#L125-L138
train
quantopian/zipline
zipline/utils/events.py
_build_time
def _build_time(time, kwargs): """ Builds the time argument for event rules. """ tz = kwargs.pop('tz', 'UTC') if time: if kwargs: raise ValueError('Cannot pass kwargs and a time') else: return ensure_utc(time, tz) elif not kwargs: raise ValueError(...
python
def _build_time(time, kwargs): """ Builds the time argument for event rules. """ tz = kwargs.pop('tz', 'UTC') if time: if kwargs: raise ValueError('Cannot pass kwargs and a time') else: return ensure_utc(time, tz) elif not kwargs: raise ValueError(...
[ "def", "_build_time", "(", "time", ",", "kwargs", ")", ":", "tz", "=", "kwargs", ".", "pop", "(", "'tz'", ",", "'UTC'", ")", "if", "time", ":", "if", "kwargs", ":", "raise", "ValueError", "(", "'Cannot pass kwargs and a time'", ")", "else", ":", "return"...
Builds the time argument for event rules.
[ "Builds", "the", "time", "argument", "for", "event", "rules", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/events.py#L141-L154
train
quantopian/zipline
zipline/utils/events.py
lossless_float_to_int
def lossless_float_to_int(funcname, func, argname, arg): """ A preprocessor that coerces integral floats to ints. Receipt of non-integral floats raises a TypeError. """ if not isinstance(arg, float): return arg arg_as_int = int(arg) if arg == arg_as_int: warnings.warn( ...
python
def lossless_float_to_int(funcname, func, argname, arg): """ A preprocessor that coerces integral floats to ints. Receipt of non-integral floats raises a TypeError. """ if not isinstance(arg, float): return arg arg_as_int = int(arg) if arg == arg_as_int: warnings.warn( ...
[ "def", "lossless_float_to_int", "(", "funcname", ",", "func", ",", "argname", ",", "arg", ")", ":", "if", "not", "isinstance", "(", "arg", ",", "float", ")", ":", "return", "arg", "arg_as_int", "=", "int", "(", "arg", ")", "if", "arg", "==", "arg_as_in...
A preprocessor that coerces integral floats to ints. Receipt of non-integral floats raises a TypeError.
[ "A", "preprocessor", "that", "coerces", "integral", "floats", "to", "ints", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/events.py#L158-L179
train
quantopian/zipline
zipline/utils/events.py
make_eventrule
def make_eventrule(date_rule, time_rule, cal, half_days=True): """ Constructs an event rule from the factory api. """ _check_if_not_called(date_rule) _check_if_not_called(time_rule) if half_days: inner_rule = date_rule & time_rule else: inner_rule = date_rule & time_rule & N...
python
def make_eventrule(date_rule, time_rule, cal, half_days=True): """ Constructs an event rule from the factory api. """ _check_if_not_called(date_rule) _check_if_not_called(time_rule) if half_days: inner_rule = date_rule & time_rule else: inner_rule = date_rule & time_rule & N...
[ "def", "make_eventrule", "(", "date_rule", ",", "time_rule", ",", "cal", ",", "half_days", "=", "True", ")", ":", "_check_if_not_called", "(", "date_rule", ")", "_check_if_not_called", "(", "time_rule", ")", "if", "half_days", ":", "inner_rule", "=", "date_rule"...
Constructs an event rule from the factory api.
[ "Constructs", "an", "event", "rule", "from", "the", "factory", "api", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/events.py#L662-L677
train
quantopian/zipline
zipline/utils/events.py
EventManager.add_event
def add_event(self, event, prepend=False): """ Adds an event to the manager. """ if prepend: self._events.insert(0, event) else: self._events.append(event)
python
def add_event(self, event, prepend=False): """ Adds an event to the manager. """ if prepend: self._events.insert(0, event) else: self._events.append(event)
[ "def", "add_event", "(", "self", ",", "event", ",", "prepend", "=", "False", ")", ":", "if", "prepend", ":", "self", ".", "_events", ".", "insert", "(", "0", ",", "event", ")", "else", ":", "self", ".", "_events", ".", "append", "(", "event", ")" ]
Adds an event to the manager.
[ "Adds", "an", "event", "to", "the", "manager", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/events.py#L201-L208
train
quantopian/zipline
zipline/utils/events.py
Event.handle_data
def handle_data(self, context, data, dt): """ Calls the callable only when the rule is triggered. """ if self.rule.should_trigger(dt): self.callback(context, data)
python
def handle_data(self, context, data, dt): """ Calls the callable only when the rule is triggered. """ if self.rule.should_trigger(dt): self.callback(context, data)
[ "def", "handle_data", "(", "self", ",", "context", ",", "data", ",", "dt", ")", ":", "if", "self", ".", "rule", ".", "should_trigger", "(", "dt", ")", ":", "self", ".", "callback", "(", "context", ",", "data", ")" ]
Calls the callable only when the rule is triggered.
[ "Calls", "the", "callable", "only", "when", "the", "rule", "is", "triggered", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/events.py#L230-L235
train
quantopian/zipline
zipline/utils/events.py
ComposedRule.should_trigger
def should_trigger(self, dt): """ Composes the two rules with a lazy composer. """ return self.composer( self.first.should_trigger, self.second.should_trigger, dt )
python
def should_trigger(self, dt): """ Composes the two rules with a lazy composer. """ return self.composer( self.first.should_trigger, self.second.should_trigger, dt )
[ "def", "should_trigger", "(", "self", ",", "dt", ")", ":", "return", "self", ".", "composer", "(", "self", ".", "first", ".", "should_trigger", ",", "self", ".", "second", ".", "should_trigger", ",", "dt", ")" ]
Composes the two rules with a lazy composer.
[ "Composes", "the", "two", "rules", "with", "a", "lazy", "composer", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/events.py#L298-L306
train
quantopian/zipline
zipline/utils/events.py
AfterOpen.calculate_dates
def calculate_dates(self, dt): """ Given a date, find that day's open and period end (open + offset). """ period_start, period_close = self.cal.open_and_close_for_session( self.cal.minute_to_session_label(dt), ) # Align the market open and close times here wi...
python
def calculate_dates(self, dt): """ Given a date, find that day's open and period end (open + offset). """ period_start, period_close = self.cal.open_and_close_for_session( self.cal.minute_to_session_label(dt), ) # Align the market open and close times here wi...
[ "def", "calculate_dates", "(", "self", ",", "dt", ")", ":", "period_start", ",", "period_close", "=", "self", ".", "cal", ".", "open_and_close_for_session", "(", "self", ".", "cal", ".", "minute_to_session_label", "(", "dt", ")", ",", ")", "# Align the market ...
Given a date, find that day's open and period end (open + offset).
[ "Given", "a", "date", "find", "that", "day", "s", "open", "and", "period", "end", "(", "open", "+", "offset", ")", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/events.py#L373-L387
train
quantopian/zipline
zipline/utils/events.py
BeforeClose.calculate_dates
def calculate_dates(self, dt): """ Given a dt, find that day's close and period start (close - offset). """ period_end = self.cal.open_and_close_for_session( self.cal.minute_to_session_label(dt), )[1] # Align the market close time here with the execution time...
python
def calculate_dates(self, dt): """ Given a dt, find that day's close and period start (close - offset). """ period_end = self.cal.open_and_close_for_session( self.cal.minute_to_session_label(dt), )[1] # Align the market close time here with the execution time...
[ "def", "calculate_dates", "(", "self", ",", "dt", ")", ":", "period_end", "=", "self", ".", "cal", ".", "open_and_close_for_session", "(", "self", ".", "cal", ".", "minute_to_session_label", "(", "dt", ")", ",", ")", "[", "1", "]", "# Align the market close ...
Given a dt, find that day's close and period start (close - offset).
[ "Given", "a", "dt", "find", "that", "day", "s", "close", "and", "period", "start", "(", "close", "-", "offset", ")", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/events.py#L429-L443
train
quantopian/zipline
zipline/data/bcolz_daily_bars.py
winsorise_uint32
def winsorise_uint32(df, invalid_data_behavior, column, *columns): """Drops any record where a value would not fit into a uint32. Parameters ---------- df : pd.DataFrame The dataframe to winsorise. invalid_data_behavior : {'warn', 'raise', 'ignore'} What to do when data is outside t...
python
def winsorise_uint32(df, invalid_data_behavior, column, *columns): """Drops any record where a value would not fit into a uint32. Parameters ---------- df : pd.DataFrame The dataframe to winsorise. invalid_data_behavior : {'warn', 'raise', 'ignore'} What to do when data is outside t...
[ "def", "winsorise_uint32", "(", "df", ",", "invalid_data_behavior", ",", "column", ",", "*", "columns", ")", ":", "columns", "=", "list", "(", "(", "column", ",", ")", "+", "columns", ")", "mask", "=", "df", "[", "columns", "]", ">", "UINT32_MAX", "if"...
Drops any record where a value would not fit into a uint32. Parameters ---------- df : pd.DataFrame The dataframe to winsorise. invalid_data_behavior : {'warn', 'raise', 'ignore'} What to do when data is outside the bounds of a uint32. *columns : iterable[str] The names of t...
[ "Drops", "any", "record", "where", "a", "value", "would", "not", "fit", "into", "a", "uint32", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/bcolz_daily_bars.py#L69-L114
train
quantopian/zipline
zipline/data/bcolz_daily_bars.py
BcolzDailyBarWriter.write
def write(self, data, assets=None, show_progress=False, invalid_data_behavior='warn'): """ Parameters ---------- data : iterable[tuple[int, pandas.DataFrame or bcolz.ctable]] The data chunks to write. Each chunk should b...
python
def write(self, data, assets=None, show_progress=False, invalid_data_behavior='warn'): """ Parameters ---------- data : iterable[tuple[int, pandas.DataFrame or bcolz.ctable]] The data chunks to write. Each chunk should b...
[ "def", "write", "(", "self", ",", "data", ",", "assets", "=", "None", ",", "show_progress", "=", "False", ",", "invalid_data_behavior", "=", "'warn'", ")", ":", "ctx", "=", "maybe_show_progress", "(", "(", "(", "sid", ",", "self", ".", "to_ctable", "(", ...
Parameters ---------- data : iterable[tuple[int, pandas.DataFrame or bcolz.ctable]] The data chunks to write. Each chunk should be a tuple of sid and the data for that asset. assets : set[int], optional The assets that should be in ``data``. If this is provide...
[ "Parameters", "----------", "data", ":", "iterable", "[", "tuple", "[", "int", "pandas", ".", "DataFrame", "or", "bcolz", ".", "ctable", "]]", "The", "data", "chunks", "to", "write", ".", "Each", "chunk", "should", "be", "a", "tuple", "of", "sid", "and",...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/bcolz_daily_bars.py#L170-L207
train
quantopian/zipline
zipline/data/bcolz_daily_bars.py
BcolzDailyBarWriter.write_csvs
def write_csvs(self, asset_map, show_progress=False, invalid_data_behavior='warn'): """Read CSVs as DataFrames from our asset map. Parameters ---------- asset_map : dict[int -> str] A mapping from asset id to file path...
python
def write_csvs(self, asset_map, show_progress=False, invalid_data_behavior='warn'): """Read CSVs as DataFrames from our asset map. Parameters ---------- asset_map : dict[int -> str] A mapping from asset id to file path...
[ "def", "write_csvs", "(", "self", ",", "asset_map", ",", "show_progress", "=", "False", ",", "invalid_data_behavior", "=", "'warn'", ")", ":", "read", "=", "partial", "(", "read_csv", ",", "parse_dates", "=", "[", "'day'", "]", ",", "index_col", "=", "'day...
Read CSVs as DataFrames from our asset map. Parameters ---------- asset_map : dict[int -> str] A mapping from asset id to file path with the CSV data for that asset show_progress : bool Whether or not to show a progress bar while writing. inva...
[ "Read", "CSVs", "as", "DataFrames", "from", "our", "asset", "map", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/bcolz_daily_bars.py#L209-L237
train
quantopian/zipline
zipline/data/bcolz_daily_bars.py
BcolzDailyBarWriter._write_internal
def _write_internal(self, iterator, assets): """ Internal implementation of write. `iterator` should be an iterator yielding pairs of (asset, ctable). """ total_rows = 0 first_row = {} last_row = {} calendar_offset = {} # Maps column name -> outp...
python
def _write_internal(self, iterator, assets): """ Internal implementation of write. `iterator` should be an iterator yielding pairs of (asset, ctable). """ total_rows = 0 first_row = {} last_row = {} calendar_offset = {} # Maps column name -> outp...
[ "def", "_write_internal", "(", "self", ",", "iterator", ",", "assets", ")", ":", "total_rows", "=", "0", "first_row", "=", "{", "}", "last_row", "=", "{", "}", "calendar_offset", "=", "{", "}", "# Maps column name -> output carray.", "columns", "=", "{", "k"...
Internal implementation of write. `iterator` should be an iterator yielding pairs of (asset, ctable).
[ "Internal", "implementation", "of", "write", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/bcolz_daily_bars.py#L239-L359
train
quantopian/zipline
zipline/data/bcolz_daily_bars.py
BcolzDailyBarReader._compute_slices
def _compute_slices(self, start_idx, end_idx, assets): """ Compute the raw row indices to load for each asset on a query for the given dates after applying a shift. Parameters ---------- start_idx : int Index of first date for which we want data. end_...
python
def _compute_slices(self, start_idx, end_idx, assets): """ Compute the raw row indices to load for each asset on a query for the given dates after applying a shift. Parameters ---------- start_idx : int Index of first date for which we want data. end_...
[ "def", "_compute_slices", "(", "self", ",", "start_idx", ",", "end_idx", ",", "assets", ")", ":", "# The core implementation of the logic here is implemented in Cython", "# for efficiency.", "return", "_compute_row_slices", "(", "self", ".", "_first_rows", ",", "self", "....
Compute the raw row indices to load for each asset on a query for the given dates after applying a shift. Parameters ---------- start_idx : int Index of first date for which we want data. end_idx : int Index of last date for which we want data. as...
[ "Compute", "the", "raw", "row", "indices", "to", "load", "for", "each", "asset", "on", "a", "query", "for", "the", "given", "dates", "after", "applying", "a", "shift", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/bcolz_daily_bars.py#L530-L570
train
quantopian/zipline
zipline/data/bcolz_daily_bars.py
BcolzDailyBarReader._spot_col
def _spot_col(self, colname): """ Get the colname from daily_bar_table and read all of it into memory, caching the result. Parameters ---------- colname : string A name of a OHLCV carray in the daily_bar_table Returns ------- array (u...
python
def _spot_col(self, colname): """ Get the colname from daily_bar_table and read all of it into memory, caching the result. Parameters ---------- colname : string A name of a OHLCV carray in the daily_bar_table Returns ------- array (u...
[ "def", "_spot_col", "(", "self", ",", "colname", ")", ":", "try", ":", "col", "=", "self", ".", "_spot_cols", "[", "colname", "]", "except", "KeyError", ":", "col", "=", "self", ".", "_spot_cols", "[", "colname", "]", "=", "self", ".", "_table", "[",...
Get the colname from daily_bar_table and read all of it into memory, caching the result. Parameters ---------- colname : string A name of a OHLCV carray in the daily_bar_table Returns ------- array (uint32) Full read array of the carray i...
[ "Get", "the", "colname", "from", "daily_bar_table", "and", "read", "all", "of", "it", "into", "memory", "caching", "the", "result", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/bcolz_daily_bars.py#L598-L618
train
quantopian/zipline
zipline/data/bcolz_daily_bars.py
BcolzDailyBarReader.sid_day_index
def sid_day_index(self, sid, day): """ Parameters ---------- sid : int The asset identifier. day : datetime64-like Midnight of the day for which data is requested. Returns ------- int Index into the data tape for the gi...
python
def sid_day_index(self, sid, day): """ Parameters ---------- sid : int The asset identifier. day : datetime64-like Midnight of the day for which data is requested. Returns ------- int Index into the data tape for the gi...
[ "def", "sid_day_index", "(", "self", ",", "sid", ",", "day", ")", ":", "try", ":", "day_loc", "=", "self", ".", "sessions", ".", "get_loc", "(", "day", ")", "except", "Exception", ":", "raise", "NoDataOnDate", "(", "\"day={0} is outside of calendar={1}\"", "...
Parameters ---------- sid : int The asset identifier. day : datetime64-like Midnight of the day for which data is requested. Returns ------- int Index into the data tape for the given sid and day. Raises a NoDataOnDate exce...
[ "Parameters", "----------", "sid", ":", "int", "The", "asset", "identifier", ".", "day", ":", "datetime64", "-", "like", "Midnight", "of", "the", "day", "for", "which", "data", "is", "requested", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/bcolz_daily_bars.py#L645-L676
train
quantopian/zipline
zipline/data/bcolz_daily_bars.py
BcolzDailyBarReader.get_value
def get_value(self, sid, dt, field): """ Parameters ---------- sid : int The asset identifier. day : datetime64-like Midnight of the day for which data is requested. colname : string The price field. e.g. ('open', 'high', 'low', 'close'...
python
def get_value(self, sid, dt, field): """ Parameters ---------- sid : int The asset identifier. day : datetime64-like Midnight of the day for which data is requested. colname : string The price field. e.g. ('open', 'high', 'low', 'close'...
[ "def", "get_value", "(", "self", ",", "sid", ",", "dt", ",", "field", ")", ":", "ix", "=", "self", ".", "sid_day_index", "(", "sid", ",", "dt", ")", "price", "=", "self", ".", "_spot_col", "(", "field", ")", "[", "ix", "]", "if", "field", "!=", ...
Parameters ---------- sid : int The asset identifier. day : datetime64-like Midnight of the day for which data is requested. colname : string The price field. e.g. ('open', 'high', 'low', 'close', 'volume') Returns ------- floa...
[ "Parameters", "----------", "sid", ":", "int", "The", "asset", "identifier", ".", "day", ":", "datetime64", "-", "like", "Midnight", "of", "the", "day", "for", "which", "data", "is", "requested", ".", "colname", ":", "string", "The", "price", "field", ".",...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/bcolz_daily_bars.py#L678-L706
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.init_engine
def init_engine(self, get_loader): """ Construct and store a PipelineEngine from loader. If get_loader is None, constructs an ExplodingPipelineEngine """ if get_loader is not None: self.engine = SimplePipelineEngine( get_loader, self.a...
python
def init_engine(self, get_loader): """ Construct and store a PipelineEngine from loader. If get_loader is None, constructs an ExplodingPipelineEngine """ if get_loader is not None: self.engine = SimplePipelineEngine( get_loader, self.a...
[ "def", "init_engine", "(", "self", ",", "get_loader", ")", ":", "if", "get_loader", "is", "not", "None", ":", "self", ".", "engine", "=", "SimplePipelineEngine", "(", "get_loader", ",", "self", ".", "asset_finder", ",", "self", ".", "default_pipeline_domain", ...
Construct and store a PipelineEngine from loader. If get_loader is None, constructs an ExplodingPipelineEngine
[ "Construct", "and", "store", "a", "PipelineEngine", "from", "loader", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L408-L421
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.initialize
def initialize(self, *args, **kwargs): """ Call self._initialize with `self` made available to Zipline API functions. """ with ZiplineAPI(self): self._initialize(self, *args, **kwargs)
python
def initialize(self, *args, **kwargs): """ Call self._initialize with `self` made available to Zipline API functions. """ with ZiplineAPI(self): self._initialize(self, *args, **kwargs)
[ "def", "initialize", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "ZiplineAPI", "(", "self", ")", ":", "self", ".", "_initialize", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Call self._initialize with `self` made available to Zipline API functions.
[ "Call", "self", ".", "_initialize", "with", "self", "made", "available", "to", "Zipline", "API", "functions", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L423-L429
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm._create_clock
def _create_clock(self): """ If the clock property is not set, then create one based on frequency. """ trading_o_and_c = self.trading_calendar.schedule.ix[ self.sim_params.sessions] market_closes = trading_o_and_c['market_close'] minutely_emission = False ...
python
def _create_clock(self): """ If the clock property is not set, then create one based on frequency. """ trading_o_and_c = self.trading_calendar.schedule.ix[ self.sim_params.sessions] market_closes = trading_o_and_c['market_close'] minutely_emission = False ...
[ "def", "_create_clock", "(", "self", ")", ":", "trading_o_and_c", "=", "self", ".", "trading_calendar", ".", "schedule", ".", "ix", "[", "self", ".", "sim_params", ".", "sessions", "]", "market_closes", "=", "trading_o_and_c", "[", "'market_close'", "]", "minu...
If the clock property is not set, then create one based on frequency.
[ "If", "the", "clock", "property", "is", "not", "set", "then", "create", "one", "based", "on", "frequency", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L482-L526
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.compute_eager_pipelines
def compute_eager_pipelines(self): """ Compute any pipelines attached with eager=True. """ for name, pipe in self._pipelines.items(): if pipe.eager: self.pipeline_output(name)
python
def compute_eager_pipelines(self): """ Compute any pipelines attached with eager=True. """ for name, pipe in self._pipelines.items(): if pipe.eager: self.pipeline_output(name)
[ "def", "compute_eager_pipelines", "(", "self", ")", ":", "for", "name", ",", "pipe", "in", "self", ".", "_pipelines", ".", "items", "(", ")", ":", "if", "pipe", ".", "eager", ":", "self", ".", "pipeline_output", "(", "name", ")" ]
Compute any pipelines attached with eager=True.
[ "Compute", "any", "pipelines", "attached", "with", "eager", "=", "True", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L601-L607
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.run
def run(self, data_portal=None): """Run the algorithm. """ # HACK: I don't think we really want to support passing a data portal # this late in the long term, but this is needed for now for backwards # compat downstream. if data_portal is not None: self.data_p...
python
def run(self, data_portal=None): """Run the algorithm. """ # HACK: I don't think we really want to support passing a data portal # this late in the long term, but this is needed for now for backwards # compat downstream. if data_portal is not None: self.data_p...
[ "def", "run", "(", "self", ",", "data_portal", "=", "None", ")", ":", "# HACK: I don't think we really want to support passing a data portal", "# this late in the long term, but this is needed for now for backwards", "# compat downstream.", "if", "data_portal", "is", "not", "None",...
Run the algorithm.
[ "Run", "the", "algorithm", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L617-L650
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.calculate_capital_changes
def calculate_capital_changes(self, dt, emission_rate, is_interday, portfolio_value_adjustment=0.0): """ If there is a capital change for a given dt, this means the the change occurs before `handle_data` on the given dt. In the case of the change being a...
python
def calculate_capital_changes(self, dt, emission_rate, is_interday, portfolio_value_adjustment=0.0): """ If there is a capital change for a given dt, this means the the change occurs before `handle_data` on the given dt. In the case of the change being a...
[ "def", "calculate_capital_changes", "(", "self", ",", "dt", ",", "emission_rate", ",", "is_interday", ",", "portfolio_value_adjustment", "=", "0.0", ")", ":", "try", ":", "capital_change", "=", "self", ".", "capital_changes", "[", "dt", "]", "except", "KeyError"...
If there is a capital change for a given dt, this means the the change occurs before `handle_data` on the given dt. In the case of the change being a target value, the change will be computed on the portfolio value according to prices at the given dt `portfolio_value_adjustment`, if spe...
[ "If", "there", "is", "a", "capital", "change", "for", "a", "given", "dt", "this", "means", "the", "the", "change", "occurs", "before", "handle_data", "on", "the", "given", "dt", ".", "In", "the", "case", "of", "the", "change", "being", "a", "target", "...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L675-L725
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.get_environment
def get_environment(self, field='platform'): """Query the execution environment. Parameters ---------- field : {'platform', 'arena', 'data_frequency', 'start', 'end', 'capital_base', 'platform', '*'} The field to query. The options have the following meaning...
python
def get_environment(self, field='platform'): """Query the execution environment. Parameters ---------- field : {'platform', 'arena', 'data_frequency', 'start', 'end', 'capital_base', 'platform', '*'} The field to query. The options have the following meaning...
[ "def", "get_environment", "(", "self", ",", "field", "=", "'platform'", ")", ":", "env", "=", "{", "'arena'", ":", "self", ".", "sim_params", ".", "arena", ",", "'data_frequency'", ":", "self", ".", "sim_params", ".", "data_frequency", ",", "'start'", ":",...
Query the execution environment. Parameters ---------- field : {'platform', 'arena', 'data_frequency', 'start', 'end', 'capital_base', 'platform', '*'} The field to query. The options have the following meanings: arena : str The arena...
[ "Query", "the", "execution", "environment", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L728-L782
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.fetch_csv
def fetch_csv(self, url, pre_func=None, post_func=None, date_column='date', date_format=None, timezone=pytz.utc.zone, symbol=None, mask=True, symbol_column=No...
python
def fetch_csv(self, url, pre_func=None, post_func=None, date_column='date', date_format=None, timezone=pytz.utc.zone, symbol=None, mask=True, symbol_column=No...
[ "def", "fetch_csv", "(", "self", ",", "url", ",", "pre_func", "=", "None", ",", "post_func", "=", "None", ",", "date_column", "=", "'date'", ",", "date_format", "=", "None", ",", "timezone", "=", "pytz", ".", "utc", ".", "zone", ",", "symbol", "=", "...
Fetch a csv from a remote url and register the data so that it is queryable from the ``data`` object. Parameters ---------- url : str The url of the csv file to load. pre_func : callable[pd.DataFrame -> pd.DataFrame], optional A callback to allow preproce...
[ "Fetch", "a", "csv", "from", "a", "remote", "url", "and", "register", "the", "data", "so", "that", "it", "is", "queryable", "from", "the", "data", "object", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L785-L872
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.add_event
def add_event(self, rule, callback): """Adds an event to the algorithm's EventManager. Parameters ---------- rule : EventRule The rule for when the callback should be triggered. callback : callable[(context, data) -> None] The function to execute when the...
python
def add_event(self, rule, callback): """Adds an event to the algorithm's EventManager. Parameters ---------- rule : EventRule The rule for when the callback should be triggered. callback : callable[(context, data) -> None] The function to execute when the...
[ "def", "add_event", "(", "self", ",", "rule", ",", "callback", ")", ":", "self", ".", "event_manager", ".", "add_event", "(", "zipline", ".", "utils", ".", "events", ".", "Event", "(", "rule", ",", "callback", ")", ",", ")" ]
Adds an event to the algorithm's EventManager. Parameters ---------- rule : EventRule The rule for when the callback should be triggered. callback : callable[(context, data) -> None] The function to execute when the rule is triggered.
[ "Adds", "an", "event", "to", "the", "algorithm", "s", "EventManager", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L874-L886
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.schedule_function
def schedule_function(self, func, date_rule=None, time_rule=None, half_days=True, calendar=None): """Schedules a function to be called according to some timed rules. Paramet...
python
def schedule_function(self, func, date_rule=None, time_rule=None, half_days=True, calendar=None): """Schedules a function to be called according to some timed rules. Paramet...
[ "def", "schedule_function", "(", "self", ",", "func", ",", "date_rule", "=", "None", ",", "time_rule", "=", "None", ",", "half_days", "=", "True", ",", "calendar", "=", "None", ")", ":", "# When the user calls schedule_function(func, <time_rule>), assume that", "# t...
Schedules a function to be called according to some timed rules. Parameters ---------- func : callable[(context, data) -> None] The function to execute when the rule is triggered. date_rule : EventRule, optional The rule for the dates to execute this function. ...
[ "Schedules", "a", "function", "to", "be", "called", "according", "to", "some", "timed", "rules", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L889-L951
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.continuous_future
def continuous_future(self, root_symbol_str, offset=0, roll='volume', adjustment='mul'): """Create a specifier for a continuous contract. Parameters ---------- root_symbol_str : str ...
python
def continuous_future(self, root_symbol_str, offset=0, roll='volume', adjustment='mul'): """Create a specifier for a continuous contract. Parameters ---------- root_symbol_str : str ...
[ "def", "continuous_future", "(", "self", ",", "root_symbol_str", ",", "offset", "=", "0", ",", "roll", "=", "'volume'", ",", "adjustment", "=", "'mul'", ")", ":", "return", "self", ".", "asset_finder", ".", "create_continuous_future", "(", "root_symbol_str", "...
Create a specifier for a continuous contract. Parameters ---------- root_symbol_str : str The root symbol for the future chain. offset : int, optional The distance from the primary contract. Default is 0. roll_style : str, optional How rolls...
[ "Create", "a", "specifier", "for", "a", "continuous", "contract", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1000-L1032
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.symbol
def symbol(self, symbol_str, country_code=None): """Lookup an Equity by its ticker symbol. Parameters ---------- symbol_str : str The ticker symbol for the equity to lookup. country_code : str or None, optional A country to limit symbol searches to. ...
python
def symbol(self, symbol_str, country_code=None): """Lookup an Equity by its ticker symbol. Parameters ---------- symbol_str : str The ticker symbol for the equity to lookup. country_code : str or None, optional A country to limit symbol searches to. ...
[ "def", "symbol", "(", "self", ",", "symbol_str", ",", "country_code", "=", "None", ")", ":", "# If the user has not set the symbol lookup date,", "# use the end_session as the date for symbol->sid resolution.", "_lookup_date", "=", "self", ".", "_symbol_lookup_date", "if", "s...
Lookup an Equity by its ticker symbol. Parameters ---------- symbol_str : str The ticker symbol for the equity to lookup. country_code : str or None, optional A country to limit symbol searches to. Returns ------- equity : Equity ...
[ "Lookup", "an", "Equity", "by", "its", "ticker", "symbol", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1039-L1074
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.symbols
def symbols(self, *args, **kwargs): """Lookup multuple Equities as a list. Parameters ---------- *args : iterable[str] The ticker symbols to lookup. country_code : str or None, optional A country to limit symbol searches to. Returns ---...
python
def symbols(self, *args, **kwargs): """Lookup multuple Equities as a list. Parameters ---------- *args : iterable[str] The ticker symbols to lookup. country_code : str or None, optional A country to limit symbol searches to. Returns ---...
[ "def", "symbols", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "[", "self", ".", "symbol", "(", "identifier", ",", "*", "*", "kwargs", ")", "for", "identifier", "in", "args", "]" ]
Lookup multuple Equities as a list. Parameters ---------- *args : iterable[str] The ticker symbols to lookup. country_code : str or None, optional A country to limit symbol searches to. Returns ------- equities : list[Equity] ...
[ "Lookup", "multuple", "Equities", "as", "a", "list", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1077-L1105
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm._calculate_order_value_amount
def _calculate_order_value_amount(self, asset, value): """ Calculates how many shares/contracts to order based on the type of asset being ordered. """ # Make sure the asset exists, and that there is a last price for it. # FIXME: we should use BarData's can_trade logic her...
python
def _calculate_order_value_amount(self, asset, value): """ Calculates how many shares/contracts to order based on the type of asset being ordered. """ # Make sure the asset exists, and that there is a last price for it. # FIXME: we should use BarData's can_trade logic her...
[ "def", "_calculate_order_value_amount", "(", "self", ",", "asset", ",", "value", ")", ":", "# Make sure the asset exists, and that there is a last price for it.", "# FIXME: we should use BarData's can_trade logic here, but I haven't", "# yet found a good way to do that.", "normalized_date"...
Calculates how many shares/contracts to order based on the type of asset being ordered.
[ "Calculates", "how", "many", "shares", "/", "contracts", "to", "order", "based", "on", "the", "type", "of", "asset", "being", "ordered", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1150-L1192
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.order
def order(self, asset, amount, limit_price=None, stop_price=None, style=None): """Place an order. Parameters ---------- asset : Asset The asset that this order is for. amount : int The ...
python
def order(self, asset, amount, limit_price=None, stop_price=None, style=None): """Place an order. Parameters ---------- asset : Asset The asset that this order is for. amount : int The ...
[ "def", "order", "(", "self", ",", "asset", ",", "amount", ",", "limit_price", "=", "None", ",", "stop_price", "=", "None", ",", "style", "=", "None", ")", ":", "if", "not", "self", ".", "_can_order_asset", "(", "asset", ")", ":", "return", "None", "a...
Place an order. Parameters ---------- asset : Asset The asset that this order is for. amount : int The amount of shares to order. If ``amount`` is positive, this is the number of shares to buy or cover. If ``amount`` is negative, this is t...
[ "Place", "an", "order", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1219-L1269
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.validate_order_params
def validate_order_params(self, asset, amount, limit_price, stop_price, style): """ Helper method for validating parameters to the order API function. ...
python
def validate_order_params(self, asset, amount, limit_price, stop_price, style): """ Helper method for validating parameters to the order API function. ...
[ "def", "validate_order_params", "(", "self", ",", "asset", ",", "amount", ",", "limit_price", ",", "stop_price", ",", "style", ")", ":", "if", "not", "self", ".", "initialized", ":", "raise", "OrderDuringInitialize", "(", "msg", "=", "\"order() can only be calle...
Helper method for validating parameters to the order API function. Raises an UnsupportedOrderParameters if invalid arguments are found.
[ "Helper", "method", "for", "validating", "parameters", "to", "the", "order", "API", "function", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1302-L1335
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.__convert_order_params_for_blotter
def __convert_order_params_for_blotter(asset, limit_price, stop_price, style): """ Helper method for converting deprecated limit_price and stop_price arguments into Ex...
python
def __convert_order_params_for_blotter(asset, limit_price, stop_price, style): """ Helper method for converting deprecated limit_price and stop_price arguments into Ex...
[ "def", "__convert_order_params_for_blotter", "(", "asset", ",", "limit_price", ",", "stop_price", ",", "style", ")", ":", "if", "style", ":", "assert", "(", "limit_price", ",", "stop_price", ")", "==", "(", "None", ",", "None", ")", "return", "style", "if", ...
Helper method for converting deprecated limit_price and stop_price arguments into ExecutionStyle instances. This function assumes that either style == None or (limit_price, stop_price) == (None, None).
[ "Helper", "method", "for", "converting", "deprecated", "limit_price", "and", "stop_price", "arguments", "into", "ExecutionStyle", "instances", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1338-L1359
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.order_value
def order_value(self, asset, value, limit_price=None, stop_price=None, style=None): """Place an order by desired value rather than desired number of shares. Parameters ---------- ...
python
def order_value(self, asset, value, limit_price=None, stop_price=None, style=None): """Place an order by desired value rather than desired number of shares. Parameters ---------- ...
[ "def", "order_value", "(", "self", ",", "asset", ",", "value", ",", "limit_price", "=", "None", ",", "stop_price", "=", "None", ",", "style", "=", "None", ")", ":", "if", "not", "self", ".", "_can_order_asset", "(", "asset", ")", ":", "return", "None",...
Place an order by desired value rather than desired number of shares. Parameters ---------- asset : Asset The asset that this order is for. value : float If the requested asset exists, the requested value is divided by its price to imply the n...
[ "Place", "an", "order", "by", "desired", "value", "rather", "than", "desired", "number", "of", "shares", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1363-L1414
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm._sync_last_sale_prices
def _sync_last_sale_prices(self, dt=None): """Sync the last sale prices on the metrics tracker to a given datetime. Parameters ---------- dt : datetime The time to sync the prices to. Notes ----- This call is cached by the datetime. Repeated ...
python
def _sync_last_sale_prices(self, dt=None): """Sync the last sale prices on the metrics tracker to a given datetime. Parameters ---------- dt : datetime The time to sync the prices to. Notes ----- This call is cached by the datetime. Repeated ...
[ "def", "_sync_last_sale_prices", "(", "self", ",", "dt", "=", "None", ")", ":", "if", "dt", "is", "None", ":", "dt", "=", "self", ".", "datetime", "if", "dt", "!=", "self", ".", "_last_sync_time", ":", "self", ".", "metrics_tracker", ".", "sync_last_sale...
Sync the last sale prices on the metrics tracker to a given datetime. Parameters ---------- dt : datetime The time to sync the prices to. Notes ----- This call is cached by the datetime. Repeated calls in the same bar are cheap.
[ "Sync", "the", "last", "sale", "prices", "on", "the", "metrics", "tracker", "to", "a", "given", "datetime", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1420-L1442
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.on_dt_changed
def on_dt_changed(self, dt): """ Callback triggered by the simulation loop whenever the current dt changes. Any logic that should happen exactly once at the start of each datetime group should happen here. """ self.datetime = dt self.blotter.set_date(dt)
python
def on_dt_changed(self, dt): """ Callback triggered by the simulation loop whenever the current dt changes. Any logic that should happen exactly once at the start of each datetime group should happen here. """ self.datetime = dt self.blotter.set_date(dt)
[ "def", "on_dt_changed", "(", "self", ",", "dt", ")", ":", "self", ".", "datetime", "=", "dt", "self", ".", "blotter", ".", "set_date", "(", "dt", ")" ]
Callback triggered by the simulation loop whenever the current dt changes. Any logic that should happen exactly once at the start of each datetime group should happen here.
[ "Callback", "triggered", "by", "the", "simulation", "loop", "whenever", "the", "current", "dt", "changes", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1457-L1466
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.get_datetime
def get_datetime(self, tz=None): """ Returns the current simulation datetime. Parameters ---------- tz : tzinfo or str, optional The timezone to return the datetime in. This defaults to utc. Returns ------- dt : datetime The curre...
python
def get_datetime(self, tz=None): """ Returns the current simulation datetime. Parameters ---------- tz : tzinfo or str, optional The timezone to return the datetime in. This defaults to utc. Returns ------- dt : datetime The curre...
[ "def", "get_datetime", "(", "self", ",", "tz", "=", "None", ")", ":", "dt", "=", "self", ".", "datetime", "assert", "dt", ".", "tzinfo", "==", "pytz", ".", "utc", ",", "\"Algorithm should have a utc datetime\"", "if", "tz", "is", "not", "None", ":", "dt"...
Returns the current simulation datetime. Parameters ---------- tz : tzinfo or str, optional The timezone to return the datetime in. This defaults to utc. Returns ------- dt : datetime The current simulation datetime converted to ``tz``.
[ "Returns", "the", "current", "simulation", "datetime", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1471-L1489
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.set_slippage
def set_slippage(self, us_equities=None, us_futures=None): """Set the slippage models for the simulation. Parameters ---------- us_equities : EquitySlippageModel The slippage model to use for trading US equities. us_futures : FutureSlippageModel The slipp...
python
def set_slippage(self, us_equities=None, us_futures=None): """Set the slippage models for the simulation. Parameters ---------- us_equities : EquitySlippageModel The slippage model to use for trading US equities. us_futures : FutureSlippageModel The slipp...
[ "def", "set_slippage", "(", "self", ",", "us_equities", "=", "None", ",", "us_futures", "=", "None", ")", ":", "if", "self", ".", "initialized", ":", "raise", "SetSlippagePostInit", "(", ")", "if", "us_equities", "is", "not", "None", ":", "if", "Equity", ...
Set the slippage models for the simulation. Parameters ---------- us_equities : EquitySlippageModel The slippage model to use for trading US equities. us_futures : FutureSlippageModel The slippage model to use for trading US futures. See Also ---...
[ "Set", "the", "slippage", "models", "for", "the", "simulation", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1492-L1525
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.set_commission
def set_commission(self, us_equities=None, us_futures=None): """Sets the commission models for the simulation. Parameters ---------- us_equities : EquityCommissionModel The commission model to use for trading US equities. us_futures : FutureCommissionModel ...
python
def set_commission(self, us_equities=None, us_futures=None): """Sets the commission models for the simulation. Parameters ---------- us_equities : EquityCommissionModel The commission model to use for trading US equities. us_futures : FutureCommissionModel ...
[ "def", "set_commission", "(", "self", ",", "us_equities", "=", "None", ",", "us_futures", "=", "None", ")", ":", "if", "self", ".", "initialized", ":", "raise", "SetCommissionPostInit", "(", ")", "if", "us_equities", "is", "not", "None", ":", "if", "Equity...
Sets the commission models for the simulation. Parameters ---------- us_equities : EquityCommissionModel The commission model to use for trading US equities. us_futures : FutureCommissionModel The commission model to use for trading US futures. See Also ...
[ "Sets", "the", "commission", "models", "for", "the", "simulation", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1528-L1563
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.set_cancel_policy
def set_cancel_policy(self, cancel_policy): """Sets the order cancellation policy for the simulation. Parameters ---------- cancel_policy : CancelPolicy The cancellation policy to use. See Also -------- :class:`zipline.api.EODCancel` :class:`...
python
def set_cancel_policy(self, cancel_policy): """Sets the order cancellation policy for the simulation. Parameters ---------- cancel_policy : CancelPolicy The cancellation policy to use. See Also -------- :class:`zipline.api.EODCancel` :class:`...
[ "def", "set_cancel_policy", "(", "self", ",", "cancel_policy", ")", ":", "if", "not", "isinstance", "(", "cancel_policy", ",", "CancelPolicy", ")", ":", "raise", "UnsupportedCancelPolicy", "(", ")", "if", "self", ".", "initialized", ":", "raise", "SetCancelPolic...
Sets the order cancellation policy for the simulation. Parameters ---------- cancel_policy : CancelPolicy The cancellation policy to use. See Also -------- :class:`zipline.api.EODCancel` :class:`zipline.api.NeverCancel`
[ "Sets", "the", "order", "cancellation", "policy", "for", "the", "simulation", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1566-L1585
train