id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
26,000
quantopian/zipline
zipline/utils/input_validation.py
validate_keys
def validate_keys(dict_, expected, funcname): """Validate that a dictionary has an expected set of keys. """ expected = set(expected) received = set(dict_) missing = expected - received if missing: raise ValueError( "Missing keys in {}:\n" "Expected Keys: {}\n" ...
python
def validate_keys(dict_, expected, funcname): """Validate that a dictionary has an expected set of keys. """ expected = set(expected) received = set(dict_) missing = expected - received if missing: raise ValueError( "Missing keys in {}:\n" "Expected Keys: {}\n" ...
[ "def", "validate_keys", "(", "dict_", ",", "expected", ",", "funcname", ")", ":", "expected", "=", "set", "(", "expected", ")", "received", "=", "set", "(", "dict_", ")", "missing", "=", "expected", "-", "received", "if", "missing", ":", "raise", "ValueE...
Validate that a dictionary has an expected set of keys.
[ "Validate", "that", "a", "dictionary", "has", "an", "expected", "set", "of", "keys", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/input_validation.py#L847-L875
26,001
quantopian/zipline
zipline/utils/enum.py
enum
def enum(option, *options): """ Construct a new enum object. Parameters ---------- *options : iterable of str The names of the fields for the enum. Returns ------- enum A new enum collection. Examples -------- >>> e = enum('a', 'b', 'c') >>> e <enum...
python
def enum(option, *options): """ Construct a new enum object. Parameters ---------- *options : iterable of str The names of the fields for the enum. Returns ------- enum A new enum collection. Examples -------- >>> e = enum('a', 'b', 'c') >>> e <enum...
[ "def", "enum", "(", "option", ",", "*", "options", ")", ":", "options", "=", "(", "option", ",", ")", "+", "options", "rangeob", "=", "range", "(", "len", "(", "options", ")", ")", "try", ":", "inttype", "=", "_inttypes", "[", "int", "(", "np", "...
Construct a new enum object. Parameters ---------- *options : iterable of str The names of the fields for the enum. Returns ------- enum A new enum collection. Examples -------- >>> e = enum('a', 'b', 'c') >>> e <enum: ('a', 'b', 'c')> >>> e.a 0 ...
[ "Construct", "a", "new", "enum", "object", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/enum.py#L48-L114
26,002
quantopian/zipline
zipline/utils/data.py
RollingPanel.extend_back
def extend_back(self, missing_dts): """ Resizes the buffer to hold a new window with a new cap_multiple. If cap_multiple is None, then the old cap_multiple is used. """ delta = len(missing_dts) if not delta: raise ValueError( 'missing_dts must...
python
def extend_back(self, missing_dts): """ Resizes the buffer to hold a new window with a new cap_multiple. If cap_multiple is None, then the old cap_multiple is used. """ delta = len(missing_dts) if not delta: raise ValueError( 'missing_dts must...
[ "def", "extend_back", "(", "self", ",", "missing_dts", ")", ":", "delta", "=", "len", "(", "missing_dts", ")", "if", "not", "delta", ":", "raise", "ValueError", "(", "'missing_dts must be a non-empty index'", ",", ")", "self", ".", "_window", "+=", "delta", ...
Resizes the buffer to hold a new window with a new cap_multiple. If cap_multiple is None, then the old cap_multiple is used.
[ "Resizes", "the", "buffer", "to", "hold", "a", "new", "window", "with", "a", "new", "cap_multiple", ".", "If", "cap_multiple", "is", "None", "then", "the", "old", "cap_multiple", "is", "used", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/data.py#L107-L148
26,003
quantopian/zipline
zipline/utils/data.py
RollingPanel.set_current
def set_current(self, panel): """ Set the values stored in our current in-view data to be values of the passed panel. The passed panel must have the same indices as the panel that would be returned by self.get_current. """ where = slice(self._start_index, self._pos) ...
python
def set_current(self, panel): """ Set the values stored in our current in-view data to be values of the passed panel. The passed panel must have the same indices as the panel that would be returned by self.get_current. """ where = slice(self._start_index, self._pos) ...
[ "def", "set_current", "(", "self", ",", "panel", ")", ":", "where", "=", "slice", "(", "self", ".", "_start_index", ",", "self", ".", "_pos", ")", "self", ".", "buffer", ".", "values", "[", ":", ",", "where", ",", ":", "]", "=", "panel", ".", "va...
Set the values stored in our current in-view data to be values of the passed panel. The passed panel must have the same indices as the panel that would be returned by self.get_current.
[ "Set", "the", "values", "stored", "in", "our", "current", "in", "-", "view", "data", "to", "be", "values", "of", "the", "passed", "panel", ".", "The", "passed", "panel", "must", "have", "the", "same", "indices", "as", "the", "panel", "that", "would", "...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/data.py#L216-L223
26,004
quantopian/zipline
zipline/utils/data.py
RollingPanel._roll_data
def _roll_data(self): """ Roll window worth of data up to position zero. Save the effort of having to expensively roll at each iteration """ self.buffer.values[:, :self._window, :] = \ self.buffer.values[:, -self._window:, :] self.date_buf[:self._window] = se...
python
def _roll_data(self): """ Roll window worth of data up to position zero. Save the effort of having to expensively roll at each iteration """ self.buffer.values[:, :self._window, :] = \ self.buffer.values[:, -self._window:, :] self.date_buf[:self._window] = se...
[ "def", "_roll_data", "(", "self", ")", ":", "self", ".", "buffer", ".", "values", "[", ":", ",", ":", "self", ".", "_window", ",", ":", "]", "=", "self", ".", "buffer", ".", "values", "[", ":", ",", "-", "self", ".", "_window", ":", ",", ":", ...
Roll window worth of data up to position zero. Save the effort of having to expensively roll at each iteration
[ "Roll", "window", "worth", "of", "data", "up", "to", "position", "zero", ".", "Save", "the", "effort", "of", "having", "to", "expensively", "roll", "at", "each", "iteration" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/data.py#L229-L238
26,005
quantopian/zipline
zipline/finance/order.py
Order.check_triggers
def check_triggers(self, price, dt): """ Update internal state based on price triggers and the trade event's price. """ stop_reached, limit_reached, sl_stop_reached = \ self.check_order_triggers(price) if (stop_reached, limit_reached) \ != (sel...
python
def check_triggers(self, price, dt): """ Update internal state based on price triggers and the trade event's price. """ stop_reached, limit_reached, sl_stop_reached = \ self.check_order_triggers(price) if (stop_reached, limit_reached) \ != (sel...
[ "def", "check_triggers", "(", "self", ",", "price", ",", "dt", ")", ":", "stop_reached", ",", "limit_reached", ",", "sl_stop_reached", "=", "self", ".", "check_order_triggers", "(", "price", ")", "if", "(", "stop_reached", ",", "limit_reached", ")", "!=", "(...
Update internal state based on price triggers and the trade event's price.
[ "Update", "internal", "state", "based", "on", "price", "triggers", "and", "the", "trade", "event", "s", "price", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/order.py#L108-L122
26,006
quantopian/zipline
zipline/finance/order.py
Order.triggered
def triggered(self): """ For a market order, True. For a stop order, True IFF stop_reached. For a limit order, True IFF limit_reached. """ if self.stop is not None and not self.stop_reached: return False if self.limit is not None and not self.limit_re...
python
def triggered(self): """ For a market order, True. For a stop order, True IFF stop_reached. For a limit order, True IFF limit_reached. """ if self.stop is not None and not self.stop_reached: return False if self.limit is not None and not self.limit_re...
[ "def", "triggered", "(", "self", ")", ":", "if", "self", ".", "stop", "is", "not", "None", "and", "not", "self", ".", "stop_reached", ":", "return", "False", "if", "self", ".", "limit", "is", "not", "None", "and", "not", "self", ".", "limit_reached", ...
For a market order, True. For a stop order, True IFF stop_reached. For a limit order, True IFF limit_reached.
[ "For", "a", "market", "order", "True", ".", "For", "a", "stop", "order", "True", "IFF", "stop_reached", ".", "For", "a", "limit", "order", "True", "IFF", "limit_reached", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/order.py#L230-L242
26,007
quantopian/zipline
zipline/gens/utils.py
hash_args
def hash_args(*args, **kwargs): """Define a unique string for any set of representable args.""" arg_string = '_'.join([str(arg) for arg in args]) kwarg_string = '_'.join([str(key) + '=' + str(value) for key, value in iteritems(kwargs)]) combined = ':'.join([arg_string, kwarg...
python
def hash_args(*args, **kwargs): """Define a unique string for any set of representable args.""" arg_string = '_'.join([str(arg) for arg in args]) kwarg_string = '_'.join([str(key) + '=' + str(value) for key, value in iteritems(kwargs)]) combined = ':'.join([arg_string, kwarg...
[ "def", "hash_args", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "arg_string", "=", "'_'", ".", "join", "(", "[", "str", "(", "arg", ")", "for", "arg", "in", "args", "]", ")", "kwarg_string", "=", "'_'", ".", "join", "(", "[", "str", "(...
Define a unique string for any set of representable args.
[ "Define", "a", "unique", "string", "for", "any", "set", "of", "representable", "args", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/gens/utils.py#L27-L36
26,008
quantopian/zipline
zipline/gens/utils.py
assert_datasource_protocol
def assert_datasource_protocol(event): """Assert that an event meets the protocol for datasource outputs.""" assert event.type in DATASOURCE_TYPE # Done packets have no dt. if not event.type == DATASOURCE_TYPE.DONE: assert isinstance(event.dt, datetime) assert event.dt.tzinfo == pytz.u...
python
def assert_datasource_protocol(event): """Assert that an event meets the protocol for datasource outputs.""" assert event.type in DATASOURCE_TYPE # Done packets have no dt. if not event.type == DATASOURCE_TYPE.DONE: assert isinstance(event.dt, datetime) assert event.dt.tzinfo == pytz.u...
[ "def", "assert_datasource_protocol", "(", "event", ")", ":", "assert", "event", ".", "type", "in", "DATASOURCE_TYPE", "# Done packets have no dt.", "if", "not", "event", ".", "type", "==", "DATASOURCE_TYPE", ".", "DONE", ":", "assert", "isinstance", "(", "event", ...
Assert that an event meets the protocol for datasource outputs.
[ "Assert", "that", "an", "event", "meets", "the", "protocol", "for", "datasource", "outputs", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/gens/utils.py#L39-L47
26,009
quantopian/zipline
zipline/gens/utils.py
assert_trade_protocol
def assert_trade_protocol(event): """Assert that an event meets the protocol for datasource TRADE outputs.""" assert_datasource_protocol(event) assert event.type == DATASOURCE_TYPE.TRADE assert isinstance(event.price, numbers.Real) assert isinstance(event.volume, numbers.Integral) assert isinst...
python
def assert_trade_protocol(event): """Assert that an event meets the protocol for datasource TRADE outputs.""" assert_datasource_protocol(event) assert event.type == DATASOURCE_TYPE.TRADE assert isinstance(event.price, numbers.Real) assert isinstance(event.volume, numbers.Integral) assert isinst...
[ "def", "assert_trade_protocol", "(", "event", ")", ":", "assert_datasource_protocol", "(", "event", ")", "assert", "event", ".", "type", "==", "DATASOURCE_TYPE", ".", "TRADE", "assert", "isinstance", "(", "event", ".", "price", ",", "numbers", ".", "Real", ")"...
Assert that an event meets the protocol for datasource TRADE outputs.
[ "Assert", "that", "an", "event", "meets", "the", "protocol", "for", "datasource", "TRADE", "outputs", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/gens/utils.py#L50-L57
26,010
quantopian/zipline
zipline/gens/composites.py
date_sorted_sources
def date_sorted_sources(*sources): """ Takes an iterable of sources, generating namestrings and piping their output into date_sort. """ sorted_stream = heapq.merge(*(_decorate_source(s) for s in sources)) # Strip out key decoration for _, message in sorted_stream: yield message
python
def date_sorted_sources(*sources): """ Takes an iterable of sources, generating namestrings and piping their output into date_sort. """ sorted_stream = heapq.merge(*(_decorate_source(s) for s in sources)) # Strip out key decoration for _, message in sorted_stream: yield message
[ "def", "date_sorted_sources", "(", "*", "sources", ")", ":", "sorted_stream", "=", "heapq", ".", "merge", "(", "*", "(", "_decorate_source", "(", "s", ")", "for", "s", "in", "sources", ")", ")", "# Strip out key decoration", "for", "_", ",", "message", "in...
Takes an iterable of sources, generating namestrings and piping their output into date_sort.
[ "Takes", "an", "iterable", "of", "sources", "generating", "namestrings", "and", "piping", "their", "output", "into", "date_sort", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/gens/composites.py#L24-L33
26,011
quantopian/zipline
zipline/utils/factory.py
create_daily_trade_source
def create_daily_trade_source(sids, sim_params, asset_finder, trading_calendar): """ creates trade_count trades for each sid in sids list. first trade will be on sim_params.start_session, and daily thereafter for e...
python
def create_daily_trade_source(sids, sim_params, asset_finder, trading_calendar): """ creates trade_count trades for each sid in sids list. first trade will be on sim_params.start_session, and daily thereafter for e...
[ "def", "create_daily_trade_source", "(", "sids", ",", "sim_params", ",", "asset_finder", ",", "trading_calendar", ")", ":", "return", "create_trade_source", "(", "sids", ",", "timedelta", "(", "days", "=", "1", ")", ",", "sim_params", ",", "asset_finder", ",", ...
creates trade_count trades for each sid in sids list. first trade will be on sim_params.start_session, and daily thereafter for each sid. Thus, two sids should result in two trades per day.
[ "creates", "trade_count", "trades", "for", "each", "sid", "in", "sids", "list", ".", "first", "trade", "will", "be", "on", "sim_params", ".", "start_session", "and", "daily", "thereafter", "for", "each", "sid", ".", "Thus", "two", "sids", "should", "result",...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/factory.py#L115-L131
26,012
quantopian/zipline
zipline/data/bundles/quandl.py
load_data_table
def load_data_table(file, index_col, show_progress=False): """ Load data table from zip file provided by Quandl. """ with ZipFile(file) as zip_file: file_names = zip_file.namelist() assert len(file_names) == 1, "Expected a single file from Quandl." ...
python
def load_data_table(file, index_col, show_progress=False): """ Load data table from zip file provided by Quandl. """ with ZipFile(file) as zip_file: file_names = zip_file.namelist() assert len(file_names) == 1, "Expected a single file from Quandl." ...
[ "def", "load_data_table", "(", "file", ",", "index_col", ",", "show_progress", "=", "False", ")", ":", "with", "ZipFile", "(", "file", ")", "as", "zip_file", ":", "file_names", "=", "zip_file", ".", "namelist", "(", ")", "assert", "len", "(", "file_names",...
Load data table from zip file provided by Quandl.
[ "Load", "data", "table", "from", "zip", "file", "provided", "by", "Quandl", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/bundles/quandl.py#L38-L75
26,013
quantopian/zipline
zipline/data/bundles/quandl.py
fetch_data_table
def fetch_data_table(api_key, show_progress, retries): """ Fetch WIKI Prices data table from Quandl """ for _ in range(retries): try: if show_progress: log.info('Downloading WIKI metadata.') metadata = pd.read_csv( ...
python
def fetch_data_table(api_key, show_progress, retries): """ Fetch WIKI Prices data table from Quandl """ for _ in range(retries): try: if show_progress: log.info('Downloading WIKI metadata.') metadata = pd.read_csv( ...
[ "def", "fetch_data_table", "(", "api_key", ",", "show_progress", ",", "retries", ")", ":", "for", "_", "in", "range", "(", "retries", ")", ":", "try", ":", "if", "show_progress", ":", "log", ".", "info", "(", "'Downloading WIKI metadata.'", ")", "metadata", ...
Fetch WIKI Prices data table from Quandl
[ "Fetch", "WIKI", "Prices", "data", "table", "from", "Quandl" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/bundles/quandl.py#L78-L114
26,014
quantopian/zipline
zipline/data/bundles/quandl.py
quandl_bundle
def quandl_bundle(environ, asset_db_writer, minute_bar_writer, daily_bar_writer, adjustment_writer, calendar, start_session, end_session, cache, show_progress...
python
def quandl_bundle(environ, asset_db_writer, minute_bar_writer, daily_bar_writer, adjustment_writer, calendar, start_session, end_session, cache, show_progress...
[ "def", "quandl_bundle", "(", "environ", ",", "asset_db_writer", ",", "minute_bar_writer", ",", "daily_bar_writer", ",", "adjustment_writer", ",", "calendar", ",", "start_session", ",", "end_session", ",", "cache", ",", "show_progress", ",", "output_dir", ")", ":", ...
quandl_bundle builds a daily dataset using Quandl's WIKI Prices dataset. For more information on Quandl's API and how to obtain an API key, please visit https://docs.quandl.com/docs#section-authentication
[ "quandl_bundle", "builds", "a", "daily", "dataset", "using", "Quandl", "s", "WIKI", "Prices", "dataset", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/bundles/quandl.py#L183-L250
26,015
quantopian/zipline
zipline/data/bundles/quandl.py
download_with_progress
def download_with_progress(url, chunk_size, **progress_kwargs): """ Download streaming data from a URL, printing progress information to the terminal. Parameters ---------- url : str A URL that can be understood by ``requests.get``. chunk_size : int Number of bytes to read a...
python
def download_with_progress(url, chunk_size, **progress_kwargs): """ Download streaming data from a URL, printing progress information to the terminal. Parameters ---------- url : str A URL that can be understood by ``requests.get``. chunk_size : int Number of bytes to read a...
[ "def", "download_with_progress", "(", "url", ",", "chunk_size", ",", "*", "*", "progress_kwargs", ")", ":", "resp", "=", "requests", ".", "get", "(", "url", ",", "stream", "=", "True", ")", "resp", ".", "raise_for_status", "(", ")", "total_size", "=", "i...
Download streaming data from a URL, printing progress information to the terminal. Parameters ---------- url : str A URL that can be understood by ``requests.get``. chunk_size : int Number of bytes to read at a time from requests. **progress_kwargs Forwarded to click.pro...
[ "Download", "streaming", "data", "from", "a", "URL", "printing", "progress", "information", "to", "the", "terminal", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/bundles/quandl.py#L253-L283
26,016
quantopian/zipline
zipline/data/bundles/quandl.py
download_without_progress
def download_without_progress(url): """ Download data from a URL, returning a BytesIO containing the loaded data. Parameters ---------- url : str A URL that can be understood by ``requests.get``. Returns ------- data : BytesIO A BytesIO containing the downloaded data. ...
python
def download_without_progress(url): """ Download data from a URL, returning a BytesIO containing the loaded data. Parameters ---------- url : str A URL that can be understood by ``requests.get``. Returns ------- data : BytesIO A BytesIO containing the downloaded data. ...
[ "def", "download_without_progress", "(", "url", ")", ":", "resp", "=", "requests", ".", "get", "(", "url", ")", "resp", ".", "raise_for_status", "(", ")", "return", "BytesIO", "(", "resp", ".", "content", ")" ]
Download data from a URL, returning a BytesIO containing the loaded data. Parameters ---------- url : str A URL that can be understood by ``requests.get``. Returns ------- data : BytesIO A BytesIO containing the downloaded data.
[ "Download", "data", "from", "a", "URL", "returning", "a", "BytesIO", "containing", "the", "loaded", "data", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/bundles/quandl.py#L286-L302
26,017
quantopian/zipline
zipline/data/resample.py
minute_frame_to_session_frame
def minute_frame_to_session_frame(minute_frame, calendar): """ Resample a DataFrame with minute data into the frame expected by a BcolzDailyBarWriter. Parameters ---------- minute_frame : pd.DataFrame A DataFrame with the columns `open`, `high`, `low`, `close`, `volume`, and `d...
python
def minute_frame_to_session_frame(minute_frame, calendar): """ Resample a DataFrame with minute data into the frame expected by a BcolzDailyBarWriter. Parameters ---------- minute_frame : pd.DataFrame A DataFrame with the columns `open`, `high`, `low`, `close`, `volume`, and `d...
[ "def", "minute_frame_to_session_frame", "(", "minute_frame", ",", "calendar", ")", ":", "how", "=", "OrderedDict", "(", "(", "c", ",", "_MINUTE_TO_SESSION_OHCLV_HOW", "[", "c", "]", ")", "for", "c", "in", "minute_frame", ".", "columns", ")", "labels", "=", "...
Resample a DataFrame with minute data into the frame expected by a BcolzDailyBarWriter. Parameters ---------- minute_frame : pd.DataFrame A DataFrame with the columns `open`, `high`, `low`, `close`, `volume`, and `dt` (minute dts) calendar : trading_calendars.trading_calendar.Tradin...
[ "Resample", "a", "DataFrame", "with", "minute", "data", "into", "the", "frame", "expected", "by", "a", "BcolzDailyBarWriter", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/resample.py#L42-L66
26,018
quantopian/zipline
zipline/data/resample.py
minute_to_session
def minute_to_session(column, close_locs, data, out): """ Resample an array with minute data into an array with session data. This function assumes that the minute data is the exact length of all minutes in the sessions in the output. Parameters ---------- column : str The `open`, ...
python
def minute_to_session(column, close_locs, data, out): """ Resample an array with minute data into an array with session data. This function assumes that the minute data is the exact length of all minutes in the sessions in the output. Parameters ---------- column : str The `open`, ...
[ "def", "minute_to_session", "(", "column", ",", "close_locs", ",", "data", ",", "out", ")", ":", "if", "column", "==", "'open'", ":", "_minute_to_session_open", "(", "close_locs", ",", "data", ",", "out", ")", "elif", "column", "==", "'high'", ":", "_minut...
Resample an array with minute data into an array with session data. This function assumes that the minute data is the exact length of all minutes in the sessions in the output. Parameters ---------- column : str The `open`, `high`, `low`, `close`, or `volume` column. close_locs : array...
[ "Resample", "an", "array", "with", "minute", "data", "into", "an", "array", "with", "session", "data", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/resample.py#L69-L100
26,019
quantopian/zipline
zipline/data/resample.py
DailyHistoryAggregator.opens
def opens(self, assets, dt): """ The open field's aggregation returns the first value that occurs for the day, if there has been no data on or before the `dt` the open is `nan`. Once the first non-nan open is seen, that value remains constant per asset for the remainder ...
python
def opens(self, assets, dt): """ The open field's aggregation returns the first value that occurs for the day, if there has been no data on or before the `dt` the open is `nan`. Once the first non-nan open is seen, that value remains constant per asset for the remainder ...
[ "def", "opens", "(", "self", ",", "assets", ",", "dt", ")", ":", "market_open", ",", "prev_dt", ",", "dt_value", ",", "entries", "=", "self", ".", "_prelude", "(", "dt", ",", "'open'", ")", "opens", "=", "[", "]", "session_label", "=", "self", ".", ...
The open field's aggregation returns the first value that occurs for the day, if there has been no data on or before the `dt` the open is `nan`. Once the first non-nan open is seen, that value remains constant per asset for the remainder of the day. Returns ------- ...
[ "The", "open", "field", "s", "aggregation", "returns", "the", "first", "value", "that", "occurs", "for", "the", "day", "if", "there", "has", "been", "no", "data", "on", "or", "before", "the", "dt", "the", "open", "is", "nan", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/resample.py#L167-L237
26,020
quantopian/zipline
zipline/data/resample.py
DailyHistoryAggregator.highs
def highs(self, assets, dt): """ The high field's aggregation returns the largest high seen between the market open and the current dt. If there has been no data on or before the `dt` the high is `nan`. Returns ------- np.array with dtype=float64, in order of ass...
python
def highs(self, assets, dt): """ The high field's aggregation returns the largest high seen between the market open and the current dt. If there has been no data on or before the `dt` the high is `nan`. Returns ------- np.array with dtype=float64, in order of ass...
[ "def", "highs", "(", "self", ",", "assets", ",", "dt", ")", ":", "market_open", ",", "prev_dt", ",", "dt_value", ",", "entries", "=", "self", ".", "_prelude", "(", "dt", ",", "'high'", ")", "highs", "=", "[", "]", "session_label", "=", "self", ".", ...
The high field's aggregation returns the largest high seen between the market open and the current dt. If there has been no data on or before the `dt` the high is `nan`. Returns ------- np.array with dtype=float64, in order of assets parameter.
[ "The", "high", "field", "s", "aggregation", "returns", "the", "largest", "high", "seen", "between", "the", "market", "open", "and", "the", "current", "dt", ".", "If", "there", "has", "been", "no", "data", "on", "or", "before", "the", "dt", "the", "high",...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/resample.py#L239-L306
26,021
quantopian/zipline
zipline/data/resample.py
DailyHistoryAggregator.lows
def lows(self, assets, dt): """ The low field's aggregation returns the smallest low seen between the market open and the current dt. If there has been no data on or before the `dt` the low is `nan`. Returns ------- np.array with dtype=float64, in order of assets...
python
def lows(self, assets, dt): """ The low field's aggregation returns the smallest low seen between the market open and the current dt. If there has been no data on or before the `dt` the low is `nan`. Returns ------- np.array with dtype=float64, in order of assets...
[ "def", "lows", "(", "self", ",", "assets", ",", "dt", ")", ":", "market_open", ",", "prev_dt", ",", "dt_value", ",", "entries", "=", "self", ".", "_prelude", "(", "dt", ",", "'low'", ")", "lows", "=", "[", "]", "session_label", "=", "self", ".", "_...
The low field's aggregation returns the smallest low seen between the market open and the current dt. If there has been no data on or before the `dt` the low is `nan`. Returns ------- np.array with dtype=float64, in order of assets parameter.
[ "The", "low", "field", "s", "aggregation", "returns", "the", "smallest", "low", "seen", "between", "the", "market", "open", "and", "the", "current", "dt", ".", "If", "there", "has", "been", "no", "data", "on", "or", "before", "the", "dt", "the", "low", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/resample.py#L308-L370
26,022
quantopian/zipline
zipline/data/resample.py
DailyHistoryAggregator.closes
def closes(self, assets, dt): """ The close field's aggregation returns the latest close at the given dt. If the close for the given dt is `nan`, the most recent non-nan `close` is used. If there has been no data on or before the `dt` the close is `nan`. Returns ...
python
def closes(self, assets, dt): """ The close field's aggregation returns the latest close at the given dt. If the close for the given dt is `nan`, the most recent non-nan `close` is used. If there has been no data on or before the `dt` the close is `nan`. Returns ...
[ "def", "closes", "(", "self", ",", "assets", ",", "dt", ")", ":", "market_open", ",", "prev_dt", ",", "dt_value", ",", "entries", "=", "self", ".", "_prelude", "(", "dt", ",", "'close'", ")", "closes", "=", "[", "]", "session_label", "=", "self", "."...
The close field's aggregation returns the latest close at the given dt. If the close for the given dt is `nan`, the most recent non-nan `close` is used. If there has been no data on or before the `dt` the close is `nan`. Returns ------- np.array with dtype=float6...
[ "The", "close", "field", "s", "aggregation", "returns", "the", "latest", "close", "at", "the", "given", "dt", ".", "If", "the", "close", "for", "the", "given", "dt", "is", "nan", "the", "most", "recent", "non", "-", "nan", "close", "is", "used", ".", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/resample.py#L372-L446
26,023
quantopian/zipline
zipline/data/resample.py
DailyHistoryAggregator.volumes
def volumes(self, assets, dt): """ The volume field's aggregation returns the sum of all volumes between the market open and the `dt` If there has been no data on or before the `dt` the volume is 0. Returns ------- np.array with dtype=int64, in order of assets pa...
python
def volumes(self, assets, dt): """ The volume field's aggregation returns the sum of all volumes between the market open and the `dt` If there has been no data on or before the `dt` the volume is 0. Returns ------- np.array with dtype=int64, in order of assets pa...
[ "def", "volumes", "(", "self", ",", "assets", ",", "dt", ")", ":", "market_open", ",", "prev_dt", ",", "dt_value", ",", "entries", "=", "self", ".", "_prelude", "(", "dt", ",", "'volume'", ")", "volumes", "=", "[", "]", "session_label", "=", "self", ...
The volume field's aggregation returns the sum of all volumes between the market open and the `dt` If there has been no data on or before the `dt` the volume is 0. Returns ------- np.array with dtype=int64, in order of assets parameter.
[ "The", "volume", "field", "s", "aggregation", "returns", "the", "sum", "of", "all", "volumes", "between", "the", "market", "open", "and", "the", "dt", "If", "there", "has", "been", "no", "data", "on", "or", "before", "the", "dt", "the", "volume", "is", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/resample.py#L448-L510
26,024
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
26,025
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
26,026
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
26,027
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
26,028
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
26,029
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
26,030
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
26,031
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
26,032
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
26,033
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
26,034
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
26,035
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
26,036
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
26,037
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
26,038
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
26,039
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
26,040
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
26,041
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
26,042
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
26,043
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
26,044
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
26,045
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
26,046
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
26,047
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
26,048
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
26,049
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
26,050
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
26,051
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
26,052
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
26,053
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
26,054
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
26,055
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
26,056
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
26,057
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
26,058
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
26,059
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
26,060
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
26,061
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
26,062
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
26,063
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
26,064
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
26,065
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
26,066
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
26,067
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
26,068
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
26,069
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
26,070
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
26,071
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
26,072
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
26,073
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
26,074
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
26,075
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
26,076
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
26,077
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
26,078
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
26,079
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
26,080
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
26,081
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
26,082
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
26,083
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
26,084
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
26,085
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
26,086
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
26,087
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
26,088
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
26,089
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
26,090
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
26,091
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
26,092
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
26,093
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
26,094
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
26,095
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
26,096
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
26,097
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
26,098
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
26,099
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