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 Raises ------ AssetDBVersionError If the version is in the table and not equal to ASSET_DB_VERSION.
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 expected_version : int The expected version of the asset database Raises ------ AssetDBVersionError If the version is in the table and not equal to ASSET_DB_VERSION. """ # Read the version out of the table version_from_table = conn.execute( sa.select((version_table.c.version,)), ).scalar() # A db without a version is considered v0 if version_from_table is None: version_from_table = 0 # Raise an error if the versions do not match if (version_from_table != expected_version): raise AssetDBVersionError(db_version=version_from_table, expected_version=expected_version)
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 expected_version : int The expected version of the asset database Raises ------ AssetDBVersionError If the version is in the table and not equal to ASSET_DB_VERSION. """ # Read the version out of the table version_from_table = conn.execute( sa.select((version_table.c.version,)), ).scalar() # A db without a version is considered v0 if version_from_table is None: version_from_table = 0 # Raise an error if the versions do not match if (version_from_table != expected_version): raise AssetDBVersionError(db_version=version_from_table, expected_version=expected_version)
[ "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_value : int The version to write in to the database """ conn.execute(sa.insert(version_table, values={'version': version_value}))
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_value : int The version to write in to the database """ conn.execute(sa.insert(version_table, values={'version': version_value}))
[ "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 this equity. asset_name : str The full name for this asset. start_date : datetime The date when this asset was created. end_date : datetime, optional The last date we have trade data for this asset. first_traded : datetime, optional The first date we have trade data for this asset. auto_close_date : datetime, optional The date on which to close any positions in this asset. exchange : str The exchange where this asset is traded. The index of this dataframe should contain the sids. futures : pd.DataFrame, optional The future contract metadata. The columns for this dataframe are: symbol : str The ticker symbol for this futures contract. root_symbol : str The root symbol, or the symbol with the expiration stripped out. asset_name : str The full name for this asset. start_date : datetime, optional The date when this asset was created. end_date : datetime, optional The last date we have trade data for this asset. first_traded : datetime, optional The first date we have trade data for this asset. exchange : str The exchange where this asset is traded. notice_date : datetime The date when the owner of the contract may be forced to take physical delivery of the contract's asset. expiration_date : datetime The date when the contract expires. auto_close_date : datetime The date when the broker will automatically close any positions in this contract. tick_size : float The minimum price movement of the contract. multiplier: float The amount of the underlying asset represented by this contract. exchanges : pd.DataFrame, optional The exchanges where assets can be traded. The columns of this dataframe are: exchange : str The full name of the exchange. canonical_name : str The canonical name of the exchange. country_code : str The ISO 3166 alpha-2 country code of the exchange. root_symbols : pd.DataFrame, optional The root symbols for the futures contracts. The columns for this dataframe are: root_symbol : str The root symbol name. root_symbol_id : int The unique id for this root symbol. sector : string, optional The sector of this root symbol. description : string, optional A short description of this root symbol. exchange : str The exchange where this root symbol is traded. equity_supplementary_mappings : pd.DataFrame, optional Additional mappings from values of abitrary type to assets. chunk_size : int, optional The amount of rows to write to the SQLite table at once. This defaults to the default number of bind params in sqlite. If you have compiled sqlite3 with more bind or less params you may want to pass that value here.
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_CHUNK_SIZE): """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 this equity. asset_name : str The full name for this asset. start_date : datetime The date when this asset was created. end_date : datetime, optional The last date we have trade data for this asset. first_traded : datetime, optional The first date we have trade data for this asset. auto_close_date : datetime, optional The date on which to close any positions in this asset. exchange : str The exchange where this asset is traded. The index of this dataframe should contain the sids. futures : pd.DataFrame, optional The future contract metadata. The columns for this dataframe are: symbol : str The ticker symbol for this futures contract. root_symbol : str The root symbol, or the symbol with the expiration stripped out. asset_name : str The full name for this asset. start_date : datetime, optional The date when this asset was created. end_date : datetime, optional The last date we have trade data for this asset. first_traded : datetime, optional The first date we have trade data for this asset. exchange : str The exchange where this asset is traded. notice_date : datetime The date when the owner of the contract may be forced to take physical delivery of the contract's asset. expiration_date : datetime The date when the contract expires. auto_close_date : datetime The date when the broker will automatically close any positions in this contract. tick_size : float The minimum price movement of the contract. multiplier: float The amount of the underlying asset represented by this contract. exchanges : pd.DataFrame, optional The exchanges where assets can be traded. The columns of this dataframe are: exchange : str The full name of the exchange. canonical_name : str The canonical name of the exchange. country_code : str The ISO 3166 alpha-2 country code of the exchange. root_symbols : pd.DataFrame, optional The root symbols for the futures contracts. The columns for this dataframe are: root_symbol : str The root symbol name. root_symbol_id : int The unique id for this root symbol. sector : string, optional The sector of this root symbol. description : string, optional A short description of this root symbol. exchange : str The exchange where this root symbol is traded. equity_supplementary_mappings : pd.DataFrame, optional Additional mappings from values of abitrary type to assets. chunk_size : int, optional The amount of rows to write to the SQLite table at once. This defaults to the default number of bind params in sqlite. If you have compiled sqlite3 with more bind or less params you may want to pass that value here. """ if equities is not None: equities = _generate_output_dataframe( equities, _direct_equities_defaults, ) if equity_symbol_mappings is None: raise ValueError( 'equities provided with no symbol mapping data', ) equity_symbol_mappings = _generate_output_dataframe( equity_symbol_mappings, _equity_symbol_mappings_defaults, ) _check_symbol_mappings( equity_symbol_mappings, exchanges, equities['exchange'], ) if equity_supplementary_mappings is not None: equity_supplementary_mappings = _generate_output_dataframe( equity_supplementary_mappings, _equity_supplementary_mappings_defaults, ) if futures is not None: futures = _generate_output_dataframe(_futures_defaults, futures) if exchanges is not None: exchanges = _generate_output_dataframe( exchanges.set_index('exchange'), _exchanges_defaults, ) if root_symbols is not None: root_symbols = _generate_output_dataframe( root_symbols, _root_symbols_defaults, ) # Set named identifier columns as indices, if provided. _normalize_index_columns_in_place( equities=equities, equity_supplementary_mappings=equity_supplementary_mappings, futures=futures, exchanges=exchanges, root_symbols=root_symbols, ) self._real_write( equities=equities, equity_symbol_mappings=equity_symbol_mappings, equity_supplementary_mappings=equity_supplementary_mappings, futures=futures, exchanges=exchanges, root_symbols=root_symbols, chunk_size=chunk_size, )
def write_direct(self, equities=None, equity_symbol_mappings=None, equity_supplementary_mappings=None, futures=None, exchanges=None, root_symbols=None, chunk_size=DEFAULT_CHUNK_SIZE): """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 this equity. asset_name : str The full name for this asset. start_date : datetime The date when this asset was created. end_date : datetime, optional The last date we have trade data for this asset. first_traded : datetime, optional The first date we have trade data for this asset. auto_close_date : datetime, optional The date on which to close any positions in this asset. exchange : str The exchange where this asset is traded. The index of this dataframe should contain the sids. futures : pd.DataFrame, optional The future contract metadata. The columns for this dataframe are: symbol : str The ticker symbol for this futures contract. root_symbol : str The root symbol, or the symbol with the expiration stripped out. asset_name : str The full name for this asset. start_date : datetime, optional The date when this asset was created. end_date : datetime, optional The last date we have trade data for this asset. first_traded : datetime, optional The first date we have trade data for this asset. exchange : str The exchange where this asset is traded. notice_date : datetime The date when the owner of the contract may be forced to take physical delivery of the contract's asset. expiration_date : datetime The date when the contract expires. auto_close_date : datetime The date when the broker will automatically close any positions in this contract. tick_size : float The minimum price movement of the contract. multiplier: float The amount of the underlying asset represented by this contract. exchanges : pd.DataFrame, optional The exchanges where assets can be traded. The columns of this dataframe are: exchange : str The full name of the exchange. canonical_name : str The canonical name of the exchange. country_code : str The ISO 3166 alpha-2 country code of the exchange. root_symbols : pd.DataFrame, optional The root symbols for the futures contracts. The columns for this dataframe are: root_symbol : str The root symbol name. root_symbol_id : int The unique id for this root symbol. sector : string, optional The sector of this root symbol. description : string, optional A short description of this root symbol. exchange : str The exchange where this root symbol is traded. equity_supplementary_mappings : pd.DataFrame, optional Additional mappings from values of abitrary type to assets. chunk_size : int, optional The amount of rows to write to the SQLite table at once. This defaults to the default number of bind params in sqlite. If you have compiled sqlite3 with more bind or less params you may want to pass that value here. """ if equities is not None: equities = _generate_output_dataframe( equities, _direct_equities_defaults, ) if equity_symbol_mappings is None: raise ValueError( 'equities provided with no symbol mapping data', ) equity_symbol_mappings = _generate_output_dataframe( equity_symbol_mappings, _equity_symbol_mappings_defaults, ) _check_symbol_mappings( equity_symbol_mappings, exchanges, equities['exchange'], ) if equity_supplementary_mappings is not None: equity_supplementary_mappings = _generate_output_dataframe( equity_supplementary_mappings, _equity_supplementary_mappings_defaults, ) if futures is not None: futures = _generate_output_dataframe(_futures_defaults, futures) if exchanges is not None: exchanges = _generate_output_dataframe( exchanges.set_index('exchange'), _exchanges_defaults, ) if root_symbols is not None: root_symbols = _generate_output_dataframe( root_symbols, _root_symbols_defaults, ) # Set named identifier columns as indices, if provided. _normalize_index_columns_in_place( equities=equities, equity_supplementary_mappings=equity_supplementary_mappings, futures=futures, exchanges=exchanges, root_symbols=root_symbols, ) self._real_write( equities=equities, equity_symbol_mappings=equity_symbol_mappings, equity_supplementary_mappings=equity_supplementary_mappings, futures=futures, exchanges=exchanges, root_symbols=root_symbols, chunk_size=chunk_size, )
[ "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 The full name for this asset. start_date : datetime The date when this asset was created. end_date : datetime, optional The last date we have trade data for this asset. first_traded : datetime, optional The first date we have trade data for this asset. auto_close_date : datetime, optional The date on which to close any positions in this asset. exchange : str The exchange where this asset is traded. The index of this dataframe should contain the sids. futures : pd.DataFrame, optional The future contract metadata. The columns for this dataframe are: symbol : str The ticker symbol for this futures contract. root_symbol : str The root symbol, or the symbol with the expiration stripped out. asset_name : str The full name for this asset. start_date : datetime, optional The date when this asset was created. end_date : datetime, optional The last date we have trade data for this asset. first_traded : datetime, optional The first date we have trade data for this asset. exchange : str The exchange where this asset is traded. notice_date : datetime The date when the owner of the contract may be forced to take physical delivery of the contract's asset. expiration_date : datetime The date when the contract expires. auto_close_date : datetime The date when the broker will automatically close any positions in this contract. tick_size : float The minimum price movement of the contract. multiplier: float The amount of the underlying asset represented by this contract. exchanges : pd.DataFrame, optional The exchanges where assets can be traded. The columns of this dataframe are: exchange : str The full name of the exchange. canonical_name : str The canonical name of the exchange. country_code : str The ISO 3166 alpha-2 country code of the exchange. root_symbols : pd.DataFrame, optional The root symbols for the futures contracts. The columns for this dataframe are: root_symbol : str The root symbol name. root_symbol_id : int The unique id for this root symbol. sector : string, optional The sector of this root symbol. description : string, optional A short description of this root symbol. exchange : str The exchange where this root symbol is traded. equity_supplementary_mappings : pd.DataFrame, optional Additional mappings from values of abitrary type to assets. chunk_size : int, optional The amount of rows to write to the SQLite table at once. This defaults to the default number of bind params in sqlite. If you have compiled sqlite3 with more bind or less params you may want to pass that value here. See Also -------- zipline.assets.asset_finder
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 ---------- equities : pd.DataFrame, optional The equity metadata. The columns for this dataframe are: symbol : str The ticker symbol for this equity. asset_name : str The full name for this asset. start_date : datetime The date when this asset was created. end_date : datetime, optional The last date we have trade data for this asset. first_traded : datetime, optional The first date we have trade data for this asset. auto_close_date : datetime, optional The date on which to close any positions in this asset. exchange : str The exchange where this asset is traded. The index of this dataframe should contain the sids. futures : pd.DataFrame, optional The future contract metadata. The columns for this dataframe are: symbol : str The ticker symbol for this futures contract. root_symbol : str The root symbol, or the symbol with the expiration stripped out. asset_name : str The full name for this asset. start_date : datetime, optional The date when this asset was created. end_date : datetime, optional The last date we have trade data for this asset. first_traded : datetime, optional The first date we have trade data for this asset. exchange : str The exchange where this asset is traded. notice_date : datetime The date when the owner of the contract may be forced to take physical delivery of the contract's asset. expiration_date : datetime The date when the contract expires. auto_close_date : datetime The date when the broker will automatically close any positions in this contract. tick_size : float The minimum price movement of the contract. multiplier: float The amount of the underlying asset represented by this contract. exchanges : pd.DataFrame, optional The exchanges where assets can be traded. The columns of this dataframe are: exchange : str The full name of the exchange. canonical_name : str The canonical name of the exchange. country_code : str The ISO 3166 alpha-2 country code of the exchange. root_symbols : pd.DataFrame, optional The root symbols for the futures contracts. The columns for this dataframe are: root_symbol : str The root symbol name. root_symbol_id : int The unique id for this root symbol. sector : string, optional The sector of this root symbol. description : string, optional A short description of this root symbol. exchange : str The exchange where this root symbol is traded. equity_supplementary_mappings : pd.DataFrame, optional Additional mappings from values of abitrary type to assets. chunk_size : int, optional The amount of rows to write to the SQLite table at once. This defaults to the default number of bind params in sqlite. If you have compiled sqlite3 with more bind or less params you may want to pass that value here. See Also -------- zipline.assets.asset_finder """ if exchanges is None: exchange_names = [ df['exchange'] for df in (equities, futures, root_symbols) if df is not None ] if exchange_names: exchanges = pd.DataFrame({ 'exchange': pd.concat(exchange_names).unique(), }) data = self._load_data( equities if equities is not None else pd.DataFrame(), futures if futures is not None else pd.DataFrame(), exchanges if exchanges is not None else pd.DataFrame(), root_symbols if root_symbols is not None else pd.DataFrame(), ( equity_supplementary_mappings if equity_supplementary_mappings is not None else pd.DataFrame() ), ) self._real_write( equities=data.equities, equity_symbol_mappings=data.equities_mappings, equity_supplementary_mappings=data.equity_supplementary_mappings, futures=data.futures, root_symbols=data.root_symbols, exchanges=data.exchanges, chunk_size=chunk_size, )
def write(self, equities=None, futures=None, exchanges=None, root_symbols=None, equity_supplementary_mappings=None, chunk_size=DEFAULT_CHUNK_SIZE): """Write asset metadata to a sqlite database. Parameters ---------- equities : pd.DataFrame, optional The equity metadata. The columns for this dataframe are: symbol : str The ticker symbol for this equity. asset_name : str The full name for this asset. start_date : datetime The date when this asset was created. end_date : datetime, optional The last date we have trade data for this asset. first_traded : datetime, optional The first date we have trade data for this asset. auto_close_date : datetime, optional The date on which to close any positions in this asset. exchange : str The exchange where this asset is traded. The index of this dataframe should contain the sids. futures : pd.DataFrame, optional The future contract metadata. The columns for this dataframe are: symbol : str The ticker symbol for this futures contract. root_symbol : str The root symbol, or the symbol with the expiration stripped out. asset_name : str The full name for this asset. start_date : datetime, optional The date when this asset was created. end_date : datetime, optional The last date we have trade data for this asset. first_traded : datetime, optional The first date we have trade data for this asset. exchange : str The exchange where this asset is traded. notice_date : datetime The date when the owner of the contract may be forced to take physical delivery of the contract's asset. expiration_date : datetime The date when the contract expires. auto_close_date : datetime The date when the broker will automatically close any positions in this contract. tick_size : float The minimum price movement of the contract. multiplier: float The amount of the underlying asset represented by this contract. exchanges : pd.DataFrame, optional The exchanges where assets can be traded. The columns of this dataframe are: exchange : str The full name of the exchange. canonical_name : str The canonical name of the exchange. country_code : str The ISO 3166 alpha-2 country code of the exchange. root_symbols : pd.DataFrame, optional The root symbols for the futures contracts. The columns for this dataframe are: root_symbol : str The root symbol name. root_symbol_id : int The unique id for this root symbol. sector : string, optional The sector of this root symbol. description : string, optional A short description of this root symbol. exchange : str The exchange where this root symbol is traded. equity_supplementary_mappings : pd.DataFrame, optional Additional mappings from values of abitrary type to assets. chunk_size : int, optional The amount of rows to write to the SQLite table at once. This defaults to the default number of bind params in sqlite. If you have compiled sqlite3 with more bind or less params you may want to pass that value here. See Also -------- zipline.assets.asset_finder """ if exchanges is None: exchange_names = [ df['exchange'] for df in (equities, futures, root_symbols) if df is not None ] if exchange_names: exchanges = pd.DataFrame({ 'exchange': pd.concat(exchange_names).unique(), }) data = self._load_data( equities if equities is not None else pd.DataFrame(), futures if futures is not None else pd.DataFrame(), exchanges if exchanges is not None else pd.DataFrame(), root_symbols if root_symbols is not None else pd.DataFrame(), ( equity_supplementary_mappings if equity_supplementary_mappings is not None else pd.DataFrame() ), ) self._real_write( equities=data.equities, equity_symbol_mappings=data.equities_mappings, equity_supplementary_mappings=data.equity_supplementary_mappings, futures=data.futures, root_symbols=data.root_symbols, exchanges=data.exchanges, chunk_size=chunk_size, )
[ "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 tables are present, otherwise False. """ conn = txn.connect() for table_name in asset_db_table_names: if txn.dialect.has_table(conn, table_name): return True return False
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 tables are present, otherwise False. """ conn = txn.connect() for table_name in asset_db_table_names: if txn.dialect.has_table(conn, table_name): return True return False
[ "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.MetaData The metadata that describes the new assets db.
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 ------- metadata : sa.MetaData The metadata that describes the new assets db. """ with ExitStack() as stack: if txn is None: txn = stack.enter_context(self.engine.begin()) tables_already_exist = self._all_tables_present(txn) # Create the SQL tables if they do not already exist. metadata.create_all(txn, checkfirst=True) if tables_already_exist: check_version_info(txn, version_info, ASSET_DB_VERSION) else: write_version_info(txn, version_info, ASSET_DB_VERSION)
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 ------- metadata : sa.MetaData The metadata that describes the new assets db. """ with ExitStack() as stack: if txn is None: txn = stack.enter_context(self.engine.begin()) tables_already_exist = self._all_tables_present(txn) # Create the SQL tables if they do not already exist. metadata.create_all(txn, checkfirst=True) if tables_already_exist: check_version_info(txn, version_info, ASSET_DB_VERSION) else: write_version_info(txn, version_info, ASSET_DB_VERSION)
[ "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 """ # Set named identifier columns as indices, if provided. _normalize_index_columns_in_place( equities=equities, equity_supplementary_mappings=equity_supplementary_mappings, futures=futures, exchanges=exchanges, root_symbols=root_symbols, ) futures_output = self._normalize_futures(futures) equity_supplementary_mappings_output = ( self._normalize_equity_supplementary_mappings( equity_supplementary_mappings, ) ) exchanges_output = _generate_output_dataframe( data_subset=exchanges, defaults=_exchanges_defaults, ) equities_output, equities_mappings = self._normalize_equities( equities, exchanges_output, ) root_symbols_output = _generate_output_dataframe( data_subset=root_symbols, defaults=_root_symbols_defaults, ) return AssetData( equities=equities_output, equities_mappings=equities_mappings, futures=futures_output, exchanges=exchanges_output, root_symbols=root_symbols_output, equity_supplementary_mappings=equity_supplementary_mappings_output, )
def _load_data(self, equities, futures, exchanges, root_symbols, equity_supplementary_mappings): """ Returns a standard set of pandas.DataFrames: equities, futures, exchanges, root_symbols """ # Set named identifier columns as indices, if provided. _normalize_index_columns_in_place( equities=equities, equity_supplementary_mappings=equity_supplementary_mappings, futures=futures, exchanges=exchanges, root_symbols=root_symbols, ) futures_output = self._normalize_futures(futures) equity_supplementary_mappings_output = ( self._normalize_equity_supplementary_mappings( equity_supplementary_mappings, ) ) exchanges_output = _generate_output_dataframe( data_subset=exchanges, defaults=_exchanges_defaults, ) equities_output, equities_mappings = self._normalize_equities( equities, exchanges_output, ) root_symbols_output = _generate_output_dataframe( data_subset=root_symbols, defaults=_root_symbols_defaults, ) return AssetData( equities=equities_output, equities_mappings=equities_mappings, futures=futures_output, exchanges=exchanges_output, root_symbols=root_symbols_output, equity_supplementary_mappings=equity_supplementary_mappings_output, )
[ "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 The datetime when data should no longer be considered available for a session. expr : expr the expression representing the data to load. odo_kwargs : dict extra keyword arguments to pass to odo when executing the expression. checkpoints : expr, optional the expression representing the checkpointed data for `expr`. Returns ------- raw : pd.dataframe The result of computing expr and materializing the result as a dataframe.
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 with a `sid` field. Parameters ---------- assets : pd.int64index the assets to load data for. data_query_cutoff_times : pd.DatetimeIndex The datetime when data should no longer be considered available for a session. expr : expr the expression representing the data to load. odo_kwargs : dict extra keyword arguments to pass to odo when executing the expression. checkpoints : expr, optional the expression representing the checkpointed data for `expr`. Returns ------- raw : pd.dataframe The result of computing expr and materializing the result as a dataframe. """ lower_dt, upper_dt = data_query_cutoff_times[[0, -1]] raw = ffill_query_in_range( expr, lower_dt, upper_dt, checkpoints=checkpoints, odo_kwargs=odo_kwargs, ) sids = raw[SID_FIELD_NAME] raw.drop( sids[~sids.isin(assets)].index, inplace=True ) return raw
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 with a `sid` field. Parameters ---------- assets : pd.int64index the assets to load data for. data_query_cutoff_times : pd.DatetimeIndex The datetime when data should no longer be considered available for a session. expr : expr the expression representing the data to load. odo_kwargs : dict extra keyword arguments to pass to odo when executing the expression. checkpoints : expr, optional the expression representing the checkpointed data for `expr`. Returns ------- raw : pd.dataframe The result of computing expr and materializing the result as a dataframe. """ lower_dt, upper_dt = data_query_cutoff_times[[0, -1]] raw = ffill_query_in_range( expr, lower_dt, upper_dt, checkpoints=checkpoints, odo_kwargs=odo_kwargs, ) sids = raw[SID_FIELD_NAME] raw.drop( sids[~sids.isin(assets)].index, inplace=True ) return raw
[ "Given", "an", "expression", "representing", "data", "to", "load", "perform", "normalization", "and", "forward", "-", "filling", "and", "return", "the", "data", "materialized", ".", "Only", "accepts", "data", "with", "a", "sid", "field", "." ]
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 tuple length is not 2 or 3. """ if len(tup) not in (2, 3): raise ValueError( 'tuple must contain 2 or 3 elements, not: %d (%r' % ( len(tup), tup, ), ) return range(*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 tuple length is not 2 or 3. """ if len(tup) not in (2, 3): raise ValueError( 'tuple must contain 2 or 3 elements, not: %d (%r' % ( len(tup), tup, ), ) return range(*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 to from_tuple or a range to return. Returns ------- range : range The input to convert to a range. Raises ------ ValueError Raised when the input is not a tuple or a range. ValueError is also raised if the input is a tuple whose length is not 2 or 3.
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 : tuple or range A tuple to pass to from_tuple or a range to return. Returns ------- range : range The input to convert to a range. Raises ------ ValueError Raised when the input is not a tuple or a range. ValueError is also raised if the input is a tuple whose length is not 2 or 3. """ if isinstance(tup_or_range, tuple): return from_tuple(tup_or_range) elif isinstance(tup_or_range, range): return tup_or_range raise ValueError( 'maybe_from_tuple expects a tuple or range, got %r: %r' % ( type(tup_or_range).__name__, 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 : tuple or range A tuple to pass to from_tuple or a range to return. Returns ------- range : range The input to convert to a range. Raises ------ ValueError Raised when the input is not a tuple or a range. ValueError is also raised if the input is a tuple whose length is not 2 or 3. """ if isinstance(tup_or_range, tuple): return from_tuple(tup_or_range) elif isinstance(tup_or_range, range): return tup_or_range raise ValueError( 'maybe_from_tuple expects a tuple or range, got %r: %r' % ( type(tup_or_range).__name__, 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: raise ValueError('a.step must be equal to 1, got: %s' % a.step) if b.step != 1: raise ValueError('b.step must be equal to 1, got: %s' % b.step)
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: raise ValueError('a.step must be equal to 1, got: %s' % a.step) if b.step != 1: raise ValueError('b.step must be equal to 1, got: %s' % b.step)
[ "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 != 1. """ _check_steps(a, b) return a.stop >= b.start and b.stop >= a.start
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 != 1. """ _check_steps(a, b) return a.stop >= b.start and b.stop >= a.start
[ "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: yield r
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: yield r
[ "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 -------- >>> ranges = [range(0, 1), range(2, 5), range(4, 7)] >>> list(intersecting_ranges(ranges)) [range(2, 5), range(4, 7)] >>> ranges = [range(0, 1), range(2, 3)] >>> list(intersecting_ranges(ranges)) [] >>> ranges = [range(0, 1), range(1, 2)] >>> list(intersecting_ranges(ranges)) [range(0, 1), range(1, 2)]
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 ``ranges``. Examples -------- >>> ranges = [range(0, 1), range(2, 5), range(4, 7)] >>> list(intersecting_ranges(ranges)) [range(2, 5), range(4, 7)] >>> ranges = [range(0, 1), range(2, 3)] >>> list(intersecting_ranges(ranges)) [] >>> ranges = [range(0, 1), range(1, 2)] >>> list(intersecting_ranges(ranges)) [range(0, 1), range(1, 2)] """ ranges = sorted(ranges, key=op.attrgetter('start')) return sorted_diff(ranges, group_ranges(ranges))
def intersecting_ranges(ranges): """Return any ranges that intersect. Parameters ---------- ranges : iterable[ranges] A sequence of ranges to check for intersections. Returns ------- intersections : iterable[ranges] A sequence of all of the ranges that intersected in ``ranges``. Examples -------- >>> ranges = [range(0, 1), range(2, 5), range(4, 7)] >>> list(intersecting_ranges(ranges)) [range(2, 5), range(4, 7)] >>> ranges = [range(0, 1), range(2, 3)] >>> list(intersecting_ranges(ranges)) [] >>> ranges = [range(0, 1), range(1, 2)] >>> list(intersecting_ranges(ranges)) [range(0, 1), range(1, 2)] """ ranges = sorted(ranges, key=op.attrgetter('start')) return sorted_diff(ranges, group_ranges(ranges))
[ "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)) first, last = dts[[0, -1]] return (first <= first_date) and (last >= last_date)
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)) first, last = dts[[0, -1]] return (first <= first_date) and (last >= last_date)
[ "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 bonds from the Bank of Canada is also available. Results downloaded from the internet are cached in ~/.zipline/data. Subsequent loads will attempt to read from the cached files before falling back to redownload. Parameters ---------- trading_day : pandas.CustomBusinessDay, optional A trading_day used to determine the latest day for which we expect to have data. Defaults to an NYSE trading day. trading_days : pd.DatetimeIndex, optional A calendar of trading days. Also used for determining what cached dates we should expect to have cached. Defaults to the NYSE calendar. bm_symbol : str, optional Symbol for the benchmark index to load. Defaults to 'SPY', the ticker for the S&P 500, provided by IEX Trading. Returns ------- (benchmark_returns, treasury_curves) : (pd.Series, pd.DataFrame) Notes ----- Both return values are DatetimeIndexed with values dated to midnight in UTC of each stored date. The columns of `treasury_curves` are: '1month', '3month', '6month', '1year','2year','3year','5year','7year','10year','20year','30year'
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 Bond rates and are downloaded from 'www.federalreserve.gov' by default. For Canadian exchanges, a loader for Canadian bonds from the Bank of Canada is also available. Results downloaded from the internet are cached in ~/.zipline/data. Subsequent loads will attempt to read from the cached files before falling back to redownload. Parameters ---------- trading_day : pandas.CustomBusinessDay, optional A trading_day used to determine the latest day for which we expect to have data. Defaults to an NYSE trading day. trading_days : pd.DatetimeIndex, optional A calendar of trading days. Also used for determining what cached dates we should expect to have cached. Defaults to the NYSE calendar. bm_symbol : str, optional Symbol for the benchmark index to load. Defaults to 'SPY', the ticker for the S&P 500, provided by IEX Trading. Returns ------- (benchmark_returns, treasury_curves) : (pd.Series, pd.DataFrame) Notes ----- Both return values are DatetimeIndexed with values dated to midnight in UTC of each stored date. The columns of `treasury_curves` are: '1month', '3month', '6month', '1year','2year','3year','5year','7year','10year','20year','30year' """ if trading_day is None: trading_day = get_calendar('XNYS').day if trading_days is None: trading_days = get_calendar('XNYS').all_sessions first_date = trading_days[0] now = pd.Timestamp.utcnow() # we will fill missing benchmark data through latest trading date last_date = trading_days[trading_days.get_loc(now, method='ffill')] br = ensure_benchmark_data( bm_symbol, first_date, last_date, now, # We need the trading_day to figure out the close prior to the first # date so that we can compute returns for the first date. trading_day, environ, ) tc = ensure_treasury_data( bm_symbol, first_date, last_date, now, environ, ) # combine dt indices and reindex using ffill then bfill all_dt = br.index.union(tc.index) br = br.reindex(all_dt, method='ffill').fillna(method='bfill') tc = tc.reindex(all_dt, method='ffill').fillna(method='bfill') benchmark_returns = br[br.index.slice_indexer(first_date, last_date)] treasury_curves = tc[tc.index.slice_indexer(first_date, last_date)] return benchmark_returns, treasury_curves
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 Bond rates and are downloaded from 'www.federalreserve.gov' by default. For Canadian exchanges, a loader for Canadian bonds from the Bank of Canada is also available. Results downloaded from the internet are cached in ~/.zipline/data. Subsequent loads will attempt to read from the cached files before falling back to redownload. Parameters ---------- trading_day : pandas.CustomBusinessDay, optional A trading_day used to determine the latest day for which we expect to have data. Defaults to an NYSE trading day. trading_days : pd.DatetimeIndex, optional A calendar of trading days. Also used for determining what cached dates we should expect to have cached. Defaults to the NYSE calendar. bm_symbol : str, optional Symbol for the benchmark index to load. Defaults to 'SPY', the ticker for the S&P 500, provided by IEX Trading. Returns ------- (benchmark_returns, treasury_curves) : (pd.Series, pd.DataFrame) Notes ----- Both return values are DatetimeIndexed with values dated to midnight in UTC of each stored date. The columns of `treasury_curves` are: '1month', '3month', '6month', '1year','2year','3year','5year','7year','10year','20year','30year' """ if trading_day is None: trading_day = get_calendar('XNYS').day if trading_days is None: trading_days = get_calendar('XNYS').all_sessions first_date = trading_days[0] now = pd.Timestamp.utcnow() # we will fill missing benchmark data through latest trading date last_date = trading_days[trading_days.get_loc(now, method='ffill')] br = ensure_benchmark_data( bm_symbol, first_date, last_date, now, # We need the trading_day to figure out the close prior to the first # date so that we can compute returns for the first date. trading_day, environ, ) tc = ensure_treasury_data( bm_symbol, first_date, last_date, now, environ, ) # combine dt indices and reindex using ffill then bfill all_dt = br.index.union(tc.index) br = br.reindex(all_dt, method='ffill').fillna(method='bfill') tc = tc.reindex(all_dt, method='ffill').fillna(method='bfill') benchmark_returns = br[br.index.slice_indexer(first_date, last_date)] treasury_curves = tc[tc.index.slice_indexer(first_date, last_date)] return benchmark_returns, treasury_curves
[ "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. now : pd.Timestamp The current time. This is used to prevent repeated attempts to re-download data that isn't available due to scheduling quirks or other failures. trading_day : pd.CustomBusinessDay A trading day delta. Used to find the day before first_date so we can get the close of the day prior to first_date. We attempt to download data unless we already have data stored at the data cache for `symbol` whose first entry is before or on `first_date` and whose last entry is on or after `last_date`. If we perform a download and the cache criteria are not satisfied, we wait at least one hour before attempting a redownload. This is determined by comparing the current time to the result of os.path.getmtime on the cache path.
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.Timestamp First required date for the cache. last_date : pd.Timestamp Last required date for the cache. now : pd.Timestamp The current time. This is used to prevent repeated attempts to re-download data that isn't available due to scheduling quirks or other failures. trading_day : pd.CustomBusinessDay A trading day delta. Used to find the day before first_date so we can get the close of the day prior to first_date. We attempt to download data unless we already have data stored at the data cache for `symbol` whose first entry is before or on `first_date` and whose last entry is on or after `last_date`. If we perform a download and the cache criteria are not satisfied, we wait at least one hour before attempting a redownload. This is determined by comparing the current time to the result of os.path.getmtime on the cache path. """ filename = get_benchmark_filename(symbol) data = _load_cached_data(filename, first_date, last_date, now, 'benchmark', environ) if data is not None: return data # If no cached data was found or it was missing any dates then download the # necessary data. logger.info( ('Downloading benchmark data for {symbol!r} ' 'from {first_date} to {last_date}'), symbol=symbol, first_date=first_date - trading_day, last_date=last_date ) try: data = get_benchmark_returns(symbol) data.to_csv(get_data_filepath(filename, environ)) except (OSError, IOError, HTTPError): logger.exception('Failed to cache the new benchmark returns') raise if not has_data_for_dates(data, first_date, last_date): logger.warn( ("Still don't have expected benchmark data for {symbol!r} " "from {first_date} to {last_date} after redownload!"), symbol=symbol, first_date=first_date - trading_day, last_date=last_date ) return data
def ensure_benchmark_data(symbol, first_date, last_date, now, trading_day, environ=None): """ Ensure we have benchmark data for `symbol` from `first_date` to `last_date` Parameters ---------- symbol : str The symbol for the benchmark to load. first_date : pd.Timestamp First required date for the cache. last_date : pd.Timestamp Last required date for the cache. now : pd.Timestamp The current time. This is used to prevent repeated attempts to re-download data that isn't available due to scheduling quirks or other failures. trading_day : pd.CustomBusinessDay A trading day delta. Used to find the day before first_date so we can get the close of the day prior to first_date. We attempt to download data unless we already have data stored at the data cache for `symbol` whose first entry is before or on `first_date` and whose last entry is on or after `last_date`. If we perform a download and the cache criteria are not satisfied, we wait at least one hour before attempting a redownload. This is determined by comparing the current time to the result of os.path.getmtime on the cache path. """ filename = get_benchmark_filename(symbol) data = _load_cached_data(filename, first_date, last_date, now, 'benchmark', environ) if data is not None: return data # If no cached data was found or it was missing any dates then download the # necessary data. logger.info( ('Downloading benchmark data for {symbol!r} ' 'from {first_date} to {last_date}'), symbol=symbol, first_date=first_date - trading_day, last_date=last_date ) try: data = get_benchmark_returns(symbol) data.to_csv(get_data_filepath(filename, environ)) except (OSError, IOError, HTTPError): logger.exception('Failed to cache the new benchmark returns') raise if not has_data_for_dates(data, first_date, last_date): logger.warn( ("Still don't have expected benchmark data for {symbol!r} " "from {first_date} to {last_date} after redownload!"), symbol=symbol, first_date=first_date - trading_day, last_date=last_date ) return data
[ "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 Last date required to be in the cache. now : pd.Timestamp The current time. This is used to prevent repeated attempts to re-download data that isn't available due to scheduling quirks or other failures. We attempt to download data unless we already have data stored in the cache for `module_name` whose first entry is before or on `first_date` and whose last entry is on or after `last_date`. If we perform a download and the cache criteria are not satisfied, we wait at least one hour before attempting a redownload. This is determined by comparing the current time to the result of os.path.getmtime on the cache path.
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.Timestamp First date required to be in the cache. last_date : pd.Timestamp Last date required to be in the cache. now : pd.Timestamp The current time. This is used to prevent repeated attempts to re-download data that isn't available due to scheduling quirks or other failures. We attempt to download data unless we already have data stored in the cache for `module_name` whose first entry is before or on `first_date` and whose last entry is on or after `last_date`. If we perform a download and the cache criteria are not satisfied, we wait at least one hour before attempting a redownload. This is determined by comparing the current time to the result of os.path.getmtime on the cache path. """ loader_module, filename, source = INDEX_MAPPING.get( symbol, INDEX_MAPPING['SPY'], ) first_date = max(first_date, loader_module.earliest_possible_date()) data = _load_cached_data(filename, first_date, last_date, now, 'treasury', environ) if data is not None: return data # If no cached data was found or it was missing any dates then download the # necessary data. logger.info( ('Downloading treasury data for {symbol!r} ' 'from {first_date} to {last_date}'), symbol=symbol, first_date=first_date, last_date=last_date ) try: data = loader_module.get_treasury_data(first_date, last_date) data.to_csv(get_data_filepath(filename, environ)) except (OSError, IOError, HTTPError): logger.exception('failed to cache treasury data') if not has_data_for_dates(data, first_date, last_date): logger.warn( ("Still don't have expected treasury data for {symbol!r} " "from {first_date} to {last_date} after redownload!"), symbol=symbol, first_date=first_date, last_date=last_date ) return data
def ensure_treasury_data(symbol, first_date, last_date, now, environ=None): """ Ensure we have treasury data from treasury module associated with `symbol`. Parameters ---------- symbol : str Benchmark symbol for which we're loading associated treasury curves. first_date : pd.Timestamp First date required to be in the cache. last_date : pd.Timestamp Last date required to be in the cache. now : pd.Timestamp The current time. This is used to prevent repeated attempts to re-download data that isn't available due to scheduling quirks or other failures. We attempt to download data unless we already have data stored in the cache for `module_name` whose first entry is before or on `first_date` and whose last entry is on or after `last_date`. If we perform a download and the cache criteria are not satisfied, we wait at least one hour before attempting a redownload. This is determined by comparing the current time to the result of os.path.getmtime on the cache path. """ loader_module, filename, source = INDEX_MAPPING.get( symbol, INDEX_MAPPING['SPY'], ) first_date = max(first_date, loader_module.earliest_possible_date()) data = _load_cached_data(filename, first_date, last_date, now, 'treasury', environ) if data is not None: return data # If no cached data was found or it was missing any dates then download the # necessary data. logger.info( ('Downloading treasury data for {symbol!r} ' 'from {first_date} to {last_date}'), symbol=symbol, first_date=first_date, last_date=last_date ) try: data = loader_module.get_treasury_data(first_date, last_date) data.to_csv(get_data_filepath(filename, environ)) except (OSError, IOError, HTTPError): logger.exception('failed to cache treasury data') if not has_data_for_dates(data, first_date, last_date): logger.warn( ("Still don't have expected treasury data for {symbol!r} " "from {first_date} to {last_date} after redownload!"), symbol=symbol, first_date=first_date, last_date=last_date ) return data
[ "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( "Can't mutate %s after construction." % type(self).__name__ ) # If we've seen this node already as a parent of the current traversal, # it means we have an unsatisifiable dependency. This should only be # possible if the term's inputs are mutated after construction. if term in parents: raise CyclicDependency(term) parents.add(term) self.graph.add_node(term) for dependency in term.dependencies: self._add_to_graph(dependency, parents) self.graph.add_edge(dependency, term) parents.remove(term)
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( "Can't mutate %s after construction." % type(self).__name__ ) # If we've seen this node already as a parent of the current traversal, # it means we have an unsatisifiable dependency. This should only be # possible if the term's inputs are mutated after construction. if term in parents: raise CyclicDependency(term) parents.add(term) self.graph.add_node(term) for dependency in term.dependencies: self._add_to_graph(dependency, parents) self.graph.add_edge(dependency, term) parents.remove(term)
[ "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 > 0}, ), ))
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 > 0}, ), ))
[ "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 reference to ensure that they're still in the graph at the end of execution.
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 equal to its outdegree, and output nodes get one extra reference to ensure that they're still in the graph at the end of execution. """ refcounts = self.graph.out_degree() for t in self.outputs.values(): refcounts[t] += 1 for t in initial_terms: self._decref_dependencies_recursive(t, refcounts, set()) return refcounts
def initial_refcounts(self, initial_terms): """ Calculate initial refcounts for execution of this graph. Parameters ---------- initial_terms : iterable[Term] An iterable of terms that were pre-computed before graph execution. Each node starts with a refcount equal to its outdegree, and output nodes get one extra reference to ensure that they're still in the graph at the end of execution. """ refcounts = self.graph.out_degree() for t in self.outputs.values(): refcounts[t] += 1 for t in initial_terms: self._decref_dependencies_recursive(t, refcounts, set()) return refcounts
[ "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` """ # Edges are tuple of (from, to). for parent, _ in self.graph.in_edges([term]): refcounts[parent] -= 1 # No one else depends on this term. Remove it from the # workspace to conserve memory. if refcounts[parent] == 0: garbage.add(parent) self._decref_dependencies_recursive(parent, refcounts, garbage)
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` """ # Edges are tuple of (from, to). for parent, _ in self.graph.in_edges([term]): refcounts[parent] -= 1 # No one else depends on this term. Remove it from the # workspace to conserve memory. if refcounts[parent] == 0: garbage.add(parent) self._decref_dependencies_recursive(parent, refcounts, garbage)
[ "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] Terms whose refcounts hit zero after decrefing.
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 refcounts. Return ------ garbage : set[Term] Terms whose refcounts hit zero after decrefing. """ garbage = set() # Edges are tuple of (from, to). for parent, _ in self.graph.in_edges([term]): refcounts[parent] -= 1 # No one else depends on this term. Remove it from the # workspace to conserve memory. if refcounts[parent] == 0: garbage.add(parent) return garbage
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 refcounts. Return ------ garbage : set[Term] Terms whose refcounts hit zero after decrefing. """ garbage = set() # Edges are tuple of (from, to). for parent, _ in self.graph.in_edges([term]): refcounts[parent] -= 1 # No one else depends on this term. Remove it from the # workspace to conserve memory. if refcounts[parent] == 0: garbage.add(parent) return garbage
[ "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 compute this value as follows:: offset(term, input) = (extra_rows_computed(input) - extra_rows_computed(term) - requested_extra_rows(term, input)) Examples -------- Case 1 ~~~~~~ Factor A needs 5 extra rows of USEquityPricing.close, and Factor B needs 3 extra rows of the same. Factor A also requires 5 extra rows of USEquityPricing.high, which no other Factor uses. We don't require any extra rows of Factor A or Factor B We load 5 extra rows of both `price` and `high` to ensure we can service Factor A, and the following offsets get computed:: offset[Factor A, USEquityPricing.close] == (5 - 0) - 5 == 0 offset[Factor A, USEquityPricing.high] == (5 - 0) - 5 == 0 offset[Factor B, USEquityPricing.close] == (5 - 0) - 3 == 2 offset[Factor B, USEquityPricing.high] raises KeyError. Case 2 ~~~~~~ Factor A needs 5 extra rows of USEquityPricing.close, and Factor B needs 3 extra rows of Factor A, and Factor B needs 2 extra rows of USEquityPricing.close. We load 8 extra rows of USEquityPricing.close (enough to load 5 extra rows of Factor A), and the following offsets get computed:: offset[Factor A, USEquityPricing.close] == (8 - 3) - 5 == 0 offset[Factor B, USEquityPricing.close] == (8 - 0) - 2 == 6 offset[Factor B, Factor A] == (3 - 0) - 3 == 0 Notes ----- `offset(term, input) >= 0` for all valid pairs, since `input` must be an input to `term` if the pair appears in the mapping. This value is useful because we load enough rows of each input to serve all possible dependencies. However, for any given dependency, we only want to compute using the actual number of required extra rows for that dependency. We can do so by truncating off the first `offset` rows of the loaded data for `input`. See Also -------- :meth:`zipline.pipeline.graph.ExecutionPlan.offset` :meth:`zipline.pipeline.engine.ExecutionPlan.mask_and_dates_for_term` :meth:`zipline.pipeline.engine.SimplePipelineEngine._inputs_for_term`
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 ``input`` before using it. We compute this value as follows:: offset(term, input) = (extra_rows_computed(input) - extra_rows_computed(term) - requested_extra_rows(term, input)) Examples -------- Case 1 ~~~~~~ Factor A needs 5 extra rows of USEquityPricing.close, and Factor B needs 3 extra rows of the same. Factor A also requires 5 extra rows of USEquityPricing.high, which no other Factor uses. We don't require any extra rows of Factor A or Factor B We load 5 extra rows of both `price` and `high` to ensure we can service Factor A, and the following offsets get computed:: offset[Factor A, USEquityPricing.close] == (5 - 0) - 5 == 0 offset[Factor A, USEquityPricing.high] == (5 - 0) - 5 == 0 offset[Factor B, USEquityPricing.close] == (5 - 0) - 3 == 2 offset[Factor B, USEquityPricing.high] raises KeyError. Case 2 ~~~~~~ Factor A needs 5 extra rows of USEquityPricing.close, and Factor B needs 3 extra rows of Factor A, and Factor B needs 2 extra rows of USEquityPricing.close. We load 8 extra rows of USEquityPricing.close (enough to load 5 extra rows of Factor A), and the following offsets get computed:: offset[Factor A, USEquityPricing.close] == (8 - 3) - 5 == 0 offset[Factor B, USEquityPricing.close] == (8 - 0) - 2 == 6 offset[Factor B, Factor A] == (3 - 0) - 3 == 0 Notes ----- `offset(term, input) >= 0` for all valid pairs, since `input` must be an input to `term` if the pair appears in the mapping. This value is useful because we load enough rows of each input to serve all possible dependencies. However, for any given dependency, we only want to compute using the actual number of required extra rows for that dependency. We can do so by truncating off the first `offset` rows of the loaded data for `input`. See Also -------- :meth:`zipline.pipeline.graph.ExecutionPlan.offset` :meth:`zipline.pipeline.engine.ExecutionPlan.mask_and_dates_for_term` :meth:`zipline.pipeline.engine.SimplePipelineEngine._inputs_for_term` """ extra = self.extra_rows out = {} for term in self.graph: for dep, requested_extra_rows in term.dependencies.items(): specialized_dep = maybe_specialize(dep, self.domain) # How much bigger is the result for dep compared to term? size_difference = extra[specialized_dep] - extra[term] # Subtract the portion of that difference that was required by # term's lookback window. offset = size_difference - requested_extra_rows out[term, specialized_dep] = offset return out
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 ``input`` before using it. We compute this value as follows:: offset(term, input) = (extra_rows_computed(input) - extra_rows_computed(term) - requested_extra_rows(term, input)) Examples -------- Case 1 ~~~~~~ Factor A needs 5 extra rows of USEquityPricing.close, and Factor B needs 3 extra rows of the same. Factor A also requires 5 extra rows of USEquityPricing.high, which no other Factor uses. We don't require any extra rows of Factor A or Factor B We load 5 extra rows of both `price` and `high` to ensure we can service Factor A, and the following offsets get computed:: offset[Factor A, USEquityPricing.close] == (5 - 0) - 5 == 0 offset[Factor A, USEquityPricing.high] == (5 - 0) - 5 == 0 offset[Factor B, USEquityPricing.close] == (5 - 0) - 3 == 2 offset[Factor B, USEquityPricing.high] raises KeyError. Case 2 ~~~~~~ Factor A needs 5 extra rows of USEquityPricing.close, and Factor B needs 3 extra rows of Factor A, and Factor B needs 2 extra rows of USEquityPricing.close. We load 8 extra rows of USEquityPricing.close (enough to load 5 extra rows of Factor A), and the following offsets get computed:: offset[Factor A, USEquityPricing.close] == (8 - 3) - 5 == 0 offset[Factor B, USEquityPricing.close] == (8 - 0) - 2 == 6 offset[Factor B, Factor A] == (3 - 0) - 3 == 0 Notes ----- `offset(term, input) >= 0` for all valid pairs, since `input` must be an input to `term` if the pair appears in the mapping. This value is useful because we load enough rows of each input to serve all possible dependencies. However, for any given dependency, we only want to compute using the actual number of required extra rows for that dependency. We can do so by truncating off the first `offset` rows of the loaded data for `input`. See Also -------- :meth:`zipline.pipeline.graph.ExecutionPlan.offset` :meth:`zipline.pipeline.engine.ExecutionPlan.mask_and_dates_for_term` :meth:`zipline.pipeline.engine.SimplePipelineEngine._inputs_for_term` """ extra = self.extra_rows out = {} for term in self.graph: for dep, requested_extra_rows in term.dependencies.items(): specialized_dep = maybe_specialize(dep, self.domain) # How much bigger is the result for dep compared to term? size_difference = extra[specialized_dep] - extra[term] # Subtract the portion of that difference that was required by # term's lookback window. offset = size_difference - requested_extra_rows out[term, specialized_dep] = offset return out
[ "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 inputs we need to load, and which is determined entirely by `Term` itself. Examples -------- Our graph contains the following terms: A = SimpleMovingAverage([USEquityPricing.high], window_length=5) B = SimpleMovingAverage([USEquityPricing.high], window_length=10) C = SimpleMovingAverage([USEquityPricing.low], window_length=8) To compute N rows of A, we need N + 4 extra rows of `high`. To compute N rows of B, we need N + 9 extra rows of `high`. To compute N rows of C, we need N + 7 extra rows of `low`. We store the following extra_row requirements: self.extra_rows[high] = 9 # Ensures that we can service B. self.extra_rows[low] = 7 See Also -------- :meth:`zipline.pipeline.graph.ExecutionPlan.offset` :meth:`zipline.pipeline.term.Term.dependencies`
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 how many additional rows of `term`'s inputs we need to load, and which is determined entirely by `Term` itself. Examples -------- Our graph contains the following terms: A = SimpleMovingAverage([USEquityPricing.high], window_length=5) B = SimpleMovingAverage([USEquityPricing.high], window_length=10) C = SimpleMovingAverage([USEquityPricing.low], window_length=8) To compute N rows of A, we need N + 4 extra rows of `high`. To compute N rows of B, we need N + 9 extra rows of `high`. To compute N rows of C, we need N + 7 extra rows of `low`. We store the following extra_row requirements: self.extra_rows[high] = 9 # Ensures that we can service B. self.extra_rows[low] = 7 See Also -------- :meth:`zipline.pipeline.graph.ExecutionPlan.offset` :meth:`zipline.pipeline.term.Term.dependencies` """ return { term: attrs['extra_rows'] for term, attrs in iteritems(self.graph.node) }
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 how many additional rows of `term`'s inputs we need to load, and which is determined entirely by `Term` itself. Examples -------- Our graph contains the following terms: A = SimpleMovingAverage([USEquityPricing.high], window_length=5) B = SimpleMovingAverage([USEquityPricing.high], window_length=10) C = SimpleMovingAverage([USEquityPricing.low], window_length=8) To compute N rows of A, we need N + 4 extra rows of `high`. To compute N rows of B, we need N + 9 extra rows of `high`. To compute N rows of C, we need N + 7 extra rows of `low`. We store the following extra_row requirements: self.extra_rows[high] = 9 # Ensures that we can service B. self.extra_rows[low] = 7 See Also -------- :meth:`zipline.pipeline.graph.ExecutionPlan.offset` :meth:`zipline.pipeline.term.Term.dependencies` """ return { term: attrs['extra_rows'] for term, attrs in iteritems(self.graph.node) }
[ "A", "dict", "mapping", "term", "-", ">", "#", "of", "extra", "rows", "to", "load", "/", "compute", "of", "term", "." ]
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 been computed for each term. all_dates : pd.DatetimeIndex All of the dates that are being computed for in the pipeline. Returns ------- mask : np.ndarray The correct mask for this term. dates : np.ndarray The slice of dates for this term.
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 : 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 been computed for each term. all_dates : pd.DatetimeIndex All of the dates that are being computed for in the pipeline. Returns ------- mask : np.ndarray The correct mask for this term. dates : np.ndarray The slice of dates for this term. """ mask = term.mask mask_offset = self.extra_rows[mask] - self.extra_rows[term] # This offset is computed against root_mask_term because that is what # determines the shape of the top-level dates array. dates_offset = ( self.extra_rows[root_mask_term] - self.extra_rows[term] ) return workspace[mask][mask_offset:], all_dates[dates_offset:]
def mask_and_dates_for_term(self, term, root_mask_term, workspace, all_dates): """ 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 been computed for each term. all_dates : pd.DatetimeIndex All of the dates that are being computed for in the pipeline. Returns ------- mask : np.ndarray The correct mask for this term. dates : np.ndarray The slice of dates for this term. """ mask = term.mask mask_offset = self.extra_rows[mask] - self.extra_rows[term] # This offset is computed against root_mask_term because that is what # determines the shape of the top-level dates array. dates_offset = ( self.extra_rows[root_mask_term] - self.extra_rows[term] ) return workspace[mask][mask_offset:], all_dates[dates_offset:]
[ "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_bounds` is falsey. """ real_path = join(dirname(abspath(__file__)), path) with open(real_path) as f: reqs = _filter_requirements(f.readlines(), filter_names=filter_names, filter_sys_version=not conda_format) if not strict_bounds: reqs = map(_with_bounds, reqs) if conda_format: reqs = map(_conda_format, reqs) return list(reqs)
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_bounds` is falsey. """ real_path = join(dirname(abspath(__file__)), path) with open(real_path) as f: reqs = _filter_requirements(f.readlines(), filter_names=filter_names, filter_sys_version=not conda_format) if not strict_bounds: reqs = map(_with_bounds, reqs) if conda_format: reqs = map(_conda_format, reqs) return list(reqs)
[ "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('Cannot pass kwargs and an offset') elif isinstance(offset, datetime.timedelta): return _td_check(offset) else: raise TypeError("Must pass 'hours' and/or 'minutes' as keywords")
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('Cannot pass kwargs and an offset') elif isinstance(offset, datetime.timedelta): return _td_check(offset) else: raise TypeError("Must pass 'hours' and/or 'minutes' as keywords")
[ "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 a date') else: return date
def _build_date(date, kwargs): """ Builds the date argument for event rules. """ if date is None: if not kwargs: raise ValueError('Must pass a date or kwargs') else: return datetime.date(**kwargs) elif kwargs: raise ValueError('Cannot pass kwargs and a date') else: return date
[ "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('Must pass a time or kwargs') else: return datetime.time(**kwargs)
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('Must pass a time or kwargs') else: return datetime.time(**kwargs)
[ "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( "{f} expected an int for argument {name!r}, but got float {arg}." " Coercing to int.".format( f=funcname, name=argname, arg=arg, ), ) return arg_as_int raise TypeError(arg)
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( "{f} expected an int for argument {name!r}, but got float {arg}." " Coercing to int.".format( f=funcname, name=argname, arg=arg, ), ) return arg_as_int raise TypeError(arg)
[ "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 & NotHalfDay() opd = OncePerDay(rule=inner_rule) # This is where a scheduled function's rule is associated with a calendar. opd.cal = cal return opd
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 & NotHalfDay() opd = OncePerDay(rule=inner_rule) # This is where a scheduled function's rule is associated with a calendar. opd.cal = cal return opd
[ "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 with the execution times # used by the simulation clock. This ensures that scheduled functions # trigger at the correct times. self._period_start = self.cal.execution_time_from_open(period_start) self._period_close = self.cal.execution_time_from_close(period_close) self._period_end = self._period_start + self.offset - self._one_minute
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 with the execution times # used by the simulation clock. This ensures that scheduled functions # trigger at the correct times. self._period_start = self.cal.execution_time_from_open(period_start) self._period_close = self.cal.execution_time_from_close(period_close) self._period_end = self._period_start + self.offset - self._one_minute
[ "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 used by the # simulation clock. This ensures that scheduled functions trigger at # the correct times. self._period_end = self.cal.execution_time_from_close(period_end) self._period_start = self._period_end - self.offset self._period_close = self._period_end
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 used by the # simulation clock. This ensures that scheduled functions trigger at # the correct times. self._period_end = self.cal.execution_time_from_close(period_end) self._period_start = self._period_end - self.offset self._period_close = self._period_end
[ "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 the columns to check. Returns ------- truncated : pd.DataFrame ``df`` with values that do not fit into a uint32 zeroed out.
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 the bounds of a uint32. *columns : iterable[str] The names of the columns to check. Returns ------- truncated : pd.DataFrame ``df`` with values that do not fit into a uint32 zeroed out. """ columns = list((column,) + columns) mask = df[columns] > UINT32_MAX if invalid_data_behavior != 'ignore': mask |= df[columns].isnull() else: # we are not going to generate a warning or error for this so just use # nan_to_num df[columns] = np.nan_to_num(df[columns]) mv = mask.values if mv.any(): if invalid_data_behavior == 'raise': raise ValueError( '%d values out of bounds for uint32: %r' % ( mv.sum(), df[mask.any(axis=1)], ), ) if invalid_data_behavior == 'warn': warnings.warn( 'Ignoring %d values because they are out of bounds for' ' uint32: %r' % ( mv.sum(), df[mask.any(axis=1)], ), stacklevel=3, # one extra frame for `expect_element` ) df[mask] = 0 return df
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 the bounds of a uint32. *columns : iterable[str] The names of the columns to check. Returns ------- truncated : pd.DataFrame ``df`` with values that do not fit into a uint32 zeroed out. """ columns = list((column,) + columns) mask = df[columns] > UINT32_MAX if invalid_data_behavior != 'ignore': mask |= df[columns].isnull() else: # we are not going to generate a warning or error for this so just use # nan_to_num df[columns] = np.nan_to_num(df[columns]) mv = mask.values if mv.any(): if invalid_data_behavior == 'raise': raise ValueError( '%d values out of bounds for uint32: %r' % ( mv.sum(), df[mask.any(axis=1)], ), ) if invalid_data_behavior == 'warn': warnings.warn( 'Ignoring %d values because they are out of bounds for' ' uint32: %r' % ( mv.sum(), df[mask.any(axis=1)], ), stacklevel=3, # one extra frame for `expect_element` ) df[mask] = 0 return df
[ "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 provided we will check ``data`` against the assets and provide better progress information. show_progress : bool, optional Whether or not to show a progress bar while writing. invalid_data_behavior : {'warn', 'raise', 'ignore'}, optional What to do when data is encountered that is outside the range of a uint32. Returns ------- table : bcolz.ctable The newly-written table.
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 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 provided we will check ``data`` against the assets and provide better progress information. show_progress : bool, optional Whether or not to show a progress bar while writing. invalid_data_behavior : {'warn', 'raise', 'ignore'}, optional What to do when data is encountered that is outside the range of a uint32. Returns ------- table : bcolz.ctable The newly-written table. """ ctx = maybe_show_progress( ( (sid, self.to_ctable(df, invalid_data_behavior)) for sid, df in data ), show_progress=show_progress, item_show_func=self.progress_bar_item_show_func, label=self.progress_bar_message, length=len(assets) if assets is not None else None, ) with ctx as it: return self._write_internal(it, assets)
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 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 provided we will check ``data`` against the assets and provide better progress information. show_progress : bool, optional Whether or not to show a progress bar while writing. invalid_data_behavior : {'warn', 'raise', 'ignore'}, optional What to do when data is encountered that is outside the range of a uint32. Returns ------- table : bcolz.ctable The newly-written table. """ ctx = maybe_show_progress( ( (sid, self.to_ctable(df, invalid_data_behavior)) for sid, df in data ), show_progress=show_progress, item_show_func=self.progress_bar_item_show_func, label=self.progress_bar_message, length=len(assets) if assets is not None else None, ) with ctx as it: return self._write_internal(it, assets)
[ "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. invalid_data_behavior : {'warn', 'raise', 'ignore'} What to do when data is encountered that is outside the range of a uint32.
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 with the CSV data for that asset show_progress : bool Whether or not to show a progress bar while writing. invalid_data_behavior : {'warn', 'raise', 'ignore'} What to do when data is encountered that is outside the range of a uint32. """ read = partial( read_csv, parse_dates=['day'], index_col='day', dtype=self._csv_dtypes, ) return self.write( ((asset, read(path)) for asset, path in iteritems(asset_map)), assets=viewkeys(asset_map), show_progress=show_progress, invalid_data_behavior=invalid_data_behavior, )
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 with the CSV data for that asset show_progress : bool Whether or not to show a progress bar while writing. invalid_data_behavior : {'warn', 'raise', 'ignore'} What to do when data is encountered that is outside the range of a uint32. """ read = partial( read_csv, parse_dates=['day'], index_col='day', dtype=self._csv_dtypes, ) return self.write( ((asset, read(path)) for asset, path in iteritems(asset_map)), assets=viewkeys(asset_map), show_progress=show_progress, invalid_data_behavior=invalid_data_behavior, )
[ "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 -> output carray. columns = { k: carray(array([], dtype=uint32_dtype)) for k in US_EQUITY_PRICING_BCOLZ_COLUMNS } earliest_date = None sessions = self._calendar.sessions_in_range( self._start_session, self._end_session ) if assets is not None: @apply def iterator(iterator=iterator, assets=set(assets)): for asset_id, table in iterator: if asset_id not in assets: raise ValueError('unknown asset id %r' % asset_id) yield asset_id, table for asset_id, table in iterator: nrows = len(table) for column_name in columns: if column_name == 'id': # We know what the content of this column is, so don't # bother reading it. columns['id'].append( full((nrows,), asset_id, dtype='uint32'), ) continue columns[column_name].append(table[column_name]) if earliest_date is None: earliest_date = table["day"][0] else: earliest_date = min(earliest_date, table["day"][0]) # Bcolz doesn't support ints as keys in `attrs`, so convert # assets to strings for use as attr keys. asset_key = str(asset_id) # Calculate the index into the array of the first and last row # for this asset. This allows us to efficiently load single # assets when querying the data back out of the table. first_row[asset_key] = total_rows last_row[asset_key] = total_rows + nrows - 1 total_rows += nrows table_day_to_session = compose( self._calendar.minute_to_session_label, partial(Timestamp, unit='s', tz='UTC'), ) asset_first_day = table_day_to_session(table['day'][0]) asset_last_day = table_day_to_session(table['day'][-1]) asset_sessions = sessions[ sessions.slice_indexer(asset_first_day, asset_last_day) ] assert len(table) == len(asset_sessions), ( 'Got {} rows for daily bars table with first day={}, last ' 'day={}, expected {} rows.\n' 'Missing sessions: {}\n' 'Extra sessions: {}'.format( len(table), asset_first_day.date(), asset_last_day.date(), len(asset_sessions), asset_sessions.difference( to_datetime( np.array(table['day']), unit='s', utc=True, ) ).tolist(), to_datetime( np.array(table['day']), unit='s', utc=True, ).difference(asset_sessions).tolist(), ) ) # Calculate the number of trading days between the first date # in the stored data and the first date of **this** asset. This # offset used for output alignment by the reader. calendar_offset[asset_key] = sessions.get_loc(asset_first_day) # This writes the table to disk. full_table = ctable( columns=[ columns[colname] for colname in US_EQUITY_PRICING_BCOLZ_COLUMNS ], names=US_EQUITY_PRICING_BCOLZ_COLUMNS, rootdir=self._filename, mode='w', ) full_table.attrs['first_trading_day'] = ( earliest_date if earliest_date is not None else iNaT ) full_table.attrs['first_row'] = first_row full_table.attrs['last_row'] = last_row full_table.attrs['calendar_offset'] = calendar_offset full_table.attrs['calendar_name'] = self._calendar.name full_table.attrs['start_session_ns'] = self._start_session.value full_table.attrs['end_session_ns'] = self._end_session.value full_table.flush() return full_table
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 -> output carray. columns = { k: carray(array([], dtype=uint32_dtype)) for k in US_EQUITY_PRICING_BCOLZ_COLUMNS } earliest_date = None sessions = self._calendar.sessions_in_range( self._start_session, self._end_session ) if assets is not None: @apply def iterator(iterator=iterator, assets=set(assets)): for asset_id, table in iterator: if asset_id not in assets: raise ValueError('unknown asset id %r' % asset_id) yield asset_id, table for asset_id, table in iterator: nrows = len(table) for column_name in columns: if column_name == 'id': # We know what the content of this column is, so don't # bother reading it. columns['id'].append( full((nrows,), asset_id, dtype='uint32'), ) continue columns[column_name].append(table[column_name]) if earliest_date is None: earliest_date = table["day"][0] else: earliest_date = min(earliest_date, table["day"][0]) # Bcolz doesn't support ints as keys in `attrs`, so convert # assets to strings for use as attr keys. asset_key = str(asset_id) # Calculate the index into the array of the first and last row # for this asset. This allows us to efficiently load single # assets when querying the data back out of the table. first_row[asset_key] = total_rows last_row[asset_key] = total_rows + nrows - 1 total_rows += nrows table_day_to_session = compose( self._calendar.minute_to_session_label, partial(Timestamp, unit='s', tz='UTC'), ) asset_first_day = table_day_to_session(table['day'][0]) asset_last_day = table_day_to_session(table['day'][-1]) asset_sessions = sessions[ sessions.slice_indexer(asset_first_day, asset_last_day) ] assert len(table) == len(asset_sessions), ( 'Got {} rows for daily bars table with first day={}, last ' 'day={}, expected {} rows.\n' 'Missing sessions: {}\n' 'Extra sessions: {}'.format( len(table), asset_first_day.date(), asset_last_day.date(), len(asset_sessions), asset_sessions.difference( to_datetime( np.array(table['day']), unit='s', utc=True, ) ).tolist(), to_datetime( np.array(table['day']), unit='s', utc=True, ).difference(asset_sessions).tolist(), ) ) # Calculate the number of trading days between the first date # in the stored data and the first date of **this** asset. This # offset used for output alignment by the reader. calendar_offset[asset_key] = sessions.get_loc(asset_first_day) # This writes the table to disk. full_table = ctable( columns=[ columns[colname] for colname in US_EQUITY_PRICING_BCOLZ_COLUMNS ], names=US_EQUITY_PRICING_BCOLZ_COLUMNS, rootdir=self._filename, mode='w', ) full_table.attrs['first_trading_day'] = ( earliest_date if earliest_date is not None else iNaT ) full_table.attrs['first_row'] = first_row full_table.attrs['last_row'] = last_row full_table.attrs['calendar_offset'] = calendar_offset full_table.attrs['calendar_name'] = self._calendar.name full_table.attrs['start_session_ns'] = self._start_session.value full_table.attrs['end_session_ns'] = self._end_session.value full_table.flush() return full_table
[ "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. assets : pandas.Int64Index Assets for which we want to compute row indices Returns ------- A 3-tuple of (first_rows, last_rows, offsets): first_rows : np.array[intp] Array with length == len(assets) containing the index of the first row to load for each asset in `assets`. last_rows : np.array[intp] Array with length == len(assets) containing the index of the last row to load for each asset in `assets`. offset : np.array[intp] Array with length == (len(asset) containing the index in a buffer of length `dates` corresponding to the first row of each asset. The value of offset[i] will be 0 if asset[i] existed at the start of a query. Otherwise, offset[i] will be equal to the number of entries in `dates` for which the asset did not yet exist.
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_idx : int Index of last date for which we want data. assets : pandas.Int64Index Assets for which we want to compute row indices Returns ------- A 3-tuple of (first_rows, last_rows, offsets): first_rows : np.array[intp] Array with length == len(assets) containing the index of the first row to load for each asset in `assets`. last_rows : np.array[intp] Array with length == len(assets) containing the index of the last row to load for each asset in `assets`. offset : np.array[intp] Array with length == (len(asset) containing the index in a buffer of length `dates` corresponding to the first row of each asset. The value of offset[i] will be 0 if asset[i] existed at the start of a query. Otherwise, offset[i] will be equal to the number of entries in `dates` for which the asset did not yet exist. """ # The core implementation of the logic here is implemented in Cython # for efficiency. return _compute_row_slices( self._first_rows, self._last_rows, self._calendar_offsets, start_idx, end_idx, assets, )
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_idx : int Index of last date for which we want data. assets : pandas.Int64Index Assets for which we want to compute row indices Returns ------- A 3-tuple of (first_rows, last_rows, offsets): first_rows : np.array[intp] Array with length == len(assets) containing the index of the first row to load for each asset in `assets`. last_rows : np.array[intp] Array with length == len(assets) containing the index of the last row to load for each asset in `assets`. offset : np.array[intp] Array with length == (len(asset) containing the index in a buffer of length `dates` corresponding to the first row of each asset. The value of offset[i] will be 0 if asset[i] existed at the start of a query. Otherwise, offset[i] will be equal to the number of entries in `dates` for which the asset did not yet exist. """ # The core implementation of the logic here is implemented in Cython # for efficiency. return _compute_row_slices( self._first_rows, self._last_rows, self._calendar_offsets, 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", "." ]
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 in the daily_bar_table with the given colname.
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 (uint32) Full read array of the carray in the daily_bar_table with the given colname. """ try: col = self._spot_cols[colname] except KeyError: col = self._spot_cols[colname] = self._table[colname] return col
def _spot_col(self, colname): """ Get the colname from daily_bar_table and read all of it into memory, caching the result. Parameters ---------- colname : string A name of a OHLCV carray in the daily_bar_table Returns ------- array (uint32) Full read array of the carray in the daily_bar_table with the given colname. """ try: col = self._spot_cols[colname] except KeyError: col = self._spot_cols[colname] = self._table[colname] return col
[ "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 exception if the given day and sid is before or after the date range of the equity.
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 given sid and day. Raises a NoDataOnDate exception if the given day and sid is before or after the date range of the equity. """ try: day_loc = self.sessions.get_loc(day) except Exception: raise NoDataOnDate("day={0} is outside of calendar={1}".format( day, self.sessions)) offset = day_loc - self._calendar_offsets[sid] if offset < 0: raise NoDataBeforeDate( "No data on or before day={0} for sid={1}".format( day, sid)) ix = self._first_rows[sid] + offset if ix > self._last_rows[sid]: raise NoDataAfterDate( "No data on or after day={0} for sid={1}".format( day, sid)) return ix
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 given sid and day. Raises a NoDataOnDate exception if the given day and sid is before or after the date range of the equity. """ try: day_loc = self.sessions.get_loc(day) except Exception: raise NoDataOnDate("day={0} is outside of calendar={1}".format( day, self.sessions)) offset = day_loc - self._calendar_offsets[sid] if offset < 0: raise NoDataBeforeDate( "No data on or before day={0} for sid={1}".format( day, sid)) ix = self._first_rows[sid] + offset if ix > self._last_rows[sid]: raise NoDataAfterDate( "No data on or after day={0} for sid={1}".format( day, sid)) return ix
[ "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 ------- float The spot price for colname of the given sid on the given day. Raises a NoDataOnDate exception if the given day and sid is before or after the date range of the equity. Returns -1 if the day is within the date range, but the price is 0.
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', 'volume') Returns ------- float The spot price for colname of the given sid on the given day. Raises a NoDataOnDate exception if the given day and sid is before or after the date range of the equity. Returns -1 if the day is within the date range, but the price is 0. """ ix = self.sid_day_index(sid, dt) price = self._spot_col(field)[ix] if field != 'volume': if price == 0: return nan else: return price * 0.001 else: return price
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', 'volume') Returns ------- float The spot price for colname of the given sid on the given day. Raises a NoDataOnDate exception if the given day and sid is before or after the date range of the equity. Returns -1 if the day is within the date range, but the price is 0. """ ix = self.sid_day_index(sid, dt) price = self._spot_col(field)[ix] if field != 'volume': if price == 0: return nan else: return price * 0.001 else: return price
[ "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.asset_finder, self.default_pipeline_domain(self.trading_calendar), ) else: self.engine = ExplodingPipelineEngine()
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.asset_finder, self.default_pipeline_domain(self.trading_calendar), ) else: self.engine = ExplodingPipelineEngine()
[ "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 if self.sim_params.data_frequency == 'minute': market_opens = trading_o_and_c['market_open'] minutely_emission = self.sim_params.emission_rate == "minute" # The calendar's execution times are the minutes over which we # actually want to run the clock. Typically the execution times # simply adhere to the market open and close times. In the case of # the futures calendar, for example, we only want to simulate over # a subset of the full 24 hour calendar, so the execution times # dictate a market open time of 6:31am US/Eastern and a close of # 5:00pm US/Eastern. execution_opens = \ self.trading_calendar.execution_time_from_open(market_opens) execution_closes = \ self.trading_calendar.execution_time_from_close(market_closes) else: # in daily mode, we want to have one bar per session, timestamped # as the last minute of the session. execution_closes = \ self.trading_calendar.execution_time_from_close(market_closes) execution_opens = execution_closes # FIXME generalize these values before_trading_start_minutes = days_at_time( self.sim_params.sessions, time(8, 45), "US/Eastern" ) return MinuteSimulationClock( self.sim_params.sessions, execution_opens, execution_closes, before_trading_start_minutes, minute_emission=minutely_emission, )
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 self.sim_params.data_frequency == 'minute': market_opens = trading_o_and_c['market_open'] minutely_emission = self.sim_params.emission_rate == "minute" # The calendar's execution times are the minutes over which we # actually want to run the clock. Typically the execution times # simply adhere to the market open and close times. In the case of # the futures calendar, for example, we only want to simulate over # a subset of the full 24 hour calendar, so the execution times # dictate a market open time of 6:31am US/Eastern and a close of # 5:00pm US/Eastern. execution_opens = \ self.trading_calendar.execution_time_from_open(market_opens) execution_closes = \ self.trading_calendar.execution_time_from_close(market_closes) else: # in daily mode, we want to have one bar per session, timestamped # as the last minute of the session. execution_closes = \ self.trading_calendar.execution_time_from_close(market_closes) execution_opens = execution_closes # FIXME generalize these values before_trading_start_minutes = days_at_time( self.sim_params.sessions, time(8, 45), "US/Eastern" ) return MinuteSimulationClock( self.sim_params.sessions, execution_opens, execution_closes, before_trading_start_minutes, minute_emission=minutely_emission, )
[ "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_portal = data_portal self.asset_finder = data_portal.asset_finder elif self.data_portal is None: raise RuntimeError( "No data portal in TradingAlgorithm.run().\n" "Either pass a DataPortal to TradingAlgorithm() or to run()." ) else: assert self.asset_finder is not None, \ "Have data portal without asset_finder." # Create zipline and loop through simulated_trading. # Each iteration returns a perf dictionary try: perfs = [] for perf in self.get_generator(): perfs.append(perf) # convert perf dict to pandas dataframe daily_stats = self._create_daily_stats(perfs) self.analyze(daily_stats) finally: self.data_portal = None self.metrics_tracker = None return daily_stats
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_portal = data_portal self.asset_finder = data_portal.asset_finder elif self.data_portal is None: raise RuntimeError( "No data portal in TradingAlgorithm.run().\n" "Either pass a DataPortal to TradingAlgorithm() or to run()." ) else: assert self.asset_finder is not None, \ "Have data portal without asset_finder." # Create zipline and loop through simulated_trading. # Each iteration returns a perf dictionary try: perfs = [] for perf in self.get_generator(): perfs.append(perf) # convert perf dict to pandas dataframe daily_stats = self._create_daily_stats(perfs) self.analyze(daily_stats) finally: self.data_portal = None self.metrics_tracker = None return daily_stats
[ "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 specified, will be removed from the portfolio_value of the cumulative performance when calculating deltas from target capital changes.
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 target value, the change will be computed on the portfolio value according to prices at the given dt `portfolio_value_adjustment`, if specified, will be removed from the portfolio_value of the cumulative performance when calculating deltas from target capital changes. """ try: capital_change = self.capital_changes[dt] except KeyError: return self._sync_last_sale_prices() if capital_change['type'] == 'target': target = capital_change['value'] capital_change_amount = ( target - ( self.portfolio.portfolio_value - portfolio_value_adjustment ) ) log.info('Processing capital change to target %s at %s. Capital ' 'change delta is %s' % (target, dt, capital_change_amount)) elif capital_change['type'] == 'delta': target = None capital_change_amount = capital_change['value'] log.info('Processing capital change of delta %s at %s' % (capital_change_amount, dt)) else: log.error("Capital change %s does not indicate a valid type " "('target' or 'delta')" % capital_change) return self.capital_change_deltas.update({dt: capital_change_amount}) self.metrics_tracker.capital_change(capital_change_amount) yield { 'capital_change': {'date': dt, 'type': 'cash', 'target': target, 'delta': capital_change_amount} }
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 target value, the change will be computed on the portfolio value according to prices at the given dt `portfolio_value_adjustment`, if specified, will be removed from the portfolio_value of the cumulative performance when calculating deltas from target capital changes. """ try: capital_change = self.capital_changes[dt] except KeyError: return self._sync_last_sale_prices() if capital_change['type'] == 'target': target = capital_change['value'] capital_change_amount = ( target - ( self.portfolio.portfolio_value - portfolio_value_adjustment ) ) log.info('Processing capital change to target %s at %s. Capital ' 'change delta is %s' % (target, dt, capital_change_amount)) elif capital_change['type'] == 'delta': target = None capital_change_amount = capital_change['value'] log.info('Processing capital change of delta %s at %s' % (capital_change_amount, dt)) else: log.error("Capital change %s does not indicate a valid type " "('target' or 'delta')" % capital_change) return self.capital_change_deltas.update({dt: capital_change_amount}) self.metrics_tracker.capital_change(capital_change_amount) yield { 'capital_change': {'date': dt, 'type': 'cash', 'target': target, 'delta': capital_change_amount} }
[ "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 from the simulation parameters. This will normally be ``'backtest'`` but some systems may use this distinguish live trading from backtesting. data_frequency : {'daily', 'minute'} data_frequency tells the algorithm if it is running with daily data or minute data. start : datetime The start date for the simulation. end : datetime The end date for the simulation. capital_base : float The starting capital for the simulation. platform : str The platform that the code is running on. By default this will be the string 'zipline'. This can allow algorithms to know if they are running on the Quantopian platform instead. * : dict[str -> any] Returns all of the fields in a dictionary. Returns ------- val : any The value for the field queried. See above for more information. Raises ------ ValueError Raised when ``field`` is not a valid option.
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 meanings: arena : str The arena from the simulation parameters. This will normally be ``'backtest'`` but some systems may use this distinguish live trading from backtesting. data_frequency : {'daily', 'minute'} data_frequency tells the algorithm if it is running with daily data or minute data. start : datetime The start date for the simulation. end : datetime The end date for the simulation. capital_base : float The starting capital for the simulation. platform : str The platform that the code is running on. By default this will be the string 'zipline'. This can allow algorithms to know if they are running on the Quantopian platform instead. * : dict[str -> any] Returns all of the fields in a dictionary. Returns ------- val : any The value for the field queried. See above for more information. Raises ------ ValueError Raised when ``field`` is not a valid option. """ env = { 'arena': self.sim_params.arena, 'data_frequency': self.sim_params.data_frequency, 'start': self.sim_params.first_open, 'end': self.sim_params.last_close, 'capital_base': self.sim_params.capital_base, 'platform': self._platform } if field == '*': return env else: try: return env[field] except KeyError: raise ValueError( '%r is not a valid field for get_environment' % field, )
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 meanings: arena : str The arena from the simulation parameters. This will normally be ``'backtest'`` but some systems may use this distinguish live trading from backtesting. data_frequency : {'daily', 'minute'} data_frequency tells the algorithm if it is running with daily data or minute data. start : datetime The start date for the simulation. end : datetime The end date for the simulation. capital_base : float The starting capital for the simulation. platform : str The platform that the code is running on. By default this will be the string 'zipline'. This can allow algorithms to know if they are running on the Quantopian platform instead. * : dict[str -> any] Returns all of the fields in a dictionary. Returns ------- val : any The value for the field queried. See above for more information. Raises ------ ValueError Raised when ``field`` is not a valid option. """ env = { 'arena': self.sim_params.arena, 'data_frequency': self.sim_params.data_frequency, 'start': self.sim_params.first_open, 'end': self.sim_params.last_close, 'capital_base': self.sim_params.capital_base, 'platform': self._platform } if field == '*': return env else: try: return env[field] except KeyError: raise ValueError( '%r is not a valid field for get_environment' % field, )
[ "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 preprocessing the raw data returned from fetch_csv before dates are paresed or symbols are mapped. post_func : callable[pd.DataFrame -> pd.DataFrame], optional A callback to allow postprocessing of the data after dates and symbols have been mapped. date_column : str, optional The name of the column in the preprocessed dataframe containing datetime information to map the data. date_format : str, optional The format of the dates in the ``date_column``. If not provided ``fetch_csv`` will attempt to infer the format. For information about the format of this string, see :func:`pandas.read_csv`. timezone : tzinfo or str, optional The timezone for the datetime in the ``date_column``. symbol : str, optional If the data is about a new asset or index then this string will be the name used to identify the values in ``data``. For example, one may use ``fetch_csv`` to load data for VIX, then this field could be the string ``'VIX'``. mask : bool, optional Drop any rows which cannot be symbol mapped. symbol_column : str If the data is attaching some new attribute to each asset then this argument is the name of the column in the preprocessed dataframe containing the symbols. This will be used along with the date information to map the sids in the asset finder. country_code : str, optional Country code to use to disambiguate symbol lookups. **kwargs Forwarded to :func:`pandas.read_csv`. Returns ------- csv_data_source : zipline.sources.requests_csv.PandasRequestsCSV A requests source that will pull data from the url specified.
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=None, special_params_checker=None, country_code=None, **kwargs): """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 preprocessing the raw data returned from fetch_csv before dates are paresed or symbols are mapped. post_func : callable[pd.DataFrame -> pd.DataFrame], optional A callback to allow postprocessing of the data after dates and symbols have been mapped. date_column : str, optional The name of the column in the preprocessed dataframe containing datetime information to map the data. date_format : str, optional The format of the dates in the ``date_column``. If not provided ``fetch_csv`` will attempt to infer the format. For information about the format of this string, see :func:`pandas.read_csv`. timezone : tzinfo or str, optional The timezone for the datetime in the ``date_column``. symbol : str, optional If the data is about a new asset or index then this string will be the name used to identify the values in ``data``. For example, one may use ``fetch_csv`` to load data for VIX, then this field could be the string ``'VIX'``. mask : bool, optional Drop any rows which cannot be symbol mapped. symbol_column : str If the data is attaching some new attribute to each asset then this argument is the name of the column in the preprocessed dataframe containing the symbols. This will be used along with the date information to map the sids in the asset finder. country_code : str, optional Country code to use to disambiguate symbol lookups. **kwargs Forwarded to :func:`pandas.read_csv`. Returns ------- csv_data_source : zipline.sources.requests_csv.PandasRequestsCSV A requests source that will pull data from the url specified. """ if country_code is None: country_code = self.default_fetch_csv_country_code( self.trading_calendar, ) # Show all the logs every time fetcher is used. csv_data_source = PandasRequestsCSV( url, pre_func, post_func, self.asset_finder, self.trading_calendar.day, self.sim_params.start_session, self.sim_params.end_session, date_column, date_format, timezone, symbol, mask, symbol_column, data_frequency=self.data_frequency, country_code=country_code, special_params_checker=special_params_checker, **kwargs ) # ingest this into dataportal self.data_portal.handle_extra_source(csv_data_source.df, self.sim_params) return csv_data_source
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=None, special_params_checker=None, country_code=None, **kwargs): """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 preprocessing the raw data returned from fetch_csv before dates are paresed or symbols are mapped. post_func : callable[pd.DataFrame -> pd.DataFrame], optional A callback to allow postprocessing of the data after dates and symbols have been mapped. date_column : str, optional The name of the column in the preprocessed dataframe containing datetime information to map the data. date_format : str, optional The format of the dates in the ``date_column``. If not provided ``fetch_csv`` will attempt to infer the format. For information about the format of this string, see :func:`pandas.read_csv`. timezone : tzinfo or str, optional The timezone for the datetime in the ``date_column``. symbol : str, optional If the data is about a new asset or index then this string will be the name used to identify the values in ``data``. For example, one may use ``fetch_csv`` to load data for VIX, then this field could be the string ``'VIX'``. mask : bool, optional Drop any rows which cannot be symbol mapped. symbol_column : str If the data is attaching some new attribute to each asset then this argument is the name of the column in the preprocessed dataframe containing the symbols. This will be used along with the date information to map the sids in the asset finder. country_code : str, optional Country code to use to disambiguate symbol lookups. **kwargs Forwarded to :func:`pandas.read_csv`. Returns ------- csv_data_source : zipline.sources.requests_csv.PandasRequestsCSV A requests source that will pull data from the url specified. """ if country_code is None: country_code = self.default_fetch_csv_country_code( self.trading_calendar, ) # Show all the logs every time fetcher is used. csv_data_source = PandasRequestsCSV( url, pre_func, post_func, self.asset_finder, self.trading_calendar.day, self.sim_params.start_session, self.sim_params.end_session, date_column, date_format, timezone, symbol, mask, symbol_column, data_frequency=self.data_frequency, country_code=country_code, special_params_checker=special_params_checker, **kwargs ) # ingest this into dataportal self.data_portal.handle_extra_source(csv_data_source.df, self.sim_params) return csv_data_source
[ "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 rule is triggered. """ self.event_manager.add_event( zipline.utils.events.Event(rule, callback), )
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 rule is triggered. """ self.event_manager.add_event( zipline.utils.events.Event(rule, callback), )
[ "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. time_rule : EventRule, optional The rule for the times to execute this function. half_days : bool, optional Should this rule fire on half days? calendar : Sentinel, optional Calendar used to reconcile date and time rules. See Also -------- :class:`zipline.api.date_rules` :class:`zipline.api.time_rules`
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. 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. time_rule : EventRule, optional The rule for the times to execute this function. half_days : bool, optional Should this rule fire on half days? calendar : Sentinel, optional Calendar used to reconcile date and time rules. See Also -------- :class:`zipline.api.date_rules` :class:`zipline.api.time_rules` """ # When the user calls schedule_function(func, <time_rule>), assume that # the user meant to specify a time rule but no date rule, instead of # a date rule and no time rule as the signature suggests if isinstance(date_rule, (AfterOpen, BeforeClose)) and not time_rule: warnings.warn('Got a time rule for the second positional argument ' 'date_rule. You should use keyword argument ' 'time_rule= when calling schedule_function without ' 'specifying a date_rule', stacklevel=3) date_rule = date_rule or date_rules.every_day() time_rule = ((time_rule or time_rules.every_minute()) if self.sim_params.data_frequency == 'minute' else # If we are in daily mode the time_rule is ignored. time_rules.every_minute()) # Check the type of the algorithm's schedule before pulling calendar # Note that the ExchangeTradingSchedule is currently the only # TradingSchedule class, so this is unlikely to be hit if calendar is None: cal = self.trading_calendar elif calendar is calendars.US_EQUITIES: cal = get_calendar('XNYS') elif calendar is calendars.US_FUTURES: cal = get_calendar('us_futures') else: raise ScheduleFunctionInvalidCalendar( given_calendar=calendar, allowed_calendars=( '[calendars.US_EQUITIES, calendars.US_FUTURES]' ), ) self.add_event( make_eventrule(date_rule, time_rule, cal, half_days), func, )
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. 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. time_rule : EventRule, optional The rule for the times to execute this function. half_days : bool, optional Should this rule fire on half days? calendar : Sentinel, optional Calendar used to reconcile date and time rules. See Also -------- :class:`zipline.api.date_rules` :class:`zipline.api.time_rules` """ # When the user calls schedule_function(func, <time_rule>), assume that # the user meant to specify a time rule but no date rule, instead of # a date rule and no time rule as the signature suggests if isinstance(date_rule, (AfterOpen, BeforeClose)) and not time_rule: warnings.warn('Got a time rule for the second positional argument ' 'date_rule. You should use keyword argument ' 'time_rule= when calling schedule_function without ' 'specifying a date_rule', stacklevel=3) date_rule = date_rule or date_rules.every_day() time_rule = ((time_rule or time_rules.every_minute()) if self.sim_params.data_frequency == 'minute' else # If we are in daily mode the time_rule is ignored. time_rules.every_minute()) # Check the type of the algorithm's schedule before pulling calendar # Note that the ExchangeTradingSchedule is currently the only # TradingSchedule class, so this is unlikely to be hit if calendar is None: cal = self.trading_calendar elif calendar is calendars.US_EQUITIES: cal = get_calendar('XNYS') elif calendar is calendars.US_FUTURES: cal = get_calendar('us_futures') else: raise ScheduleFunctionInvalidCalendar( given_calendar=calendar, allowed_calendars=( '[calendars.US_EQUITIES, calendars.US_FUTURES]' ), ) self.add_event( make_eventrule(date_rule, time_rule, cal, half_days), func, )
[ "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 are determined. Default is 'volume'. adjustment : str, optional Method for adjusting lookback prices between rolls. Options are 'mul', 'add', and None. Default is 'mul'. Returns ------- continuous_future : ContinuousFuture The continuous future specifier.
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 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 are determined. Default is 'volume'. adjustment : str, optional Method for adjusting lookback prices between rolls. Options are 'mul', 'add', and None. Default is 'mul'. Returns ------- continuous_future : ContinuousFuture The continuous future specifier. """ return self.asset_finder.create_continuous_future( root_symbol_str, offset, roll, adjustment, )
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 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 are determined. Default is 'volume'. adjustment : str, optional Method for adjusting lookback prices between rolls. Options are 'mul', 'add', and None. Default is 'mul'. Returns ------- continuous_future : ContinuousFuture The continuous future specifier. """ return self.asset_finder.create_continuous_future( root_symbol_str, offset, roll, adjustment, )
[ "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 The equity that held the ticker symbol on the current symbol lookup date. Raises ------ SymbolNotFound Raised when the symbols was not held on the current lookup date. See Also -------- :func:`zipline.api.set_symbol_lookup_date`
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. Returns ------- equity : Equity The equity that held the ticker symbol on the current symbol lookup date. Raises ------ SymbolNotFound Raised when the symbols was not held on the current lookup date. See Also -------- :func:`zipline.api.set_symbol_lookup_date` """ # 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 self._symbol_lookup_date is not None \ else self.sim_params.end_session return self.asset_finder.lookup_symbol( symbol_str, as_of_date=_lookup_date, country_code=country_code, )
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. Returns ------- equity : Equity The equity that held the ticker symbol on the current symbol lookup date. Raises ------ SymbolNotFound Raised when the symbols was not held on the current lookup date. See Also -------- :func:`zipline.api.set_symbol_lookup_date` """ # 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 self._symbol_lookup_date is not None \ else self.sim_params.end_session return self.asset_finder.lookup_symbol( symbol_str, as_of_date=_lookup_date, country_code=country_code, )
[ "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] The equities that held the given ticker symbols on the current symbol lookup date. Raises ------ SymbolNotFound Raised when one of the symbols was not held on the current lookup date. See Also -------- :func:`zipline.api.set_symbol_lookup_date`
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 ------- equities : list[Equity] The equities that held the given ticker symbols on the current symbol lookup date. Raises ------ SymbolNotFound Raised when one of the symbols was not held on the current lookup date. See Also -------- :func:`zipline.api.set_symbol_lookup_date` """ return [self.symbol(identifier, **kwargs) for identifier in args]
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 ------- equities : list[Equity] The equities that held the given ticker symbols on the current symbol lookup date. Raises ------ SymbolNotFound Raised when one of the symbols was not held on the current lookup date. See Also -------- :func:`zipline.api.set_symbol_lookup_date` """ return [self.symbol(identifier, **kwargs) for identifier in args]
[ "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 here, but I haven't # yet found a good way to do that. normalized_date = normalize_date(self.datetime) if normalized_date < asset.start_date: raise CannotOrderDelistedAsset( msg="Cannot order {0}, as it started trading on" " {1}.".format(asset.symbol, asset.start_date) ) elif normalized_date > asset.end_date: raise CannotOrderDelistedAsset( msg="Cannot order {0}, as it stopped trading on" " {1}.".format(asset.symbol, asset.end_date) ) else: last_price = \ self.trading_client.current_data.current(asset, "price") if np.isnan(last_price): raise CannotOrderDelistedAsset( msg="Cannot order {0} on {1} as there is no last " "price for the security.".format(asset.symbol, self.datetime) ) if tolerant_equals(last_price, 0): zero_message = "Price of 0 for {psid}; can't infer value".format( psid=asset ) if self.logger: self.logger.debug(zero_message) # Don't place any order return 0 value_multiplier = asset.price_multiplier return value / (last_price * value_multiplier)
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 here, but I haven't # yet found a good way to do that. normalized_date = normalize_date(self.datetime) if normalized_date < asset.start_date: raise CannotOrderDelistedAsset( msg="Cannot order {0}, as it started trading on" " {1}.".format(asset.symbol, asset.start_date) ) elif normalized_date > asset.end_date: raise CannotOrderDelistedAsset( msg="Cannot order {0}, as it stopped trading on" " {1}.".format(asset.symbol, asset.end_date) ) else: last_price = \ self.trading_client.current_data.current(asset, "price") if np.isnan(last_price): raise CannotOrderDelistedAsset( msg="Cannot order {0} on {1} as there is no last " "price for the security.".format(asset.symbol, self.datetime) ) if tolerant_equals(last_price, 0): zero_message = "Price of 0 for {psid}; can't infer value".format( psid=asset ) if self.logger: self.logger.debug(zero_message) # Don't place any order return 0 value_multiplier = asset.price_multiplier return value / (last_price * value_multiplier)
[ "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 the number of shares to sell or short. limit_price : float, optional The limit price for the order. stop_price : float, optional The stop price for the order. style : ExecutionStyle, optional The execution style for the order. Returns ------- order_id : str or None The unique identifier for this order, or None if no order was placed. Notes ----- The ``limit_price`` and ``stop_price`` arguments provide shorthands for passing common execution styles. Passing ``limit_price=N`` is equivalent to ``style=LimitOrder(N)``. Similarly, passing ``stop_price=M`` is equivalent to ``style=StopOrder(M)``, and passing ``limit_price=N`` and ``stop_price=M`` is equivalent to ``style=StopLimitOrder(N, M)``. It is an error to pass both a ``style`` and ``limit_price`` or ``stop_price``. See Also -------- :class:`zipline.finance.execution.ExecutionStyle` :func:`zipline.api.order_value` :func:`zipline.api.order_percent`
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 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 the number of shares to sell or short. limit_price : float, optional The limit price for the order. stop_price : float, optional The stop price for the order. style : ExecutionStyle, optional The execution style for the order. Returns ------- order_id : str or None The unique identifier for this order, or None if no order was placed. Notes ----- The ``limit_price`` and ``stop_price`` arguments provide shorthands for passing common execution styles. Passing ``limit_price=N`` is equivalent to ``style=LimitOrder(N)``. Similarly, passing ``stop_price=M`` is equivalent to ``style=StopOrder(M)``, and passing ``limit_price=N`` and ``stop_price=M`` is equivalent to ``style=StopLimitOrder(N, M)``. It is an error to pass both a ``style`` and ``limit_price`` or ``stop_price``. See Also -------- :class:`zipline.finance.execution.ExecutionStyle` :func:`zipline.api.order_value` :func:`zipline.api.order_percent` """ if not self._can_order_asset(asset): return None amount, style = self._calculate_order(asset, amount, limit_price, stop_price, style) return self.blotter.order(asset, amount, style)
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 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 the number of shares to sell or short. limit_price : float, optional The limit price for the order. stop_price : float, optional The stop price for the order. style : ExecutionStyle, optional The execution style for the order. Returns ------- order_id : str or None The unique identifier for this order, or None if no order was placed. Notes ----- The ``limit_price`` and ``stop_price`` arguments provide shorthands for passing common execution styles. Passing ``limit_price=N`` is equivalent to ``style=LimitOrder(N)``. Similarly, passing ``stop_price=M`` is equivalent to ``style=StopOrder(M)``, and passing ``limit_price=N`` and ``stop_price=M`` is equivalent to ``style=StopLimitOrder(N, M)``. It is an error to pass both a ``style`` and ``limit_price`` or ``stop_price``. See Also -------- :class:`zipline.finance.execution.ExecutionStyle` :func:`zipline.api.order_value` :func:`zipline.api.order_percent` """ if not self._can_order_asset(asset): return None amount, style = self._calculate_order(asset, amount, limit_price, stop_price, style) return self.blotter.order(asset, amount, style)
[ "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. Raises an UnsupportedOrderParameters if invalid arguments are found. """ if not self.initialized: raise OrderDuringInitialize( msg="order() can only be called from within handle_data()" ) if style: if limit_price: raise UnsupportedOrderParameters( msg="Passing both limit_price and style is not supported." ) if stop_price: raise UnsupportedOrderParameters( msg="Passing both stop_price and style is not supported." ) for control in self.trading_controls: control.validate(asset, amount, self.portfolio, self.get_datetime(), self.trading_client.current_data)
def validate_order_params(self, asset, amount, limit_price, stop_price, style): """ Helper method for validating parameters to the order API function. Raises an UnsupportedOrderParameters if invalid arguments are found. """ if not self.initialized: raise OrderDuringInitialize( msg="order() can only be called from within handle_data()" ) if style: if limit_price: raise UnsupportedOrderParameters( msg="Passing both limit_price and style is not supported." ) if stop_price: raise UnsupportedOrderParameters( msg="Passing both stop_price and style is not supported." ) for control in self.trading_controls: control.validate(asset, amount, self.portfolio, self.get_datetime(), self.trading_client.current_data)
[ "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 ExecutionStyle instances. This function assumes that either style == None or (limit_price, stop_price) == (None, None). """ if style: assert (limit_price, stop_price) == (None, None) return style if limit_price and stop_price: return StopLimitOrder(limit_price, stop_price, asset=asset) if limit_price: return LimitOrder(limit_price, asset=asset) if stop_price: return StopOrder(stop_price, asset=asset) else: return MarketOrder()
def __convert_order_params_for_blotter(asset, limit_price, stop_price, style): """ 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). """ if style: assert (limit_price, stop_price) == (None, None) return style if limit_price and stop_price: return StopLimitOrder(limit_price, stop_price, asset=asset) if limit_price: return LimitOrder(limit_price, asset=asset) if stop_price: return StopOrder(stop_price, asset=asset) else: return MarketOrder()
[ "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 number of shares to transact. If the Asset being ordered is a Future, the 'value' calculated is actually the exposure, as Futures have no 'value'. value > 0 :: Buy/Cover value < 0 :: Sell/Short limit_price : float, optional The limit price for the order. stop_price : float, optional The stop price for the order. style : ExecutionStyle The execution style for the order. Returns ------- order_id : str The unique identifier for this order. Notes ----- See :func:`zipline.api.order` for more information about ``limit_price``, ``stop_price``, and ``style`` See Also -------- :class:`zipline.finance.execution.ExecutionStyle` :func:`zipline.api.order` :func:`zipline.api.order_percent`
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 ---------- 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 number of shares to transact. If the Asset being ordered is a Future, the 'value' calculated is actually the exposure, as Futures have no 'value'. value > 0 :: Buy/Cover value < 0 :: Sell/Short limit_price : float, optional The limit price for the order. stop_price : float, optional The stop price for the order. style : ExecutionStyle The execution style for the order. Returns ------- order_id : str The unique identifier for this order. Notes ----- See :func:`zipline.api.order` for more information about ``limit_price``, ``stop_price``, and ``style`` See Also -------- :class:`zipline.finance.execution.ExecutionStyle` :func:`zipline.api.order` :func:`zipline.api.order_percent` """ if not self._can_order_asset(asset): return None amount = self._calculate_order_value_amount(asset, value) return self.order(asset, amount, limit_price=limit_price, stop_price=stop_price, style=style)
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 ---------- 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 number of shares to transact. If the Asset being ordered is a Future, the 'value' calculated is actually the exposure, as Futures have no 'value'. value > 0 :: Buy/Cover value < 0 :: Sell/Short limit_price : float, optional The limit price for the order. stop_price : float, optional The stop price for the order. style : ExecutionStyle The execution style for the order. Returns ------- order_id : str The unique identifier for this order. Notes ----- See :func:`zipline.api.order` for more information about ``limit_price``, ``stop_price``, and ``style`` See Also -------- :class:`zipline.finance.execution.ExecutionStyle` :func:`zipline.api.order` :func:`zipline.api.order_percent` """ if not self._can_order_asset(asset): return None amount = self._calculate_order_value_amount(asset, value) return self.order(asset, amount, limit_price=limit_price, stop_price=stop_price, style=style)
[ "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 calls in the same bar are cheap. """ if dt is None: dt = self.datetime if dt != self._last_sync_time: self.metrics_tracker.sync_last_sale_prices( dt, self.data_portal, ) self._last_sync_time = dt
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 calls in the same bar are cheap. """ if dt is None: dt = self.datetime if dt != self._last_sync_time: self.metrics_tracker.sync_last_sale_prices( dt, self.data_portal, ) self._last_sync_time = dt
[ "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 current simulation datetime converted to ``tz``. """ dt = self.datetime assert dt.tzinfo == pytz.utc, "Algorithm should have a utc datetime" if tz is not None: dt = dt.astimezone(tz) return dt
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 current simulation datetime converted to ``tz``. """ dt = self.datetime assert dt.tzinfo == pytz.utc, "Algorithm should have a utc datetime" if tz is not None: dt = dt.astimezone(tz) return dt
[ "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 -------- :class:`zipline.finance.slippage.SlippageModel`
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 slippage model to use for trading US futures. See Also -------- :class:`zipline.finance.slippage.SlippageModel` """ if self.initialized: raise SetSlippagePostInit() if us_equities is not None: if Equity not in us_equities.allowed_asset_types: raise IncompatibleSlippageModel( asset_type='equities', given_model=us_equities, supported_asset_types=us_equities.allowed_asset_types, ) self.blotter.slippage_models[Equity] = us_equities if us_futures is not None: if Future not in us_futures.allowed_asset_types: raise IncompatibleSlippageModel( asset_type='futures', given_model=us_futures, supported_asset_types=us_futures.allowed_asset_types, ) self.blotter.slippage_models[Future] = us_futures
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 slippage model to use for trading US futures. See Also -------- :class:`zipline.finance.slippage.SlippageModel` """ if self.initialized: raise SetSlippagePostInit() if us_equities is not None: if Equity not in us_equities.allowed_asset_types: raise IncompatibleSlippageModel( asset_type='equities', given_model=us_equities, supported_asset_types=us_equities.allowed_asset_types, ) self.blotter.slippage_models[Equity] = us_equities if us_futures is not None: if Future not in us_futures.allowed_asset_types: raise IncompatibleSlippageModel( asset_type='futures', given_model=us_futures, supported_asset_types=us_futures.allowed_asset_types, ) self.blotter.slippage_models[Future] = us_futures
[ "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 -------- :class:`zipline.finance.commission.PerShare` :class:`zipline.finance.commission.PerTrade` :class:`zipline.finance.commission.PerDollar`
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 The commission model to use for trading US futures. See Also -------- :class:`zipline.finance.commission.PerShare` :class:`zipline.finance.commission.PerTrade` :class:`zipline.finance.commission.PerDollar` """ if self.initialized: raise SetCommissionPostInit() if us_equities is not None: if Equity not in us_equities.allowed_asset_types: raise IncompatibleCommissionModel( asset_type='equities', given_model=us_equities, supported_asset_types=us_equities.allowed_asset_types, ) self.blotter.commission_models[Equity] = us_equities if us_futures is not None: if Future not in us_futures.allowed_asset_types: raise IncompatibleCommissionModel( asset_type='futures', given_model=us_futures, supported_asset_types=us_futures.allowed_asset_types, ) self.blotter.commission_models[Future] = us_futures
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 The commission model to use for trading US futures. See Also -------- :class:`zipline.finance.commission.PerShare` :class:`zipline.finance.commission.PerTrade` :class:`zipline.finance.commission.PerDollar` """ if self.initialized: raise SetCommissionPostInit() if us_equities is not None: if Equity not in us_equities.allowed_asset_types: raise IncompatibleCommissionModel( asset_type='equities', given_model=us_equities, supported_asset_types=us_equities.allowed_asset_types, ) self.blotter.commission_models[Equity] = us_equities if us_futures is not None: if Future not in us_futures.allowed_asset_types: raise IncompatibleCommissionModel( asset_type='futures', given_model=us_futures, supported_asset_types=us_futures.allowed_asset_types, ) self.blotter.commission_models[Future] = us_futures
[ "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:`zipline.api.NeverCancel` """ if not isinstance(cancel_policy, CancelPolicy): raise UnsupportedCancelPolicy() if self.initialized: raise SetCancelPolicyPostInit() self.blotter.cancel_policy = cancel_policy
def set_cancel_policy(self, cancel_policy): """Sets the order cancellation policy for the simulation. Parameters ---------- cancel_policy : CancelPolicy The cancellation policy to use. See Also -------- :class:`zipline.api.EODCancel` :class:`zipline.api.NeverCancel` """ if not isinstance(cancel_policy, CancelPolicy): raise UnsupportedCancelPolicy() if self.initialized: raise SetCancelPolicyPostInit() self.blotter.cancel_policy = cancel_policy
[ "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. """ try: self._symbol_lookup_date = pd.Timestamp(dt, tz='UTC') except ValueError: raise UnsupportedDatetimeFormat(input=dt, method='set_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. """ try: self._symbol_lookup_date = pd.Timestamp(dt, tz='UTC') except ValueError: raise UnsupportedDatetimeFormat(input=dt, method='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", ")" ]
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``. This is specified as a decimal, for example: 0.50 means 50%. limit_price : float, optional The limit price for the order. stop_price : float, optional The stop price for the order. style : ExecutionStyle The execution style for the order. Returns ------- order_id : str The unique identifier for this order. Notes ----- See :func:`zipline.api.order` for more information about ``limit_price``, ``stop_price``, and ``style`` See Also -------- :class:`zipline.finance.execution.ExecutionStyle` :func:`zipline.api.order` :func:`zipline.api.order_value`
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. Parameters ---------- asset : Asset The asset that this order is for. percent : float The percentage of the portfolio value to allocate to ``asset``. This is specified as a decimal, for example: 0.50 means 50%. limit_price : float, optional The limit price for the order. stop_price : float, optional The stop price for the order. style : ExecutionStyle The execution style for the order. Returns ------- order_id : str The unique identifier for this order. Notes ----- See :func:`zipline.api.order` for more information about ``limit_price``, ``stop_price``, and ``style`` See Also -------- :class:`zipline.finance.execution.ExecutionStyle` :func:`zipline.api.order` :func:`zipline.api.order_value` """ if not self._can_order_asset(asset): return None amount = self._calculate_order_percent_amount(asset, percent) return self.order(asset, amount, limit_price=limit_price, stop_price=stop_price, style=style)
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. Parameters ---------- asset : Asset The asset that this order is for. percent : float The percentage of the portfolio value to allocate to ``asset``. This is specified as a decimal, for example: 0.50 means 50%. limit_price : float, optional The limit price for the order. stop_price : float, optional The stop price for the order. style : ExecutionStyle The execution style for the order. Returns ------- order_id : str The unique identifier for this order. Notes ----- See :func:`zipline.api.order` for more information about ``limit_price``, ``stop_price``, and ``style`` See Also -------- :class:`zipline.finance.execution.ExecutionStyle` :func:`zipline.api.order` :func:`zipline.api.order_value` """ if not self._can_order_asset(asset): return None amount = self._calculate_order_percent_amount(asset, percent) return self.order(asset, amount, limit_price=limit_price, stop_price=stop_price, style=style)
[ "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 number of shares. Parameters ---------- asset : Asset The asset that this order is for. target : int The desired number of shares of ``asset``. limit_price : float, optional The limit price for the order. stop_price : float, optional The stop price for the order. style : ExecutionStyle The execution style for the order. Returns ------- order_id : str The unique identifier for this order. Notes ----- ``order_target`` does not take into account any open orders. For example: .. code-block:: python order_target(sid(0), 10) order_target(sid(0), 10) This code will result in 20 shares of ``sid(0)`` because the first call to ``order_target`` will not have been filled when the second ``order_target`` call is made. See :func:`zipline.api.order` for more information about ``limit_price``, ``stop_price``, and ``style`` See Also -------- :class:`zipline.finance.execution.ExecutionStyle` :func:`zipline.api.order` :func:`zipline.api.order_target_percent` :func:`zipline.api.order_target_value`
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 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 number of shares. Parameters ---------- asset : Asset The asset that this order is for. target : int The desired number of shares of ``asset``. limit_price : float, optional The limit price for the order. stop_price : float, optional The stop price for the order. style : ExecutionStyle The execution style for the order. Returns ------- order_id : str The unique identifier for this order. Notes ----- ``order_target`` does not take into account any open orders. For example: .. code-block:: python order_target(sid(0), 10) order_target(sid(0), 10) This code will result in 20 shares of ``sid(0)`` because the first call to ``order_target`` will not have been filled when the second ``order_target`` call is made. See :func:`zipline.api.order` for more information about ``limit_price``, ``stop_price``, and ``style`` See Also -------- :class:`zipline.finance.execution.ExecutionStyle` :func:`zipline.api.order` :func:`zipline.api.order_target_percent` :func:`zipline.api.order_target_value` """ if not self._can_order_asset(asset): return None amount = self._calculate_order_target_amount(asset, target) return self.order(asset, amount, limit_price=limit_price, stop_price=stop_price, style=style)
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 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 number of shares. Parameters ---------- asset : Asset The asset that this order is for. target : int The desired number of shares of ``asset``. limit_price : float, optional The limit price for the order. stop_price : float, optional The stop price for the order. style : ExecutionStyle The execution style for the order. Returns ------- order_id : str The unique identifier for this order. Notes ----- ``order_target`` does not take into account any open orders. For example: .. code-block:: python order_target(sid(0), 10) order_target(sid(0), 10) This code will result in 20 shares of ``sid(0)`` because the first call to ``order_target`` will not have been filled when the second ``order_target`` call is made. See :func:`zipline.api.order` for more information about ``limit_price``, ``stop_price``, and ``style`` See Also -------- :class:`zipline.finance.execution.ExecutionStyle` :func:`zipline.api.order` :func:`zipline.api.order_target_percent` :func:`zipline.api.order_target_value` """ if not self._can_order_asset(asset): return None amount = self._calculate_order_target_amount(asset, target) return self.order(asset, amount, limit_price=limit_price, stop_price=stop_price, style=style)
[ "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 Asset being ordered is a Future, the 'target value' calculated is actually the target exposure, as Futures have no 'value'. Parameters ---------- asset : Asset The asset that this order is for. target : float The desired total value of ``asset``. limit_price : float, optional The limit price for the order. stop_price : float, optional The stop price for the order. style : ExecutionStyle The execution style for the order. Returns ------- order_id : str The unique identifier for this order. Notes ----- ``order_target_value`` does not take into account any open orders. For example: .. code-block:: python order_target_value(sid(0), 10) order_target_value(sid(0), 10) This code will result in 20 dollars of ``sid(0)`` because the first call to ``order_target_value`` will not have been filled when the second ``order_target_value`` call is made. See :func:`zipline.api.order` for more information about ``limit_price``, ``stop_price``, and ``style`` See Also -------- :class:`zipline.finance.execution.ExecutionStyle` :func:`zipline.api.order` :func:`zipline.api.order_target` :func:`zipline.api.order_target_percent`
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 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 Asset being ordered is a Future, the 'target value' calculated is actually the target exposure, as Futures have no 'value'. Parameters ---------- asset : Asset The asset that this order is for. target : float The desired total value of ``asset``. limit_price : float, optional The limit price for the order. stop_price : float, optional The stop price for the order. style : ExecutionStyle The execution style for the order. Returns ------- order_id : str The unique identifier for this order. Notes ----- ``order_target_value`` does not take into account any open orders. For example: .. code-block:: python order_target_value(sid(0), 10) order_target_value(sid(0), 10) This code will result in 20 dollars of ``sid(0)`` because the first call to ``order_target_value`` will not have been filled when the second ``order_target_value`` call is made. See :func:`zipline.api.order` for more information about ``limit_price``, ``stop_price``, and ``style`` See Also -------- :class:`zipline.finance.execution.ExecutionStyle` :func:`zipline.api.order` :func:`zipline.api.order_target` :func:`zipline.api.order_target_percent` """ if not self._can_order_asset(asset): return None target_amount = self._calculate_order_value_amount(asset, target) amount = self._calculate_order_target_amount(asset, target_amount) return self.order(asset, amount, limit_price=limit_price, stop_price=stop_price, style=style)
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 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 Asset being ordered is a Future, the 'target value' calculated is actually the target exposure, as Futures have no 'value'. Parameters ---------- asset : Asset The asset that this order is for. target : float The desired total value of ``asset``. limit_price : float, optional The limit price for the order. stop_price : float, optional The stop price for the order. style : ExecutionStyle The execution style for the order. Returns ------- order_id : str The unique identifier for this order. Notes ----- ``order_target_value`` does not take into account any open orders. For example: .. code-block:: python order_target_value(sid(0), 10) order_target_value(sid(0), 10) This code will result in 20 dollars of ``sid(0)`` because the first call to ``order_target_value`` will not have been filled when the second ``order_target_value`` call is made. See :func:`zipline.api.order` for more information about ``limit_price``, ``stop_price``, and ``style`` See Also -------- :class:`zipline.finance.execution.ExecutionStyle` :func:`zipline.api.order` :func:`zipline.api.order_target` :func:`zipline.api.order_target_percent` """ if not self._can_order_asset(asset): return None target_amount = self._calculate_order_value_amount(asset, target) amount = self._calculate_order_target_amount(asset, target_amount) return self.order(asset, amount, limit_price=limit_price, stop_price=stop_price, style=style)
[ "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 the current percent. Parameters ---------- asset : Asset The asset that this order is for. target : float The desired percentage of the portfolio value to allocate to ``asset``. This is specified as a decimal, for example: 0.50 means 50%. limit_price : float, optional The limit price for the order. stop_price : float, optional The stop price for the order. style : ExecutionStyle The execution style for the order. Returns ------- order_id : str The unique identifier for this order. Notes ----- ``order_target_value`` does not take into account any open orders. For example: .. code-block:: python order_target_percent(sid(0), 10) order_target_percent(sid(0), 10) This code will result in 20% of the portfolio being allocated to sid(0) because the first call to ``order_target_percent`` will not have been filled when the second ``order_target_percent`` call is made. See :func:`zipline.api.order` for more information about ``limit_price``, ``stop_price``, and ``style`` See Also -------- :class:`zipline.finance.execution.ExecutionStyle` :func:`zipline.api.order` :func:`zipline.api.order_target` :func:`zipline.api.order_target_value`
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. If the position does exist, this is equivalent to placing an order for the difference between the target percent and the current percent. Parameters ---------- asset : Asset The asset that this order is for. target : float The desired percentage of the portfolio value to allocate to ``asset``. This is specified as a decimal, for example: 0.50 means 50%. limit_price : float, optional The limit price for the order. stop_price : float, optional The stop price for the order. style : ExecutionStyle The execution style for the order. Returns ------- order_id : str The unique identifier for this order. Notes ----- ``order_target_value`` does not take into account any open orders. For example: .. code-block:: python order_target_percent(sid(0), 10) order_target_percent(sid(0), 10) This code will result in 20% of the portfolio being allocated to sid(0) because the first call to ``order_target_percent`` will not have been filled when the second ``order_target_percent`` call is made. See :func:`zipline.api.order` for more information about ``limit_price``, ``stop_price``, and ``style`` See Also -------- :class:`zipline.finance.execution.ExecutionStyle` :func:`zipline.api.order` :func:`zipline.api.order_target` :func:`zipline.api.order_target_value` """ if not self._can_order_asset(asset): return None amount = self._calculate_order_target_percent_amount(asset, target) return self.order(asset, amount, limit_price=limit_price, stop_price=stop_price, style=style)
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. If the position does exist, this is equivalent to placing an order for the difference between the target percent and the current percent. Parameters ---------- asset : Asset The asset that this order is for. target : float The desired percentage of the portfolio value to allocate to ``asset``. This is specified as a decimal, for example: 0.50 means 50%. limit_price : float, optional The limit price for the order. stop_price : float, optional The stop price for the order. style : ExecutionStyle The execution style for the order. Returns ------- order_id : str The unique identifier for this order. Notes ----- ``order_target_value`` does not take into account any open orders. For example: .. code-block:: python order_target_percent(sid(0), 10) order_target_percent(sid(0), 10) This code will result in 20% of the portfolio being allocated to sid(0) because the first call to ``order_target_percent`` will not have been filled when the second ``order_target_percent`` call is made. See :func:`zipline.api.order` for more information about ``limit_price``, ``stop_price``, and ``style`` See Also -------- :class:`zipline.finance.execution.ExecutionStyle` :func:`zipline.api.order` :func:`zipline.api.order_target` :func:`zipline.api.order_target_value` """ if not self._can_order_asset(asset): return None amount = self._calculate_order_target_percent_amount(asset, target) return self.order(asset, amount, limit_price=limit_price, stop_price=stop_price, style=style)
[ "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 orders.
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.Index[str] Index of ids for newly-created orders. """ style = MarketOrder() order_args = [ (asset, amount, style) for (asset, amount) in iteritems(share_counts) if amount ] return self.blotter.batch_order(order_args)
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.Index[str] Index of ids for newly-created orders. """ style = MarketOrder() order_args = [ (asset, amount, style) for (asset, amount) in iteritems(share_counts) if amount ] return self.blotter.batch_order(order_args)
[ "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] If no asset is passed this will return a dict mapping Assets to a list containing all the open orders for the asset. If an asset is passed then this will return a list of the open orders for this asset.
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 ------- open_orders : dict[list[Order]] or list[Order] If no asset is passed this will return a dict mapping Assets to a list containing all the open orders for the asset. If an asset is passed then this will return a list of the open orders for this asset. """ if asset is None: return { key: [order.to_api_obj() for order in orders] for key, orders in iteritems(self.blotter.open_orders) if orders } if asset in self.blotter.open_orders: orders = self.blotter.open_orders[asset] return [order.to_api_obj() for order in orders] return []
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 ------- open_orders : dict[list[Order]] or list[Order] If no asset is passed this will return a dict mapping Assets to a list containing all the open orders for the asset. If an asset is passed then this will return a list of the open orders for this asset. """ if asset is None: return { key: [order.to_api_obj() for order in orders] for key, orders in iteritems(self.blotter.open_orders) if orders } if asset in self.blotter.open_orders: orders = self.blotter.open_orders[asset] return [order.to_api_obj() for order in orders] return []
[ "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 object. """ if order_id in self.blotter.orders: return self.blotter.orders[order_id].to_api_obj()
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 object. """ if order_id in self.blotter.orders: return self.blotter.orders[order_id].to_api_obj()
[ "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 = order_param.id self.blotter.cancel(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 = order_param.id self.blotter.cancel(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 ) return self.get_history_window( bar_count, frequency, self._calculate_universe(), field, ffill )
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 ) return self.get_history_window( bar_count, frequency, self._calculate_universe(), field, ffill )
[ "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 used to enforce a minimum leverage. """ deadline = self.sim_params.start_session + grace_period control = MinLeverage(min_leverage, deadline) self.register_account_control(control)
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 used to enforce a minimum leverage. """ deadline = self.sim_params.start_session + grace_period control = MinLeverage(min_leverage, deadline) self.register_account_control(control)
[ "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 splits/dividends, and more than the max notional due to price improvement. If an algorithm attempts to place an order that would result in increasing the absolute value of shares/dollar value exceeding one of these limits, raise a TradingControlException. Parameters ---------- asset : Asset, optional If provided, this sets the guard only on positions in the given asset. max_shares : int, optional The maximum number of shares to hold for an asset. max_notional : float, optional The maximum value to hold for an asset.
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. 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 splits/dividends, and more than the max notional due to price improvement. If an algorithm attempts to place an order that would result in increasing the absolute value of shares/dollar value exceeding one of these limits, raise a TradingControlException. Parameters ---------- asset : Asset, optional If provided, this sets the guard only on positions in the given asset. max_shares : int, optional The maximum number of shares to hold for an asset. max_notional : float, optional The maximum value to hold for an asset. """ control = MaxPositionSize(asset=asset, max_shares=max_shares, max_notional=max_notional, on_error=on_error) self.register_trading_control(control)
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. 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 splits/dividends, and more than the max notional due to price improvement. If an algorithm attempts to place an order that would result in increasing the absolute value of shares/dollar value exceeding one of these limits, raise a TradingControlException. Parameters ---------- asset : Asset, optional If provided, this sets the guard only on positions in the given asset. max_shares : int, optional The maximum number of shares to hold for an asset. max_notional : float, optional The maximum value to hold for an asset. """ control = MaxPositionSize(asset=asset, max_shares=max_shares, max_notional=max_notional, on_error=on_error) self.register_trading_control(control)
[ "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 of these limits, raise a TradingControlException. Parameters ---------- asset : Asset, optional If provided, this sets the guard only on positions in the given asset. max_shares : int, optional The maximum number of shares that can be ordered at one time. max_notional : float, optional The maximum value that can be ordered at one time.
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. 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 of these limits, raise a TradingControlException. Parameters ---------- asset : Asset, optional If provided, this sets the guard only on positions in the given asset. max_shares : int, optional The maximum number of shares that can be ordered at one time. max_notional : float, optional The maximum value that can be ordered at one time. """ control = MaxOrderSize(asset=asset, max_shares=max_shares, max_notional=max_notional, on_error=on_error) self.register_trading_control(control)
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. 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 of these limits, raise a TradingControlException. Parameters ---------- asset : Asset, optional If provided, this sets the guard only on positions in the given asset. max_shares : int, optional The maximum number of shares that can be ordered at one time. max_notional : float, optional The maximum value that can be ordered at one time. """ control = MaxOrderSize(asset=asset, max_shares=max_shares, max_notional=max_notional, on_error=on_error) self.register_trading_control(control)
[ "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 = MaxOrderCount(on_error, max_count) self.register_trading_control(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 = MaxOrderCount(on_error, max_count) self.register_trading_control(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 -------- zipline.finance.asset_restrictions.Restrictions """ control = RestrictedListOrder(on_error, restrictions) self.register_trading_control(control) self.restrictions |= restrictions
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 -------- zipline.finance.asset_restrictions.Restrictions """ control = RestrictedListOrder(on_error, restrictions) self.register_trading_control(control) self.restrictions |= restrictions
[ "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 pipeline results for. Increasing this number will make it longer to get the first results but may improve the total runtime of the simulation. If an iterator is passed, we will run in chunks based on values of the iterator. Default is True. eager : bool, optional Whether or not to compute this pipeline prior to before_trading_start. Returns ------- pipeline : Pipeline Returns the pipeline that was attached unchanged. See Also -------- :func:`zipline.api.pipeline_output`
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. chunks : int or iterator, optional The number of days to compute pipeline results for. Increasing this number will make it longer to get the first results but may improve the total runtime of the simulation. If an iterator is passed, we will run in chunks based on values of the iterator. Default is True. eager : bool, optional Whether or not to compute this pipeline prior to before_trading_start. Returns ------- pipeline : Pipeline Returns the pipeline that was attached unchanged. See Also -------- :func:`zipline.api.pipeline_output` """ if chunks is None: # Make the first chunk smaller to get more immediate results: # (one week, then every half year) chunks = chain([5], repeat(126)) elif isinstance(chunks, int): chunks = repeat(chunks) if name in self._pipelines: raise DuplicatePipelineName(name=name) self._pipelines[name] = AttachedPipeline(pipeline, iter(chunks), eager) # Return the pipeline to allow expressions like # p = attach_pipeline(Pipeline(), 'name') return pipeline
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. chunks : int or iterator, optional The number of days to compute pipeline results for. Increasing this number will make it longer to get the first results but may improve the total runtime of the simulation. If an iterator is passed, we will run in chunks based on values of the iterator. Default is True. eager : bool, optional Whether or not to compute this pipeline prior to before_trading_start. Returns ------- pipeline : Pipeline Returns the pipeline that was attached unchanged. See Also -------- :func:`zipline.api.pipeline_output` """ if chunks is None: # Make the first chunk smaller to get more immediate results: # (one week, then every half year) chunks = chain([5], repeat(126)) elif isinstance(chunks, int): chunks = repeat(chunks) if name in self._pipelines: raise DuplicatePipelineName(name=name) self._pipelines[name] = AttachedPipeline(pipeline, iter(chunks), eager) # Return the pipeline to allow expressions like # p = attach_pipeline(Pipeline(), 'name') return pipeline
[ "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 the requested pipeline for the current simulation date. Raises ------ NoSuchPipeline Raised when no pipeline with the name `name` has been registered. See Also -------- :func:`zipline.api.attach_pipeline` :meth:`zipline.pipeline.engine.PipelineEngine.run_pipeline`
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 DataFrame containing the results of the requested pipeline for the current simulation date. Raises ------ NoSuchPipeline Raised when no pipeline with the name `name` has been registered. See Also -------- :func:`zipline.api.attach_pipeline` :meth:`zipline.pipeline.engine.PipelineEngine.run_pipeline` """ try: pipe, chunks, _ = self._pipelines[name] except KeyError: raise NoSuchPipeline( name=name, valid=list(self._pipelines.keys()), ) return self._pipeline_output(pipe, chunks, name)
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 DataFrame containing the results of the requested pipeline for the current simulation date. Raises ------ NoSuchPipeline Raised when no pipeline with the name `name` has been registered. See Also -------- :func:`zipline.api.attach_pipeline` :meth:`zipline.pipeline.engine.PipelineEngine.run_pipeline` """ try: pipe, chunks, _ = self._pipelines[name] except KeyError: raise NoSuchPipeline( name=name, valid=list(self._pipelines.keys()), ) return self._pipeline_output(pipe, chunks, name)
[ "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. data, valid_until = self.run_pipeline( pipeline, today, next(chunks), ) self._pipeline_cache.set(name, data, valid_until) # Now that we have a cached result, try to return the data for today. try: return data.loc[today] except KeyError: # This happens if no assets passed the pipeline screen on a given # day. return pd.DataFrame(index=[], columns=data.columns)
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. data, valid_until = self.run_pipeline( pipeline, today, next(chunks), ) self._pipeline_cache.set(name, data, valid_until) # Now that we have a cached result, try to return the data for today. try: return data.loc[today] except KeyError: # This happens if no assets passed the pipeline screen on a given # day. return pd.DataFrame(index=[], columns=data.columns)
[ "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)` Returns ------- (data, valid_until) : tuple (pd.DataFrame, pd.Timestamp) See Also -------- PipelineEngine.run_pipeline
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 + chunksize trading days, simulation_end)` Returns ------- (data, valid_until) : tuple (pd.DataFrame, pd.Timestamp) See Also -------- PipelineEngine.run_pipeline """ sessions = self.trading_calendar.all_sessions # Load data starting from the previous trading day... start_date_loc = sessions.get_loc(start_session) # ...continuing until either the day before the simulation end, or # until chunksize days of data have been loaded. sim_end_session = self.sim_params.end_session end_loc = min( start_date_loc + chunksize, sessions.get_loc(sim_end_session) ) end_session = sessions[end_loc] return \ self.engine.run_pipeline(pipeline, start_session, end_session), \ end_session
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 + chunksize trading days, simulation_end)` Returns ------- (data, valid_until) : tuple (pd.DataFrame, pd.Timestamp) See Also -------- PipelineEngine.run_pipeline """ sessions = self.trading_calendar.all_sessions # Load data starting from the previous trading day... start_date_loc = sessions.get_loc(start_session) # ...continuing until either the day before the simulation end, or # until chunksize days of data have been loaded. sim_end_session = self.sim_params.end_session end_loc = min( start_date_loc + chunksize, sessions.get_loc(sim_end_session) ) end_session = sessions[end_loc] return \ self.engine.run_pipeline(pipeline, start_session, end_session), \ end_session
[ "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 = (" " * indent) + "- {}" return "\n".join(map(line_template.format, items))
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 = (" " * indent) + "- {}" return "\n".join(map(line_template.format, items))
[ "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) elif expected and expected is not Argument.ignore: raise exc_missing(*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) elif expected and expected is not Argument.ignore: raise 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", "." ]
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