partition stringclasses 3
values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1
value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
train | check_version_info | 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... | zipline/assets/asset_writer.py | 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):
"""
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... | [
"Checks",
"for",
"a",
"version",
"value",
"in",
"the",
"version",
"table",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/asset_writer.py#L392-L423 | [
"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... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | write_version_info | 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 | zipline/assets/asset_writer.py | 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):
"""
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... | [
"Inserts",
"the",
"version",
"value",
"in",
"to",
"the",
"version",
"table",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/asset_writer.py#L426-L440 | [
"def",
"write_version_info",
"(",
"conn",
",",
"version_table",
",",
"version_value",
")",
":",
"conn",
".",
"execute",
"(",
"sa",
".",
"insert",
"(",
"version_table",
",",
"values",
"=",
"{",
"'version'",
":",
"version_value",
"}",
")",
")"
] | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | AssetDBWriter.write_direct | 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... | zipline/assets/asset_writer.py | 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,
chunk_size=DEFAULT_CH... | [
"Write",
"asset",
"metadata",
"to",
"a",
"sqlite",
"database",
"in",
"the",
"format",
"that",
"it",
"is",
"stored",
"in",
"the",
"assets",
"db",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/asset_writer.py#L514-L668 | [
"def",
"write_direct",
"(",
"self",
",",
"equities",
"=",
"None",
",",
"equity_symbol_mappings",
"=",
"None",
",",
"equity_supplementary_mappings",
"=",
"None",
",",
"futures",
"=",
"None",
",",
"exchanges",
"=",
"None",
",",
"root_symbols",
"=",
"None",
",",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | AssetDBWriter.write | 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
... | zipline/assets/asset_writer.py | 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
------... | [
"Write",
"asset",
"metadata",
"to",
"a",
"sqlite",
"database",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/asset_writer.py#L670-L797 | [
"def",
"write",
"(",
"self",
",",
"equities",
"=",
"None",
",",
"futures",
"=",
"None",
",",
"exchanges",
"=",
"None",
",",
"root_symbols",
"=",
"None",
",",
"equity_supplementary_mappings",
"=",
"None",
",",
"chunk_size",
"=",
"DEFAULT_CHUNK_SIZE",
")",
":"... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | AssetDBWriter._all_tables_present | 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. | zipline/assets/asset_writer.py | 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):
"""
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... | [
"Checks",
"if",
"any",
"tables",
"are",
"present",
"in",
"the",
"current",
"assets",
"database",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/asset_writer.py#L856-L874 | [
"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",
")",
":"... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | AssetDBWriter.init_db | 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... | zipline/assets/asset_writer.py | 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):
"""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
... | [
"Connect",
"to",
"database",
"and",
"create",
"tables",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/asset_writer.py#L876-L902 | [
"def",
"init_db",
"(",
"self",
",",
"txn",
"=",
"None",
")",
":",
"with",
"ExitStack",
"(",
")",
"as",
"stack",
":",
"if",
"txn",
"is",
"None",
":",
"txn",
"=",
"stack",
".",
"enter_context",
"(",
"self",
".",
"engine",
".",
"begin",
"(",
")",
")... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | AssetDBWriter._load_data | Returns a standard set of pandas.DataFrames:
equities, futures, exchanges, root_symbols | zipline/assets/asset_writer.py | def _load_data(self,
equities,
futures,
exchanges,
root_symbols,
equity_supplementary_mappings):
"""
Returns a standard set of pandas.DataFrames:
equities, futures, exchanges, root_symbols
"""
... | def _load_data(self,
equities,
futures,
exchanges,
root_symbols,
equity_supplementary_mappings):
"""
Returns a standard set of pandas.DataFrames:
equities, futures, exchanges, root_symbols
"""
... | [
"Returns",
"a",
"standard",
"set",
"of",
"pandas",
".",
"DataFrames",
":",
"equities",
"futures",
"exchanges",
"root_symbols"
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/asset_writer.py#L970-L1019 | [
"def",
"_load_data",
"(",
"self",
",",
"equities",
",",
"futures",
",",
"exchanges",
",",
"root_symbols",
",",
"equity_supplementary_mappings",
")",
":",
"# Set named identifier columns as indices, if provided.",
"_normalize_index_columns_in_place",
"(",
"equities",
"=",
"e... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | load_raw_data | 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
... | zipline/pipeline/loaders/blaze/utils.py | 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):
"""
Given an expression representing data to load, perform normalization and
forward-filling and return the data, materialized. Only accepts data wi... | [
"Given",
"an",
"expression",
"representing",
"data",
"to",
"load",
"perform",
"normalization",
"and",
"forward",
"-",
"filling",
"and",
"return",
"the",
"data",
"materialized",
".",
"Only",
"accepts",
"data",
"with",
"a",
"sid",
"field",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/blaze/utils.py#L5-L48 | [
"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",
"=... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | from_tuple | 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. | zipline/utils/range.py | 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):
"""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... | [
"Convert",
"a",
"tuple",
"into",
"a",
"range",
"with",
"error",
"handling",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/range.py#L151-L176 | [
"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",
",",
")",... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | maybe_from_tuple | 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... | zipline/utils/range.py | 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):
"""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... | [
"Convert",
"a",
"tuple",
"into",
"a",
"range",
"but",
"pass",
"ranges",
"through",
"silently",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/range.py#L179-L212 | [
"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... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | _check_steps | 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. | zipline/utils/range.py | 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):
"""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:
... | [
"Check",
"that",
"the",
"steps",
"of",
"a",
"and",
"b",
"are",
"both",
"1",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/range.py#L215-L233 | [
"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",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | overlap | 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. | zipline/utils/range.py | 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 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 != ... | [
"Check",
"if",
"two",
"ranges",
"overlap",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/range.py#L236-L256 | [
"def",
"overlap",
"(",
"a",
",",
"b",
")",
":",
"_check_steps",
"(",
"a",
",",
"b",
")",
"return",
"a",
".",
"stop",
">=",
"b",
".",
"start",
"and",
"b",
".",
"stop",
">=",
"a",
".",
"start"
] | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | merge | Merge two ranges with step == 1.
Parameters
----------
a : range
The first range.
b : range
The second range. | zipline/utils/range.py | 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):
"""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)) | [
"Merge",
"two",
"ranges",
"with",
"step",
"==",
"1",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/range.py#L259-L270 | [
"def",
"merge",
"(",
"a",
",",
"b",
")",
":",
"_check_steps",
"(",
"a",
",",
"b",
")",
"return",
"range",
"(",
"min",
"(",
"a",
".",
"start",
",",
"b",
".",
"start",
")",
",",
"max",
"(",
"a",
".",
"stop",
",",
"b",
".",
"stop",
")",
")"
] | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | _combine | helper for ``_group_ranges`` | zipline/utils/range.py | 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):
"""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:
... | [
"helper",
"for",
"_group_ranges"
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/range.py#L273-L290 | [
"def",
"_combine",
"(",
"n",
",",
"rs",
")",
":",
"try",
":",
"r",
",",
"rs",
"=",
"peek",
"(",
"rs",
")",
"except",
"StopIteration",
":",
"yield",
"n",
"return",
"if",
"overlap",
"(",
"n",
",",
"r",
")",
":",
"yield",
"merge",
"(",
"n",
",",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | intersecting_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
--------
>>>... | zipline/utils/range.py | 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):
"""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... | [
"Return",
"any",
"ranges",
"that",
"intersect",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/range.py#L336-L364 | [
"def",
"intersecting_ranges",
"(",
"ranges",
")",
":",
"ranges",
"=",
"sorted",
"(",
"ranges",
",",
"key",
"=",
"op",
".",
"attrgetter",
"(",
"'start'",
")",
")",
"return",
"sorted_diff",
"(",
"ranges",
",",
"group_ranges",
"(",
"ranges",
")",
")"
] | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | get_data_filepath | Returns a handle to data file.
Creates containing directory, if needed. | zipline/data/loader.py | 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):
"""
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) | [
"Returns",
"a",
"handle",
"to",
"data",
"file",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/loader.py#L52-L63 | [
"def",
"get_data_filepath",
"(",
"name",
",",
"environ",
"=",
"None",
")",
":",
"dr",
"=",
"data_root",
"(",
"environ",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dr",
")",
":",
"os",
".",
"makedirs",
"(",
"dr",
")",
"return",
"os",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | has_data_for_dates | Does `series_or_df` have data on or before first_date and on or after
last_date? | zipline/data/loader.py | 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):
"""
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))
... | [
"Does",
"series_or_df",
"have",
"data",
"on",
"or",
"before",
"first_date",
"and",
"on",
"or",
"after",
"last_date?"
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/loader.py#L78-L87 | [
"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... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | load_market_data | 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... | zipline/data/loader.py | 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):
"""
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... | [
"Load",
"benchmark",
"returns",
"and",
"treasury",
"yield",
"curves",
"for",
"the",
"given",
"calendar",
"and",
"benchmark",
"symbol",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/loader.py#L90-L166 | [
"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'",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | ensure_benchmark_data | 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... | zipline/data/loader.py | 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):
"""
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... | [
"Ensure",
"we",
"have",
"benchmark",
"data",
"for",
"symbol",
"from",
"first_date",
"to",
"last_date"
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/loader.py#L169-L229 | [
"def",
"ensure_benchmark_data",
"(",
"symbol",
",",
"first_date",
",",
"last_date",
",",
"now",
",",
"trading_day",
",",
"environ",
"=",
"None",
")",
":",
"filename",
"=",
"get_benchmark_filename",
"(",
"symbol",
")",
"data",
"=",
"_load_cached_data",
"(",
"fi... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | ensure_treasury_data | 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
... | zipline/data/loader.py | 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):
"""
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... | [
"Ensure",
"we",
"have",
"treasury",
"data",
"from",
"treasury",
"module",
"associated",
"with",
"symbol",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/loader.py#L232-L292 | [
"def",
"ensure_treasury_data",
"(",
"symbol",
",",
"first_date",
",",
"last_date",
",",
"now",
",",
"environ",
"=",
"None",
")",
":",
"loader_module",
",",
"filename",
",",
"source",
"=",
"INDEX_MAPPING",
".",
"get",
"(",
"symbol",
",",
"INDEX_MAPPING",
"[",... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | maybe_specialize | Specialize a term if it's loadable. | zipline/pipeline/graph.py | 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):
"""Specialize a term if it's loadable.
"""
if isinstance(term, LoadableTerm):
return term.specialize(domain)
return term | [
"Specialize",
"a",
"term",
"if",
"it",
"s",
"loadable",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/graph.py#L498-L503 | [
"def",
"maybe_specialize",
"(",
"term",
",",
"domain",
")",
":",
"if",
"isinstance",
"(",
"term",
",",
"LoadableTerm",
")",
":",
"return",
"term",
".",
"specialize",
"(",
"domain",
")",
"return",
"term"
] | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TermGraph._add_to_graph | 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. | zipline/pipeline/graph.py | 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):
"""
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(
... | [
"Add",
"a",
"term",
"and",
"all",
"its",
"children",
"to",
"graph",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/graph.py#L69-L95 | [
"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 ... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TermGraph.execution_order | Return a topologically-sorted iterator over the terms in ``self`` which
need to be computed. | zipline/pipeline/graph.py | 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 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 >... | [
"Return",
"a",
"topologically",
"-",
"sorted",
"iterator",
"over",
"the",
"terms",
"in",
"self",
"which",
"need",
"to",
"be",
"computed",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/graph.py#L110-L119 | [
"def",
"execution_order",
"(",
"self",
",",
"refcounts",
")",
":",
"return",
"iter",
"(",
"nx",
".",
"topological_sort",
"(",
"self",
".",
"graph",
".",
"subgraph",
"(",
"{",
"term",
"for",
"term",
",",
"refcount",
"in",
"refcounts",
".",
"items",
"(",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TermGraph.initial_refcounts | 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 ... | zipline/pipeline/graph.py | 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):
"""
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... | [
"Calculate",
"initial",
"refcounts",
"for",
"execution",
"of",
"this",
"graph",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/graph.py#L143-L163 | [
"def",
"initial_refcounts",
"(",
"self",
",",
"initial_terms",
")",
":",
"refcounts",
"=",
"self",
".",
"graph",
".",
"out_degree",
"(",
")",
"for",
"t",
"in",
"self",
".",
"outputs",
".",
"values",
"(",
")",
":",
"refcounts",
"[",
"t",
"]",
"+=",
"1... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TermGraph._decref_dependencies_recursive | 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` | zipline/pipeline/graph.py | 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):
"""
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",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/graph.py#L165-L182 | [
"def",
"_decref_dependencies_recursive",
"(",
"self",
",",
"term",
",",
"refcounts",
",",
"garbage",
")",
":",
"# Edges are tuple of (from, to).",
"for",
"parent",
",",
"_",
"in",
"self",
".",
"graph",
".",
"in_edges",
"(",
"[",
"term",
"]",
")",
":",
"refco... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TermGraph.decref_dependencies | 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]
... | zipline/pipeline/graph.py | 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):
"""
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... | [
"Decrement",
"in",
"-",
"edges",
"for",
"term",
"after",
"computation",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/graph.py#L184-L208 | [
"def",
"decref_dependencies",
"(",
"self",
",",
"term",
",",
"refcounts",
")",
":",
"garbage",
"=",
"set",
"(",
")",
"# Edges are tuple of (from, to).",
"for",
"parent",
",",
"_",
"in",
"self",
".",
"graph",
".",
"in_edges",
"(",
"[",
"term",
"]",
")",
"... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | ExecutionPlan.offset | For all pairs (term, input) such that `input` is an input to `term`,
compute a mapping::
(term, input) -> offset(term, input)
where ``offset(term, input)`` is the number of rows that ``term``
should truncate off the raw array produced for ``input`` before using
it. We compu... | zipline/pipeline/graph.py | def offset(self):
"""
For all pairs (term, input) such that `input` is an input to `term`,
compute a mapping::
(term, input) -> offset(term, input)
where ``offset(term, input)`` is the number of rows that ``term``
should truncate off the raw array produced for ``inp... | def offset(self):
"""
For all pairs (term, input) such that `input` is an input to `term`,
compute a mapping::
(term, input) -> offset(term, input)
where ``offset(term, input)`` is the number of rows that ``term``
should truncate off the raw array produced for ``inp... | [
"For",
"all",
"pairs",
"(",
"term",
"input",
")",
"such",
"that",
"input",
"is",
"an",
"input",
"to",
"term",
"compute",
"a",
"mapping",
"::"
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/graph.py#L324-L403 | [
"def",
"offset",
"(",
"self",
")",
":",
"extra",
"=",
"self",
".",
"extra_rows",
"out",
"=",
"{",
"}",
"for",
"term",
"in",
"self",
".",
"graph",
":",
"for",
"dep",
",",
"requested_extra_rows",
"in",
"term",
".",
"dependencies",
".",
"items",
"(",
")... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | ExecutionPlan.extra_rows | A dict mapping `term` -> `# of extra rows to load/compute of `term`.
Notes
----
This value depends on the other terms in the graph that require `term`
**as an input**. This is not to be confused with `term.dependencies`,
which describes how many additional rows of `term`'s inpu... | zipline/pipeline/graph.py | def extra_rows(self):
"""
A dict mapping `term` -> `# of extra rows to load/compute of `term`.
Notes
----
This value depends on the other terms in the graph that require `term`
**as an input**. This is not to be confused with `term.dependencies`,
which describes... | def extra_rows(self):
"""
A dict mapping `term` -> `# of extra rows to load/compute of `term`.
Notes
----
This value depends on the other terms in the graph that require `term`
**as an input**. This is not to be confused with `term.dependencies`,
which describes... | [
"A",
"dict",
"mapping",
"term",
"-",
">",
"#",
"of",
"extra",
"rows",
"to",
"load",
"/",
"compute",
"of",
"term",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/graph.py#L406-L442 | [
"def",
"extra_rows",
"(",
"self",
")",
":",
"return",
"{",
"term",
":",
"attrs",
"[",
"'extra_rows'",
"]",
"for",
"term",
",",
"attrs",
"in",
"iteritems",
"(",
"self",
".",
"graph",
".",
"node",
")",
"}"
] | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | ExecutionPlan._ensure_extra_rows | Ensure that we're going to compute at least N extra rows of `term`. | zipline/pipeline/graph.py | 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):
"""
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)) | [
"Ensure",
"that",
"we",
"re",
"going",
"to",
"compute",
"at",
"least",
"N",
"extra",
"rows",
"of",
"term",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/graph.py#L444-L449 | [
"def",
"_ensure_extra_rows",
"(",
"self",
",",
"term",
",",
"N",
")",
":",
"attrs",
"=",
"self",
".",
"graph",
".",
"node",
"[",
"term",
"]",
"attrs",
"[",
"'extra_rows'",
"]",
"=",
"max",
"(",
"N",
",",
"attrs",
".",
"get",
"(",
"'extra_rows'",
",... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | ExecutionPlan.mask_and_dates_for_term | 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... | zipline/pipeline/graph.py | 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):
"""
Load mask and mask row labels for term.
Parameters
----------
term :... | [
"Load",
"mask",
"and",
"mask",
"row",
"labels",
"for",
"term",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/graph.py#L451-L486 | [
"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... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | ExecutionPlan._assert_all_loadable_terms_specialized_to | Make sure that we've specialized all loadable terms in the graph. | zipline/pipeline/graph.py | 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):
"""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 | [
"Make",
"sure",
"that",
"we",
"ve",
"specialized",
"all",
"loadable",
"terms",
"in",
"the",
"graph",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/graph.py#L488-L493 | [
"def",
"_assert_all_loadable_terms_specialized_to",
"(",
"self",
",",
"domain",
")",
":",
"for",
"term",
"in",
"self",
".",
"graph",
".",
"node",
":",
"if",
"isinstance",
"(",
"term",
",",
"LoadableTerm",
")",
":",
"assert",
"term",
".",
"domain",
"is",
"d... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | window_specialization | Make an extension for an AdjustedArrayWindow specialization. | setup.py | 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):
"""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'],
) | [
"Make",
"an",
"extension",
"for",
"an",
"AdjustedArrayWindow",
"specialization",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/setup.py#L81-L87 | [
"def",
"window_specialization",
"(",
"typename",
")",
":",
"return",
"Extension",
"(",
"'zipline.lib._{name}window'",
".",
"format",
"(",
"name",
"=",
"typename",
")",
",",
"[",
"'zipline/lib/_{name}window.pyx'",
".",
"format",
"(",
"name",
"=",
"typename",
")",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | read_requirements | 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. | setup.py | 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):
"""
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... | [
"Read",
"a",
"requirements",
".",
"txt",
"file",
"expressed",
"as",
"a",
"path",
"relative",
"to",
"Zipline",
"root",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/setup.py#L217-L238 | [
"def",
"read_requirements",
"(",
"path",
",",
"strict_bounds",
",",
"conda_format",
"=",
"False",
",",
"filter_names",
"=",
"None",
")",
":",
"real_path",
"=",
"join",
"(",
"dirname",
"(",
"abspath",
"(",
"__file__",
")",
")",
",",
"path",
")",
"with",
"... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | ensure_utc | Normalize a time. If the time is tz-naive, assume it is UTC. | zipline/utils/events.py | 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'):
"""
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) | [
"Normalize",
"a",
"time",
".",
"If",
"the",
"time",
"is",
"tz",
"-",
"naive",
"assume",
"it",
"is",
"UTC",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/events.py#L72-L78 | [
"def",
"ensure_utc",
"(",
"time",
",",
"tz",
"=",
"'UTC'",
")",
":",
"if",
"not",
"time",
".",
"tzinfo",
":",
"time",
"=",
"time",
".",
"replace",
"(",
"tzinfo",
"=",
"pytz",
".",
"timezone",
"(",
"tz",
")",
")",
"return",
"time",
".",
"replace",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | _build_offset | Builds the offset argument for event rules. | zipline/utils/events.py | 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):
"""
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... | [
"Builds",
"the",
"offset",
"argument",
"for",
"event",
"rules",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/events.py#L108-L122 | [
"def",
"_build_offset",
"(",
"offset",
",",
"kwargs",
",",
"default",
")",
":",
"if",
"offset",
"is",
"None",
":",
"if",
"not",
"kwargs",
":",
"return",
"default",
"# use the default.",
"else",
":",
"return",
"_td_check",
"(",
"datetime",
".",
"timedelta",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | _build_date | Builds the date argument for event rules. | zipline/utils/events.py | 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):
"""
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 ... | [
"Builds",
"the",
"date",
"argument",
"for",
"event",
"rules",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/events.py#L125-L138 | [
"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... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | _build_time | Builds the time argument for event rules. | zipline/utils/events.py | 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):
"""
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(... | [
"Builds",
"the",
"time",
"argument",
"for",
"event",
"rules",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/events.py#L141-L154 | [
"def",
"_build_time",
"(",
"time",
",",
"kwargs",
")",
":",
"tz",
"=",
"kwargs",
".",
"pop",
"(",
"'tz'",
",",
"'UTC'",
")",
"if",
"time",
":",
"if",
"kwargs",
":",
"raise",
"ValueError",
"(",
"'Cannot pass kwargs and a time'",
")",
"else",
":",
"return"... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | lossless_float_to_int | A preprocessor that coerces integral floats to ints.
Receipt of non-integral floats raises a TypeError. | zipline/utils/events.py | 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):
"""
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(
... | [
"A",
"preprocessor",
"that",
"coerces",
"integral",
"floats",
"to",
"ints",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/events.py#L158-L179 | [
"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... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | make_eventrule | Constructs an event rule from the factory api. | zipline/utils/events.py | def make_eventrule(date_rule, time_rule, cal, half_days=True):
"""
Constructs an event rule from the factory api.
"""
_check_if_not_called(date_rule)
_check_if_not_called(time_rule)
if half_days:
inner_rule = date_rule & time_rule
else:
inner_rule = date_rule & time_rule & N... | def make_eventrule(date_rule, time_rule, cal, half_days=True):
"""
Constructs an event rule from the factory api.
"""
_check_if_not_called(date_rule)
_check_if_not_called(time_rule)
if half_days:
inner_rule = date_rule & time_rule
else:
inner_rule = date_rule & time_rule & N... | [
"Constructs",
"an",
"event",
"rule",
"from",
"the",
"factory",
"api",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/events.py#L662-L677 | [
"def",
"make_eventrule",
"(",
"date_rule",
",",
"time_rule",
",",
"cal",
",",
"half_days",
"=",
"True",
")",
":",
"_check_if_not_called",
"(",
"date_rule",
")",
"_check_if_not_called",
"(",
"time_rule",
")",
"if",
"half_days",
":",
"inner_rule",
"=",
"date_rule"... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | EventManager.add_event | Adds an event to the manager. | zipline/utils/events.py | 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):
"""
Adds an event to the manager.
"""
if prepend:
self._events.insert(0, event)
else:
self._events.append(event) | [
"Adds",
"an",
"event",
"to",
"the",
"manager",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/events.py#L201-L208 | [
"def",
"add_event",
"(",
"self",
",",
"event",
",",
"prepend",
"=",
"False",
")",
":",
"if",
"prepend",
":",
"self",
".",
"_events",
".",
"insert",
"(",
"0",
",",
"event",
")",
"else",
":",
"self",
".",
"_events",
".",
"append",
"(",
"event",
")"
] | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | Event.handle_data | Calls the callable only when the rule is triggered. | zipline/utils/events.py | 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):
"""
Calls the callable only when the rule is triggered.
"""
if self.rule.should_trigger(dt):
self.callback(context, data) | [
"Calls",
"the",
"callable",
"only",
"when",
"the",
"rule",
"is",
"triggered",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/events.py#L230-L235 | [
"def",
"handle_data",
"(",
"self",
",",
"context",
",",
"data",
",",
"dt",
")",
":",
"if",
"self",
".",
"rule",
".",
"should_trigger",
"(",
"dt",
")",
":",
"self",
".",
"callback",
"(",
"context",
",",
"data",
")"
] | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | ComposedRule.should_trigger | Composes the two rules with a lazy composer. | zipline/utils/events.py | 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):
"""
Composes the two rules with a lazy composer.
"""
return self.composer(
self.first.should_trigger,
self.second.should_trigger,
dt
) | [
"Composes",
"the",
"two",
"rules",
"with",
"a",
"lazy",
"composer",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/events.py#L298-L306 | [
"def",
"should_trigger",
"(",
"self",
",",
"dt",
")",
":",
"return",
"self",
".",
"composer",
"(",
"self",
".",
"first",
".",
"should_trigger",
",",
"self",
".",
"second",
".",
"should_trigger",
",",
"dt",
")"
] | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | AfterOpen.calculate_dates | Given a date, find that day's open and period end (open + offset). | zipline/utils/events.py | def calculate_dates(self, dt):
"""
Given a date, find that day's open and period end (open + offset).
"""
period_start, period_close = self.cal.open_and_close_for_session(
self.cal.minute_to_session_label(dt),
)
# Align the market open and close times here wi... | def calculate_dates(self, dt):
"""
Given a date, find that day's open and period end (open + offset).
"""
period_start, period_close = self.cal.open_and_close_for_session(
self.cal.minute_to_session_label(dt),
)
# Align the market open and close times here wi... | [
"Given",
"a",
"date",
"find",
"that",
"day",
"s",
"open",
"and",
"period",
"end",
"(",
"open",
"+",
"offset",
")",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/events.py#L373-L387 | [
"def",
"calculate_dates",
"(",
"self",
",",
"dt",
")",
":",
"period_start",
",",
"period_close",
"=",
"self",
".",
"cal",
".",
"open_and_close_for_session",
"(",
"self",
".",
"cal",
".",
"minute_to_session_label",
"(",
"dt",
")",
",",
")",
"# Align the market ... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | BeforeClose.calculate_dates | Given a dt, find that day's close and period start (close - offset). | zipline/utils/events.py | def calculate_dates(self, dt):
"""
Given a dt, find that day's close and period start (close - offset).
"""
period_end = self.cal.open_and_close_for_session(
self.cal.minute_to_session_label(dt),
)[1]
# Align the market close time here with the execution time... | def calculate_dates(self, dt):
"""
Given a dt, find that day's close and period start (close - offset).
"""
period_end = self.cal.open_and_close_for_session(
self.cal.minute_to_session_label(dt),
)[1]
# Align the market close time here with the execution time... | [
"Given",
"a",
"dt",
"find",
"that",
"day",
"s",
"close",
"and",
"period",
"start",
"(",
"close",
"-",
"offset",
")",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/events.py#L429-L443 | [
"def",
"calculate_dates",
"(",
"self",
",",
"dt",
")",
":",
"period_end",
"=",
"self",
".",
"cal",
".",
"open_and_close_for_session",
"(",
"self",
".",
"cal",
".",
"minute_to_session_label",
"(",
"dt",
")",
",",
")",
"[",
"1",
"]",
"# Align the market close ... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | winsorise_uint32 | 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... | zipline/data/bcolz_daily_bars.py | 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):
"""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... | [
"Drops",
"any",
"record",
"where",
"a",
"value",
"would",
"not",
"fit",
"into",
"a",
"uint32",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/bcolz_daily_bars.py#L69-L114 | [
"def",
"winsorise_uint32",
"(",
"df",
",",
"invalid_data_behavior",
",",
"column",
",",
"*",
"columns",
")",
":",
"columns",
"=",
"list",
"(",
"(",
"column",
",",
")",
"+",
"columns",
")",
"mask",
"=",
"df",
"[",
"columns",
"]",
">",
"UINT32_MAX",
"if"... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | BcolzDailyBarWriter.write | Parameters
----------
data : iterable[tuple[int, pandas.DataFrame or bcolz.ctable]]
The data chunks to write. Each chunk should be a tuple of sid
and the data for that asset.
assets : set[int], optional
The assets that should be in ``data``. If this is provide... | zipline/data/bcolz_daily_bars.py | def write(self,
data,
assets=None,
show_progress=False,
invalid_data_behavior='warn'):
"""
Parameters
----------
data : iterable[tuple[int, pandas.DataFrame or bcolz.ctable]]
The data chunks to write. Each chunk should b... | def write(self,
data,
assets=None,
show_progress=False,
invalid_data_behavior='warn'):
"""
Parameters
----------
data : iterable[tuple[int, pandas.DataFrame or bcolz.ctable]]
The data chunks to write. Each chunk should b... | [
"Parameters",
"----------",
"data",
":",
"iterable",
"[",
"tuple",
"[",
"int",
"pandas",
".",
"DataFrame",
"or",
"bcolz",
".",
"ctable",
"]]",
"The",
"data",
"chunks",
"to",
"write",
".",
"Each",
"chunk",
"should",
"be",
"a",
"tuple",
"of",
"sid",
"and",... | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/bcolz_daily_bars.py#L170-L207 | [
"def",
"write",
"(",
"self",
",",
"data",
",",
"assets",
"=",
"None",
",",
"show_progress",
"=",
"False",
",",
"invalid_data_behavior",
"=",
"'warn'",
")",
":",
"ctx",
"=",
"maybe_show_progress",
"(",
"(",
"(",
"sid",
",",
"self",
".",
"to_ctable",
"(",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | BcolzDailyBarWriter.write_csvs | 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... | zipline/data/bcolz_daily_bars.py | 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 CSVs as DataFrames from our asset map.
Parameters
----------
asset_map : dict[int -> str]
A mapping from asset id to file path... | [
"Read",
"CSVs",
"as",
"DataFrames",
"from",
"our",
"asset",
"map",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/bcolz_daily_bars.py#L209-L237 | [
"def",
"write_csvs",
"(",
"self",
",",
"asset_map",
",",
"show_progress",
"=",
"False",
",",
"invalid_data_behavior",
"=",
"'warn'",
")",
":",
"read",
"=",
"partial",
"(",
"read_csv",
",",
"parse_dates",
"=",
"[",
"'day'",
"]",
",",
"index_col",
"=",
"'day... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | BcolzDailyBarWriter._write_internal | Internal implementation of write.
`iterator` should be an iterator yielding pairs of (asset, ctable). | zipline/data/bcolz_daily_bars.py | def _write_internal(self, iterator, assets):
"""
Internal implementation of write.
`iterator` should be an iterator yielding pairs of (asset, ctable).
"""
total_rows = 0
first_row = {}
last_row = {}
calendar_offset = {}
# Maps column name -> outp... | def _write_internal(self, iterator, assets):
"""
Internal implementation of write.
`iterator` should be an iterator yielding pairs of (asset, ctable).
"""
total_rows = 0
first_row = {}
last_row = {}
calendar_offset = {}
# Maps column name -> outp... | [
"Internal",
"implementation",
"of",
"write",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/bcolz_daily_bars.py#L239-L359 | [
"def",
"_write_internal",
"(",
"self",
",",
"iterator",
",",
"assets",
")",
":",
"total_rows",
"=",
"0",
"first_row",
"=",
"{",
"}",
"last_row",
"=",
"{",
"}",
"calendar_offset",
"=",
"{",
"}",
"# Maps column name -> output carray.",
"columns",
"=",
"{",
"k"... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | BcolzDailyBarReader._compute_slices | 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... | zipline/data/bcolz_daily_bars.py | 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):
"""
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_... | [
"Compute",
"the",
"raw",
"row",
"indices",
"to",
"load",
"for",
"each",
"asset",
"on",
"a",
"query",
"for",
"the",
"given",
"dates",
"after",
"applying",
"a",
"shift",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/bcolz_daily_bars.py#L530-L570 | [
"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",
".... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | BcolzDailyBarReader._spot_col | 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... | zipline/data/bcolz_daily_bars.py | 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):
"""
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... | [
"Get",
"the",
"colname",
"from",
"daily_bar_table",
"and",
"read",
"all",
"of",
"it",
"into",
"memory",
"caching",
"the",
"result",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/bcolz_daily_bars.py#L598-L618 | [
"def",
"_spot_col",
"(",
"self",
",",
"colname",
")",
":",
"try",
":",
"col",
"=",
"self",
".",
"_spot_cols",
"[",
"colname",
"]",
"except",
"KeyError",
":",
"col",
"=",
"self",
".",
"_spot_cols",
"[",
"colname",
"]",
"=",
"self",
".",
"_table",
"[",... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | BcolzDailyBarReader.sid_day_index | Parameters
----------
sid : int
The asset identifier.
day : datetime64-like
Midnight of the day for which data is requested.
Returns
-------
int
Index into the data tape for the given sid and day.
Raises a NoDataOnDate exce... | zipline/data/bcolz_daily_bars.py | def sid_day_index(self, sid, day):
"""
Parameters
----------
sid : int
The asset identifier.
day : datetime64-like
Midnight of the day for which data is requested.
Returns
-------
int
Index into the data tape for the gi... | def sid_day_index(self, sid, day):
"""
Parameters
----------
sid : int
The asset identifier.
day : datetime64-like
Midnight of the day for which data is requested.
Returns
-------
int
Index into the data tape for the gi... | [
"Parameters",
"----------",
"sid",
":",
"int",
"The",
"asset",
"identifier",
".",
"day",
":",
"datetime64",
"-",
"like",
"Midnight",
"of",
"the",
"day",
"for",
"which",
"data",
"is",
"requested",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/bcolz_daily_bars.py#L645-L676 | [
"def",
"sid_day_index",
"(",
"self",
",",
"sid",
",",
"day",
")",
":",
"try",
":",
"day_loc",
"=",
"self",
".",
"sessions",
".",
"get_loc",
"(",
"day",
")",
"except",
"Exception",
":",
"raise",
"NoDataOnDate",
"(",
"\"day={0} is outside of calendar={1}\"",
"... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | BcolzDailyBarReader.get_value | Parameters
----------
sid : int
The asset identifier.
day : datetime64-like
Midnight of the day for which data is requested.
colname : string
The price field. e.g. ('open', 'high', 'low', 'close', 'volume')
Returns
-------
floa... | zipline/data/bcolz_daily_bars.py | def get_value(self, sid, dt, field):
"""
Parameters
----------
sid : int
The asset identifier.
day : datetime64-like
Midnight of the day for which data is requested.
colname : string
The price field. e.g. ('open', 'high', 'low', 'close'... | def get_value(self, sid, dt, field):
"""
Parameters
----------
sid : int
The asset identifier.
day : datetime64-like
Midnight of the day for which data is requested.
colname : string
The price field. e.g. ('open', 'high', 'low', 'close'... | [
"Parameters",
"----------",
"sid",
":",
"int",
"The",
"asset",
"identifier",
".",
"day",
":",
"datetime64",
"-",
"like",
"Midnight",
"of",
"the",
"day",
"for",
"which",
"data",
"is",
"requested",
".",
"colname",
":",
"string",
"The",
"price",
"field",
".",... | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/bcolz_daily_bars.py#L678-L706 | [
"def",
"get_value",
"(",
"self",
",",
"sid",
",",
"dt",
",",
"field",
")",
":",
"ix",
"=",
"self",
".",
"sid_day_index",
"(",
"sid",
",",
"dt",
")",
"price",
"=",
"self",
".",
"_spot_col",
"(",
"field",
")",
"[",
"ix",
"]",
"if",
"field",
"!=",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.init_engine | Construct and store a PipelineEngine from loader.
If get_loader is None, constructs an ExplodingPipelineEngine | zipline/algorithm.py | 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):
"""
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... | [
"Construct",
"and",
"store",
"a",
"PipelineEngine",
"from",
"loader",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L408-L421 | [
"def",
"init_engine",
"(",
"self",
",",
"get_loader",
")",
":",
"if",
"get_loader",
"is",
"not",
"None",
":",
"self",
".",
"engine",
"=",
"SimplePipelineEngine",
"(",
"get_loader",
",",
"self",
".",
"asset_finder",
",",
"self",
".",
"default_pipeline_domain",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.initialize | Call self._initialize with `self` made available to Zipline API
functions. | zipline/algorithm.py | 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):
"""
Call self._initialize with `self` made available to Zipline API
functions.
"""
with ZiplineAPI(self):
self._initialize(self, *args, **kwargs) | [
"Call",
"self",
".",
"_initialize",
"with",
"self",
"made",
"available",
"to",
"Zipline",
"API",
"functions",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L423-L429 | [
"def",
"initialize",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"ZiplineAPI",
"(",
"self",
")",
":",
"self",
".",
"_initialize",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm._create_clock | If the clock property is not set, then create one based on frequency. | zipline/algorithm.py | 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):
"""
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
... | [
"If",
"the",
"clock",
"property",
"is",
"not",
"set",
"then",
"create",
"one",
"based",
"on",
"frequency",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L482-L526 | [
"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... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.compute_eager_pipelines | Compute any pipelines attached with eager=True. | zipline/algorithm.py | 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):
"""
Compute any pipelines attached with eager=True.
"""
for name, pipe in self._pipelines.items():
if pipe.eager:
self.pipeline_output(name) | [
"Compute",
"any",
"pipelines",
"attached",
"with",
"eager",
"=",
"True",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L601-L607 | [
"def",
"compute_eager_pipelines",
"(",
"self",
")",
":",
"for",
"name",
",",
"pipe",
"in",
"self",
".",
"_pipelines",
".",
"items",
"(",
")",
":",
"if",
"pipe",
".",
"eager",
":",
"self",
".",
"pipeline_output",
"(",
"name",
")"
] | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.run | Run the algorithm. | zipline/algorithm.py | 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):
"""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... | [
"Run",
"the",
"algorithm",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L617-L650 | [
"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",... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.calculate_capital_changes | 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... | zipline/algorithm.py | 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):
"""
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... | [
"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",
"... | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L675-L725 | [
"def",
"calculate_capital_changes",
"(",
"self",
",",
"dt",
",",
"emission_rate",
",",
"is_interday",
",",
"portfolio_value_adjustment",
"=",
"0.0",
")",
":",
"try",
":",
"capital_change",
"=",
"self",
".",
"capital_changes",
"[",
"dt",
"]",
"except",
"KeyError"... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.get_environment | 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... | zipline/algorithm.py | 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'):
"""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... | [
"Query",
"the",
"execution",
"environment",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L728-L782 | [
"def",
"get_environment",
"(",
"self",
",",
"field",
"=",
"'platform'",
")",
":",
"env",
"=",
"{",
"'arena'",
":",
"self",
".",
"sim_params",
".",
"arena",
",",
"'data_frequency'",
":",
"self",
".",
"sim_params",
".",
"data_frequency",
",",
"'start'",
":",... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.fetch_csv | 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... | zipline/algorithm.py | 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=None,
mask=True,
symbol_column=No... | [
"Fetch",
"a",
"csv",
"from",
"a",
"remote",
"url",
"and",
"register",
"the",
"data",
"so",
"that",
"it",
"is",
"queryable",
"from",
"the",
"data",
"object",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L785-L872 | [
"def",
"fetch_csv",
"(",
"self",
",",
"url",
",",
"pre_func",
"=",
"None",
",",
"post_func",
"=",
"None",
",",
"date_column",
"=",
"'date'",
",",
"date_format",
"=",
"None",
",",
"timezone",
"=",
"pytz",
".",
"utc",
".",
"zone",
",",
"symbol",
"=",
"... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.add_event | 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. | zipline/algorithm.py | 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):
"""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... | [
"Adds",
"an",
"event",
"to",
"the",
"algorithm",
"s",
"EventManager",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L874-L886 | [
"def",
"add_event",
"(",
"self",
",",
"rule",
",",
"callback",
")",
":",
"self",
".",
"event_manager",
".",
"add_event",
"(",
"zipline",
".",
"utils",
".",
"events",
".",
"Event",
"(",
"rule",
",",
"callback",
")",
",",
")"
] | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.schedule_function | 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.
... | zipline/algorithm.py | 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):
"""Schedules a function to be called according to some timed rules.
Paramet... | [
"Schedules",
"a",
"function",
"to",
"be",
"called",
"according",
"to",
"some",
"timed",
"rules",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L889-L951 | [
"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... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.continuous_future | 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... | zipline/algorithm.py | 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'):
"""Create a specifier for a continuous contract.
Parameters
----------
root_symbol_str : str
... | [
"Create",
"a",
"specifier",
"for",
"a",
"continuous",
"contract",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1000-L1032 | [
"def",
"continuous_future",
"(",
"self",
",",
"root_symbol_str",
",",
"offset",
"=",
"0",
",",
"roll",
"=",
"'volume'",
",",
"adjustment",
"=",
"'mul'",
")",
":",
"return",
"self",
".",
"asset_finder",
".",
"create_continuous_future",
"(",
"root_symbol_str",
"... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.symbol | 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
... | zipline/algorithm.py | 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):
"""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.
... | [
"Lookup",
"an",
"Equity",
"by",
"its",
"ticker",
"symbol",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1039-L1074 | [
"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... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.symbols | 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]
... | zipline/algorithm.py | 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):
"""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
---... | [
"Lookup",
"multuple",
"Equities",
"as",
"a",
"list",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1077-L1105 | [
"def",
"symbols",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"[",
"self",
".",
"symbol",
"(",
"identifier",
",",
"*",
"*",
"kwargs",
")",
"for",
"identifier",
"in",
"args",
"]"
] | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm._calculate_order_value_amount | Calculates how many shares/contracts to order based on the type of
asset being ordered. | zipline/algorithm.py | def _calculate_order_value_amount(self, asset, value):
"""
Calculates how many shares/contracts to order based on the type of
asset being ordered.
"""
# Make sure the asset exists, and that there is a last price for it.
# FIXME: we should use BarData's can_trade logic her... | def _calculate_order_value_amount(self, asset, value):
"""
Calculates how many shares/contracts to order based on the type of
asset being ordered.
"""
# Make sure the asset exists, and that there is a last price for it.
# FIXME: we should use BarData's can_trade logic her... | [
"Calculates",
"how",
"many",
"shares",
"/",
"contracts",
"to",
"order",
"based",
"on",
"the",
"type",
"of",
"asset",
"being",
"ordered",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1150-L1192 | [
"def",
"_calculate_order_value_amount",
"(",
"self",
",",
"asset",
",",
"value",
")",
":",
"# Make sure the asset exists, and that there is a last price for it.",
"# FIXME: we should use BarData's can_trade logic here, but I haven't",
"# yet found a good way to do that.",
"normalized_date"... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.order | Place an order.
Parameters
----------
asset : Asset
The asset that this order is for.
amount : int
The amount of shares to order. If ``amount`` is positive, this is
the number of shares to buy or cover. If ``amount`` is negative,
this is t... | zipline/algorithm.py | def order(self,
asset,
amount,
limit_price=None,
stop_price=None,
style=None):
"""Place an order.
Parameters
----------
asset : Asset
The asset that this order is for.
amount : int
The ... | def order(self,
asset,
amount,
limit_price=None,
stop_price=None,
style=None):
"""Place an order.
Parameters
----------
asset : Asset
The asset that this order is for.
amount : int
The ... | [
"Place",
"an",
"order",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1219-L1269 | [
"def",
"order",
"(",
"self",
",",
"asset",
",",
"amount",
",",
"limit_price",
"=",
"None",
",",
"stop_price",
"=",
"None",
",",
"style",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_can_order_asset",
"(",
"asset",
")",
":",
"return",
"None",
"a... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.validate_order_params | Helper method for validating parameters to the order API function.
Raises an UnsupportedOrderParameters if invalid arguments are found. | zipline/algorithm.py | 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):
"""
Helper method for validating parameters to the order API function.
... | [
"Helper",
"method",
"for",
"validating",
"parameters",
"to",
"the",
"order",
"API",
"function",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1302-L1335 | [
"def",
"validate_order_params",
"(",
"self",
",",
"asset",
",",
"amount",
",",
"limit_price",
",",
"stop_price",
",",
"style",
")",
":",
"if",
"not",
"self",
".",
"initialized",
":",
"raise",
"OrderDuringInitialize",
"(",
"msg",
"=",
"\"order() can only be calle... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.__convert_order_params_for_blotter | 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). | zipline/algorithm.py | 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):
"""
Helper method for converting deprecated limit_price and stop_price
arguments into Ex... | [
"Helper",
"method",
"for",
"converting",
"deprecated",
"limit_price",
"and",
"stop_price",
"arguments",
"into",
"ExecutionStyle",
"instances",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1338-L1359 | [
"def",
"__convert_order_params_for_blotter",
"(",
"asset",
",",
"limit_price",
",",
"stop_price",
",",
"style",
")",
":",
"if",
"style",
":",
"assert",
"(",
"limit_price",
",",
"stop_price",
")",
"==",
"(",
"None",
",",
"None",
")",
"return",
"style",
"if",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.order_value | 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... | zipline/algorithm.py | 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):
"""Place an order by desired value rather than desired number of
shares.
Parameters
----------
... | [
"Place",
"an",
"order",
"by",
"desired",
"value",
"rather",
"than",
"desired",
"number",
"of",
"shares",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1363-L1414 | [
"def",
"order_value",
"(",
"self",
",",
"asset",
",",
"value",
",",
"limit_price",
"=",
"None",
",",
"stop_price",
"=",
"None",
",",
"style",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_can_order_asset",
"(",
"asset",
")",
":",
"return",
"None",... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm._sync_last_sale_prices | 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. | zipline/algorithm.py | 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):
"""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 ... | [
"Sync",
"the",
"last",
"sale",
"prices",
"on",
"the",
"metrics",
"tracker",
"to",
"a",
"given",
"datetime",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1420-L1442 | [
"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... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.on_dt_changed | 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. | zipline/algorithm.py | 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):
"""
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) | [
"Callback",
"triggered",
"by",
"the",
"simulation",
"loop",
"whenever",
"the",
"current",
"dt",
"changes",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1457-L1466 | [
"def",
"on_dt_changed",
"(",
"self",
",",
"dt",
")",
":",
"self",
".",
"datetime",
"=",
"dt",
"self",
".",
"blotter",
".",
"set_date",
"(",
"dt",
")"
] | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.get_datetime | 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``. | zipline/algorithm.py | 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):
"""
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... | [
"Returns",
"the",
"current",
"simulation",
"datetime",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1471-L1489 | [
"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"... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.set_slippage | 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
---... | zipline/algorithm.py | 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):
"""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... | [
"Set",
"the",
"slippage",
"models",
"for",
"the",
"simulation",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1492-L1525 | [
"def",
"set_slippage",
"(",
"self",
",",
"us_equities",
"=",
"None",
",",
"us_futures",
"=",
"None",
")",
":",
"if",
"self",
".",
"initialized",
":",
"raise",
"SetSlippagePostInit",
"(",
")",
"if",
"us_equities",
"is",
"not",
"None",
":",
"if",
"Equity",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.set_commission | Sets the commission models for the simulation.
Parameters
----------
us_equities : EquityCommissionModel
The commission model to use for trading US equities.
us_futures : FutureCommissionModel
The commission model to use for trading US futures.
See Also
... | zipline/algorithm.py | def set_commission(self, us_equities=None, us_futures=None):
"""Sets the commission models for the simulation.
Parameters
----------
us_equities : EquityCommissionModel
The commission model to use for trading US equities.
us_futures : FutureCommissionModel
... | def set_commission(self, us_equities=None, us_futures=None):
"""Sets the commission models for the simulation.
Parameters
----------
us_equities : EquityCommissionModel
The commission model to use for trading US equities.
us_futures : FutureCommissionModel
... | [
"Sets",
"the",
"commission",
"models",
"for",
"the",
"simulation",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1528-L1563 | [
"def",
"set_commission",
"(",
"self",
",",
"us_equities",
"=",
"None",
",",
"us_futures",
"=",
"None",
")",
":",
"if",
"self",
".",
"initialized",
":",
"raise",
"SetCommissionPostInit",
"(",
")",
"if",
"us_equities",
"is",
"not",
"None",
":",
"if",
"Equity... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.set_cancel_policy | Sets the order cancellation policy for the simulation.
Parameters
----------
cancel_policy : CancelPolicy
The cancellation policy to use.
See Also
--------
:class:`zipline.api.EODCancel`
:class:`zipline.api.NeverCancel` | zipline/algorithm.py | def set_cancel_policy(self, cancel_policy):
"""Sets the order cancellation policy for the simulation.
Parameters
----------
cancel_policy : CancelPolicy
The cancellation policy to use.
See Also
--------
:class:`zipline.api.EODCancel`
:class:`... | def set_cancel_policy(self, cancel_policy):
"""Sets the order cancellation policy for the simulation.
Parameters
----------
cancel_policy : CancelPolicy
The cancellation policy to use.
See Also
--------
:class:`zipline.api.EODCancel`
:class:`... | [
"Sets",
"the",
"order",
"cancellation",
"policy",
"for",
"the",
"simulation",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1566-L1585 | [
"def",
"set_cancel_policy",
"(",
"self",
",",
"cancel_policy",
")",
":",
"if",
"not",
"isinstance",
"(",
"cancel_policy",
",",
"CancelPolicy",
")",
":",
"raise",
"UnsupportedCancelPolicy",
"(",
")",
"if",
"self",
".",
"initialized",
":",
"raise",
"SetCancelPolic... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.set_symbol_lookup_date | Set the date for which symbols will be resolved to their assets
(symbols may map to different firms or underlying assets at
different times)
Parameters
----------
dt : datetime
The new symbol lookup date. | zipline/algorithm.py | def set_symbol_lookup_date(self, dt):
"""Set the date for which symbols will be resolved to their assets
(symbols may map to different firms or underlying assets at
different times)
Parameters
----------
dt : datetime
The new symbol lookup date.
"""
... | def set_symbol_lookup_date(self, dt):
"""Set the date for which symbols will be resolved to their assets
(symbols may map to different firms or underlying assets at
different times)
Parameters
----------
dt : datetime
The new symbol lookup date.
"""
... | [
"Set",
"the",
"date",
"for",
"which",
"symbols",
"will",
"be",
"resolved",
"to",
"their",
"assets",
"(",
"symbols",
"may",
"map",
"to",
"different",
"firms",
"or",
"underlying",
"assets",
"at",
"different",
"times",
")"
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1588-L1602 | [
"def",
"set_symbol_lookup_date",
"(",
"self",
",",
"dt",
")",
":",
"try",
":",
"self",
".",
"_symbol_lookup_date",
"=",
"pd",
".",
"Timestamp",
"(",
"dt",
",",
"tz",
"=",
"'UTC'",
")",
"except",
"ValueError",
":",
"raise",
"UnsupportedDatetimeFormat",
"(",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.order_percent | Place an order in the specified asset corresponding to the given
percent of the current portfolio value.
Parameters
----------
asset : Asset
The asset that this order is for.
percent : float
The percentage of the portfolio value to allocate to ``asset``.
... | zipline/algorithm.py | def order_percent(self,
asset,
percent,
limit_price=None,
stop_price=None,
style=None):
"""Place an order in the specified asset corresponding to the given
percent of the current portfolio value... | def order_percent(self,
asset,
percent,
limit_price=None,
stop_price=None,
style=None):
"""Place an order in the specified asset corresponding to the given
percent of the current portfolio value... | [
"Place",
"an",
"order",
"in",
"the",
"specified",
"asset",
"corresponding",
"to",
"the",
"given",
"percent",
"of",
"the",
"current",
"portfolio",
"value",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1616-L1662 | [
"def",
"order_percent",
"(",
"self",
",",
"asset",
",",
"percent",
",",
"limit_price",
"=",
"None",
",",
"stop_price",
"=",
"None",
",",
"style",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_can_order_asset",
"(",
"asset",
")",
":",
"return",
"No... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.order_target | Place an order to adjust a position to a target number of shares. If
the position doesn't already exist, this is equivalent to placing a new
order. If the position does exist, this is equivalent to placing an
order for the difference between the target number of shares and the
current nu... | zipline/algorithm.py | def order_target(self,
asset,
target,
limit_price=None,
stop_price=None,
style=None):
"""Place an order to adjust a position to a target number of shares. If
the position doesn't already exist, this ... | def order_target(self,
asset,
target,
limit_price=None,
stop_price=None,
style=None):
"""Place an order to adjust a position to a target number of shares. If
the position doesn't already exist, this ... | [
"Place",
"an",
"order",
"to",
"adjust",
"a",
"position",
"to",
"a",
"target",
"number",
"of",
"shares",
".",
"If",
"the",
"position",
"doesn",
"t",
"already",
"exist",
"this",
"is",
"equivalent",
"to",
"placing",
"a",
"new",
"order",
".",
"If",
"the",
... | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1670-L1732 | [
"def",
"order_target",
"(",
"self",
",",
"asset",
",",
"target",
",",
"limit_price",
"=",
"None",
",",
"stop_price",
"=",
"None",
",",
"style",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_can_order_asset",
"(",
"asset",
")",
":",
"return",
"None... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.order_target_value | Place an order to adjust a position to a target value. If
the position doesn't already exist, this is equivalent to placing a new
order. If the position does exist, this is equivalent to placing an
order for the difference between the target value and the
current value.
If the As... | zipline/algorithm.py | def order_target_value(self,
asset,
target,
limit_price=None,
stop_price=None,
style=None):
"""Place an order to adjust a position to a target value. If
the position doe... | def order_target_value(self,
asset,
target,
limit_price=None,
stop_price=None,
style=None):
"""Place an order to adjust a position to a target value. If
the position doe... | [
"Place",
"an",
"order",
"to",
"adjust",
"a",
"position",
"to",
"a",
"target",
"value",
".",
"If",
"the",
"position",
"doesn",
"t",
"already",
"exist",
"this",
"is",
"equivalent",
"to",
"placing",
"a",
"new",
"order",
".",
"If",
"the",
"position",
"does",... | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1743-L1807 | [
"def",
"order_target_value",
"(",
"self",
",",
"asset",
",",
"target",
",",
"limit_price",
"=",
"None",
",",
"stop_price",
"=",
"None",
",",
"style",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_can_order_asset",
"(",
"asset",
")",
":",
"return",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.order_target_percent | Place an order to adjust a position to a target percent of the
current portfolio value. If the position doesn't already exist, this is
equivalent to placing a new order. If the position does exist, this is
equivalent to placing an order for the difference between the target
percent and t... | zipline/algorithm.py | def order_target_percent(self, asset, target,
limit_price=None, stop_price=None, style=None):
"""Place an order to adjust a position to a target percent of the
current portfolio value. If the position doesn't already exist, this is
equivalent to placing a new order. ... | def order_target_percent(self, asset, target,
limit_price=None, stop_price=None, style=None):
"""Place an order to adjust a position to a target percent of the
current portfolio value. If the position doesn't already exist, this is
equivalent to placing a new order. ... | [
"Place",
"an",
"order",
"to",
"adjust",
"a",
"position",
"to",
"a",
"target",
"percent",
"of",
"the",
"current",
"portfolio",
"value",
".",
"If",
"the",
"position",
"doesn",
"t",
"already",
"exist",
"this",
"is",
"equivalent",
"to",
"placing",
"a",
"new",
... | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1811-L1870 | [
"def",
"order_target_percent",
"(",
"self",
",",
"asset",
",",
"target",
",",
"limit_price",
"=",
"None",
",",
"stop_price",
"=",
"None",
",",
"style",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_can_order_asset",
"(",
"asset",
")",
":",
"return",... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.batch_market_order | Place a batch market order for multiple assets.
Parameters
----------
share_counts : pd.Series[Asset -> int]
Map from asset to number of shares to order for that asset.
Returns
-------
order_ids : pd.Index[str]
Index of ids for newly-created orde... | zipline/algorithm.py | def batch_market_order(self, share_counts):
"""Place a batch market order for multiple assets.
Parameters
----------
share_counts : pd.Series[Asset -> int]
Map from asset to number of shares to order for that asset.
Returns
-------
order_ids : pd.Ind... | def batch_market_order(self, share_counts):
"""Place a batch market order for multiple assets.
Parameters
----------
share_counts : pd.Series[Asset -> int]
Map from asset to number of shares to order for that asset.
Returns
-------
order_ids : pd.Ind... | [
"Place",
"a",
"batch",
"market",
"order",
"for",
"multiple",
"assets",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1879-L1898 | [
"def",
"batch_market_order",
"(",
"self",
",",
"share_counts",
")",
":",
"style",
"=",
"MarketOrder",
"(",
")",
"order_args",
"=",
"[",
"(",
"asset",
",",
"amount",
",",
"style",
")",
"for",
"(",
"asset",
",",
"amount",
")",
"in",
"iteritems",
"(",
"sh... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.get_open_orders | Retrieve all of the current open orders.
Parameters
----------
asset : Asset
If passed and not None, return only the open orders for the given
asset instead of all open orders.
Returns
-------
open_orders : dict[list[Order]] or list[Order]
... | zipline/algorithm.py | def get_open_orders(self, asset=None):
"""Retrieve all of the current open orders.
Parameters
----------
asset : Asset
If passed and not None, return only the open orders for the given
asset instead of all open orders.
Returns
-------
ope... | def get_open_orders(self, asset=None):
"""Retrieve all of the current open orders.
Parameters
----------
asset : Asset
If passed and not None, return only the open orders for the given
asset instead of all open orders.
Returns
-------
ope... | [
"Retrieve",
"all",
"of",
"the",
"current",
"open",
"orders",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1903-L1929 | [
"def",
"get_open_orders",
"(",
"self",
",",
"asset",
"=",
"None",
")",
":",
"if",
"asset",
"is",
"None",
":",
"return",
"{",
"key",
":",
"[",
"order",
".",
"to_api_obj",
"(",
")",
"for",
"order",
"in",
"orders",
"]",
"for",
"key",
",",
"orders",
"i... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.get_order | Lookup an order based on the order id returned from one of the
order functions.
Parameters
----------
order_id : str
The unique identifier for the order.
Returns
-------
order : Order
The order object. | zipline/algorithm.py | def get_order(self, order_id):
"""Lookup an order based on the order id returned from one of the
order functions.
Parameters
----------
order_id : str
The unique identifier for the order.
Returns
-------
order : Order
The order ob... | def get_order(self, order_id):
"""Lookup an order based on the order id returned from one of the
order functions.
Parameters
----------
order_id : str
The unique identifier for the order.
Returns
-------
order : Order
The order ob... | [
"Lookup",
"an",
"order",
"based",
"on",
"the",
"order",
"id",
"returned",
"from",
"one",
"of",
"the",
"order",
"functions",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1932-L1947 | [
"def",
"get_order",
"(",
"self",
",",
"order_id",
")",
":",
"if",
"order_id",
"in",
"self",
".",
"blotter",
".",
"orders",
":",
"return",
"self",
".",
"blotter",
".",
"orders",
"[",
"order_id",
"]",
".",
"to_api_obj",
"(",
")"
] | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.cancel_order | Cancel an open order.
Parameters
----------
order_param : str or Order
The order_id or order object to cancel. | zipline/algorithm.py | def cancel_order(self, order_param):
"""Cancel an open order.
Parameters
----------
order_param : str or Order
The order_id or order object to cancel.
"""
order_id = order_param
if isinstance(order_param, zipline.protocol.Order):
order_id ... | def cancel_order(self, order_param):
"""Cancel an open order.
Parameters
----------
order_param : str or Order
The order_id or order object to cancel.
"""
order_id = order_param
if isinstance(order_param, zipline.protocol.Order):
order_id ... | [
"Cancel",
"an",
"open",
"order",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1950-L1962 | [
"def",
"cancel_order",
"(",
"self",
",",
"order_param",
")",
":",
"order_id",
"=",
"order_param",
"if",
"isinstance",
"(",
"order_param",
",",
"zipline",
".",
"protocol",
".",
"Order",
")",
":",
"order_id",
"=",
"order_param",
".",
"id",
"self",
".",
"blot... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.history | DEPRECATED: use ``data.history`` instead. | zipline/algorithm.py | def history(self, bar_count, frequency, field, ffill=True):
"""DEPRECATED: use ``data.history`` instead.
"""
warnings.warn(
"The `history` method is deprecated. Use `data.history` instead.",
category=ZiplineDeprecationWarning,
stacklevel=4
)
... | def history(self, bar_count, frequency, field, ffill=True):
"""DEPRECATED: use ``data.history`` instead.
"""
warnings.warn(
"The `history` method is deprecated. Use `data.history` instead.",
category=ZiplineDeprecationWarning,
stacklevel=4
)
... | [
"DEPRECATED",
":",
"use",
"data",
".",
"history",
"instead",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1966-L1981 | [
"def",
"history",
"(",
"self",
",",
"bar_count",
",",
"frequency",
",",
"field",
",",
"ffill",
"=",
"True",
")",
":",
"warnings",
".",
"warn",
"(",
"\"The `history` method is deprecated. Use `data.history` instead.\"",
",",
"category",
"=",
"ZiplineDeprecationWarning... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.register_account_control | Register a new AccountControl to be checked on each bar. | zipline/algorithm.py | def register_account_control(self, control):
"""
Register a new AccountControl to be checked on each bar.
"""
if self.initialized:
raise RegisterAccountControlPostInit()
self.account_controls.append(control) | def register_account_control(self, control):
"""
Register a new AccountControl to be checked on each bar.
"""
if self.initialized:
raise RegisterAccountControlPostInit()
self.account_controls.append(control) | [
"Register",
"a",
"new",
"AccountControl",
"to",
"be",
"checked",
"on",
"each",
"bar",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L2028-L2034 | [
"def",
"register_account_control",
"(",
"self",
",",
"control",
")",
":",
"if",
"self",
".",
"initialized",
":",
"raise",
"RegisterAccountControlPostInit",
"(",
")",
"self",
".",
"account_controls",
".",
"append",
"(",
"control",
")"
] | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.set_min_leverage | Set a limit on the minimum leverage of the algorithm.
Parameters
----------
min_leverage : float
The minimum leverage for the algorithm.
grace_period : pd.Timedelta
The offset from the start date used to enforce a minimum leverage. | zipline/algorithm.py | def set_min_leverage(self, min_leverage, grace_period):
"""Set a limit on the minimum leverage of the algorithm.
Parameters
----------
min_leverage : float
The minimum leverage for the algorithm.
grace_period : pd.Timedelta
The offset from the start date ... | def set_min_leverage(self, min_leverage, grace_period):
"""Set a limit on the minimum leverage of the algorithm.
Parameters
----------
min_leverage : float
The minimum leverage for the algorithm.
grace_period : pd.Timedelta
The offset from the start date ... | [
"Set",
"a",
"limit",
"on",
"the",
"minimum",
"leverage",
"of",
"the",
"algorithm",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L2057-L2069 | [
"def",
"set_min_leverage",
"(",
"self",
",",
"min_leverage",
",",
"grace_period",
")",
":",
"deadline",
"=",
"self",
".",
"sim_params",
".",
"start_session",
"+",
"grace_period",
"control",
"=",
"MinLeverage",
"(",
"min_leverage",
",",
"deadline",
")",
"self",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.register_trading_control | Register a new TradingControl to be checked prior to order calls. | zipline/algorithm.py | def register_trading_control(self, control):
"""
Register a new TradingControl to be checked prior to order calls.
"""
if self.initialized:
raise RegisterTradingControlPostInit()
self.trading_controls.append(control) | def register_trading_control(self, control):
"""
Register a new TradingControl to be checked prior to order calls.
"""
if self.initialized:
raise RegisterTradingControlPostInit()
self.trading_controls.append(control) | [
"Register",
"a",
"new",
"TradingControl",
"to",
"be",
"checked",
"prior",
"to",
"order",
"calls",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L2075-L2081 | [
"def",
"register_trading_control",
"(",
"self",
",",
"control",
")",
":",
"if",
"self",
".",
"initialized",
":",
"raise",
"RegisterTradingControlPostInit",
"(",
")",
"self",
".",
"trading_controls",
".",
"append",
"(",
"control",
")"
] | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.set_max_position_size | Set a limit on the number of shares and/or dollar value held for the
given sid. Limits are treated as absolute values and are enforced at
the time that the algo attempts to place an order for sid. This means
that it's possible to end up with more than the max number of shares
due to spli... | zipline/algorithm.py | def set_max_position_size(self,
asset=None,
max_shares=None,
max_notional=None,
on_error='fail'):
"""Set a limit on the number of shares and/or dollar value held for the
given sid. Lim... | def set_max_position_size(self,
asset=None,
max_shares=None,
max_notional=None,
on_error='fail'):
"""Set a limit on the number of shares and/or dollar value held for the
given sid. Lim... | [
"Set",
"a",
"limit",
"on",
"the",
"number",
"of",
"shares",
"and",
"/",
"or",
"dollar",
"value",
"held",
"for",
"the",
"given",
"sid",
".",
"Limits",
"are",
"treated",
"as",
"absolute",
"values",
"and",
"are",
"enforced",
"at",
"the",
"time",
"that",
"... | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L2084-L2114 | [
"def",
"set_max_position_size",
"(",
"self",
",",
"asset",
"=",
"None",
",",
"max_shares",
"=",
"None",
",",
"max_notional",
"=",
"None",
",",
"on_error",
"=",
"'fail'",
")",
":",
"control",
"=",
"MaxPositionSize",
"(",
"asset",
"=",
"asset",
",",
"max_sha... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.set_max_order_size | Set a limit on the number of shares and/or dollar value of any single
order placed for sid. Limits are treated as absolute values and are
enforced at the time that the algo attempts to place an order for sid.
If an algorithm attempts to place an order that would result in
exceeding one... | zipline/algorithm.py | def set_max_order_size(self,
asset=None,
max_shares=None,
max_notional=None,
on_error='fail'):
"""Set a limit on the number of shares and/or dollar value of any single
order placed for sid. Limit... | def set_max_order_size(self,
asset=None,
max_shares=None,
max_notional=None,
on_error='fail'):
"""Set a limit on the number of shares and/or dollar value of any single
order placed for sid. Limit... | [
"Set",
"a",
"limit",
"on",
"the",
"number",
"of",
"shares",
"and",
"/",
"or",
"dollar",
"value",
"of",
"any",
"single",
"order",
"placed",
"for",
"sid",
".",
"Limits",
"are",
"treated",
"as",
"absolute",
"values",
"and",
"are",
"enforced",
"at",
"the",
... | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L2117-L2143 | [
"def",
"set_max_order_size",
"(",
"self",
",",
"asset",
"=",
"None",
",",
"max_shares",
"=",
"None",
",",
"max_notional",
"=",
"None",
",",
"on_error",
"=",
"'fail'",
")",
":",
"control",
"=",
"MaxOrderSize",
"(",
"asset",
"=",
"asset",
",",
"max_shares",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.set_max_order_count | Set a limit on the number of orders that can be placed in a single
day.
Parameters
----------
max_count : int
The maximum number of orders that can be placed on any single day. | zipline/algorithm.py | def set_max_order_count(self, max_count, on_error='fail'):
"""Set a limit on the number of orders that can be placed in a single
day.
Parameters
----------
max_count : int
The maximum number of orders that can be placed on any single day.
"""
control ... | def set_max_order_count(self, max_count, on_error='fail'):
"""Set a limit on the number of orders that can be placed in a single
day.
Parameters
----------
max_count : int
The maximum number of orders that can be placed on any single day.
"""
control ... | [
"Set",
"a",
"limit",
"on",
"the",
"number",
"of",
"orders",
"that",
"can",
"be",
"placed",
"in",
"a",
"single",
"day",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L2146-L2156 | [
"def",
"set_max_order_count",
"(",
"self",
",",
"max_count",
",",
"on_error",
"=",
"'fail'",
")",
":",
"control",
"=",
"MaxOrderCount",
"(",
"on_error",
",",
"max_count",
")",
"self",
".",
"register_trading_control",
"(",
"control",
")"
] | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.set_asset_restrictions | Set a restriction on which assets can be ordered.
Parameters
----------
restricted_list : Restrictions
An object providing information about restricted assets.
See Also
--------
zipline.finance.asset_restrictions.Restrictions | zipline/algorithm.py | def set_asset_restrictions(self, restrictions, on_error='fail'):
"""Set a restriction on which assets can be ordered.
Parameters
----------
restricted_list : Restrictions
An object providing information about restricted assets.
See Also
--------
zipl... | def set_asset_restrictions(self, restrictions, on_error='fail'):
"""Set a restriction on which assets can be ordered.
Parameters
----------
restricted_list : Restrictions
An object providing information about restricted assets.
See Also
--------
zipl... | [
"Set",
"a",
"restriction",
"on",
"which",
"assets",
"can",
"be",
"ordered",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L2195-L2209 | [
"def",
"set_asset_restrictions",
"(",
"self",
",",
"restrictions",
",",
"on_error",
"=",
"'fail'",
")",
":",
"control",
"=",
"RestrictedListOrder",
"(",
"on_error",
",",
"restrictions",
")",
"self",
".",
"register_trading_control",
"(",
"control",
")",
"self",
"... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.attach_pipeline | Register a pipeline to be computed at the start of each day.
Parameters
----------
pipeline : Pipeline
The pipeline to have computed.
name : str
The name of the pipeline.
chunks : int or iterator, optional
The number of days to compute pipelin... | zipline/algorithm.py | def attach_pipeline(self, pipeline, name, chunks=None, eager=True):
"""Register a pipeline to be computed at the start of each day.
Parameters
----------
pipeline : Pipeline
The pipeline to have computed.
name : str
The name of the pipeline.
chunk... | def attach_pipeline(self, pipeline, name, chunks=None, eager=True):
"""Register a pipeline to be computed at the start of each day.
Parameters
----------
pipeline : Pipeline
The pipeline to have computed.
name : str
The name of the pipeline.
chunk... | [
"Register",
"a",
"pipeline",
"to",
"be",
"computed",
"at",
"the",
"start",
"of",
"each",
"day",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L2228-L2270 | [
"def",
"attach_pipeline",
"(",
"self",
",",
"pipeline",
",",
"name",
",",
"chunks",
"=",
"None",
",",
"eager",
"=",
"True",
")",
":",
"if",
"chunks",
"is",
"None",
":",
"# Make the first chunk smaller to get more immediate results:",
"# (one week, then every half year... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.pipeline_output | Get the results of the pipeline that was attached with the name:
``name``.
Parameters
----------
name : str
Name of the pipeline for which results are requested.
Returns
-------
results : pd.DataFrame
DataFrame containing the results of t... | zipline/algorithm.py | def pipeline_output(self, name):
"""Get the results of the pipeline that was attached with the name:
``name``.
Parameters
----------
name : str
Name of the pipeline for which results are requested.
Returns
-------
results : pd.DataFrame
... | def pipeline_output(self, name):
"""Get the results of the pipeline that was attached with the name:
``name``.
Parameters
----------
name : str
Name of the pipeline for which results are requested.
Returns
-------
results : pd.DataFrame
... | [
"Get",
"the",
"results",
"of",
"the",
"pipeline",
"that",
"was",
"attached",
"with",
"the",
"name",
":",
"name",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L2274-L2306 | [
"def",
"pipeline_output",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"pipe",
",",
"chunks",
",",
"_",
"=",
"self",
".",
"_pipelines",
"[",
"name",
"]",
"except",
"KeyError",
":",
"raise",
"NoSuchPipeline",
"(",
"name",
"=",
"name",
",",
"valid",
... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm._pipeline_output | Internal implementation of `pipeline_output`. | zipline/algorithm.py | def _pipeline_output(self, pipeline, chunks, name):
"""
Internal implementation of `pipeline_output`.
"""
today = normalize_date(self.get_datetime())
try:
data = self._pipeline_cache.get(name, today)
except KeyError:
# Calculate the next block.
... | def _pipeline_output(self, pipeline, chunks, name):
"""
Internal implementation of `pipeline_output`.
"""
today = normalize_date(self.get_datetime())
try:
data = self._pipeline_cache.get(name, today)
except KeyError:
# Calculate the next block.
... | [
"Internal",
"implementation",
"of",
"pipeline_output",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L2308-L2328 | [
"def",
"_pipeline_output",
"(",
"self",
",",
"pipeline",
",",
"chunks",
",",
"name",
")",
":",
"today",
"=",
"normalize_date",
"(",
"self",
".",
"get_datetime",
"(",
")",
")",
"try",
":",
"data",
"=",
"self",
".",
"_pipeline_cache",
".",
"get",
"(",
"n... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.run_pipeline | Compute `pipeline`, providing values for at least `start_date`.
Produces a DataFrame containing data for days between `start_date` and
`end_date`, where `end_date` is defined by:
`end_date = min(start_date + chunksize trading days,
simulation_end)`
Retu... | zipline/algorithm.py | def run_pipeline(self, pipeline, start_session, chunksize):
"""
Compute `pipeline`, providing values for at least `start_date`.
Produces a DataFrame containing data for days between `start_date` and
`end_date`, where `end_date` is defined by:
`end_date = min(start_date + ch... | def run_pipeline(self, pipeline, start_session, chunksize):
"""
Compute `pipeline`, providing values for at least `start_date`.
Produces a DataFrame containing data for days between `start_date` and
`end_date`, where `end_date` is defined by:
`end_date = min(start_date + ch... | [
"Compute",
"pipeline",
"providing",
"values",
"for",
"at",
"least",
"start_date",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L2330-L2366 | [
"def",
"run_pipeline",
"(",
"self",
",",
"pipeline",
",",
"start_session",
",",
"chunksize",
")",
":",
"sessions",
"=",
"self",
".",
"trading_calendar",
".",
"all_sessions",
"# Load data starting from the previous trading day...",
"start_date_loc",
"=",
"sessions",
".",... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | TradingAlgorithm.all_api_methods | Return a list of all the TradingAlgorithm API methods. | zipline/algorithm.py | def all_api_methods(cls):
"""
Return a list of all the TradingAlgorithm API methods.
"""
return [
fn for fn in itervalues(vars(cls))
if getattr(fn, 'is_api_method', False)
] | def all_api_methods(cls):
"""
Return a list of all the TradingAlgorithm API methods.
"""
return [
fn for fn in itervalues(vars(cls))
if getattr(fn, 'is_api_method', False)
] | [
"Return",
"a",
"list",
"of",
"all",
"the",
"TradingAlgorithm",
"API",
"methods",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L2394-L2401 | [
"def",
"all_api_methods",
"(",
"cls",
")",
":",
"return",
"[",
"fn",
"for",
"fn",
"in",
"itervalues",
"(",
"vars",
"(",
"cls",
")",
")",
"if",
"getattr",
"(",
"fn",
",",
"'is_api_method'",
",",
"False",
")",
"]"
] | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | bulleted_list | Format a bulleted list of values. | zipline/utils/string_formatting.py | def bulleted_list(items, max_count=None, indent=2):
"""Format a bulleted list of values.
"""
if max_count is not None and len(items) > max_count:
item_list = list(items)
items = item_list[:max_count - 1]
items.append('...')
items.append(item_list[-1])
line_template = (" ... | def bulleted_list(items, max_count=None, indent=2):
"""Format a bulleted list of values.
"""
if max_count is not None and len(items) > max_count:
item_list = list(items)
items = item_list[:max_count - 1]
items.append('...')
items.append(item_list[-1])
line_template = (" ... | [
"Format",
"a",
"bulleted",
"list",
"of",
"values",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/string_formatting.py#L1-L11 | [
"def",
"bulleted_list",
"(",
"items",
",",
"max_count",
"=",
"None",
",",
"indent",
"=",
"2",
")",
":",
"if",
"max_count",
"is",
"not",
"None",
"and",
"len",
"(",
"items",
")",
">",
"max_count",
":",
"item_list",
"=",
"list",
"(",
"items",
")",
"item... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
train | _expect_extra | Checks for the presence of an extra to the argument list. Raises expections
if this is unexpected or if it is missing and expected. | zipline/utils/argcheck.py | def _expect_extra(expected, present, exc_unexpected, exc_missing, exc_args):
"""
Checks for the presence of an extra to the argument list. Raises expections
if this is unexpected or if it is missing and expected.
"""
if present:
if not expected:
raise exc_unexpected(*exc_args)
... | def _expect_extra(expected, present, exc_unexpected, exc_missing, exc_args):
"""
Checks for the presence of an extra to the argument list. Raises expections
if this is unexpected or if it is missing and expected.
"""
if present:
if not expected:
raise exc_unexpected(*exc_args)
... | [
"Checks",
"for",
"the",
"presence",
"of",
"an",
"extra",
"to",
"the",
"argument",
"list",
".",
"Raises",
"expections",
"if",
"this",
"is",
"unexpected",
"or",
"if",
"it",
"is",
"missing",
"and",
"expected",
"."
] | quantopian/zipline | python | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/argcheck.py#L131-L140 | [
"def",
"_expect_extra",
"(",
"expected",
",",
"present",
",",
"exc_unexpected",
",",
"exc_missing",
",",
"exc_args",
")",
":",
"if",
"present",
":",
"if",
"not",
"expected",
":",
"raise",
"exc_unexpected",
"(",
"*",
"exc_args",
")",
"elif",
"expected",
"and"... | 77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.