repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.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. """ ...
python
def set_symbol_lookup_date(self, dt): """Set the date for which symbols will be resolved to their assets (symbols may map to different firms or underlying assets at different times) Parameters ---------- dt : datetime The new symbol lookup date. """ ...
[ "def", "set_symbol_lookup_date", "(", "self", ",", "dt", ")", ":", "try", ":", "self", ".", "_symbol_lookup_date", "=", "pd", ".", "Timestamp", "(", "dt", ",", "tz", "=", "'UTC'", ")", "except", "ValueError", ":", "raise", "UnsupportedDatetimeFormat", "(", ...
Set the date for which symbols will be resolved to their assets (symbols may map to different firms or underlying assets at different times) Parameters ---------- dt : datetime The new symbol lookup date.
[ "Set", "the", "date", "for", "which", "symbols", "will", "be", "resolved", "to", "their", "assets", "(", "symbols", "may", "map", "to", "different", "firms", "or", "underlying", "assets", "at", "different", "times", ")" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1588-L1602
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.order_percent
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...
python
def order_percent(self, asset, percent, limit_price=None, stop_price=None, style=None): """Place an order in the specified asset corresponding to the given percent of the current portfolio value...
[ "def", "order_percent", "(", "self", ",", "asset", ",", "percent", ",", "limit_price", "=", "None", ",", "stop_price", "=", "None", ",", "style", "=", "None", ")", ":", "if", "not", "self", ".", "_can_order_asset", "(", "asset", ")", ":", "return", "No...
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``. ...
[ "Place", "an", "order", "in", "the", "specified", "asset", "corresponding", "to", "the", "given", "percent", "of", "the", "current", "portfolio", "value", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1616-L1662
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.order_target
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 ...
python
def order_target(self, asset, target, limit_price=None, stop_price=None, style=None): """Place an order to adjust a position to a target number of shares. If the position doesn't already exist, this ...
[ "def", "order_target", "(", "self", ",", "asset", ",", "target", ",", "limit_price", "=", "None", ",", "stop_price", "=", "None", ",", "style", "=", "None", ")", ":", "if", "not", "self", ".", "_can_order_asset", "(", "asset", ")", ":", "return", "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 nu...
[ "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", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1670-L1732
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.order_target_value
def order_target_value(self, asset, target, limit_price=None, stop_price=None, style=None): """Place an order to adjust a position to a target value. If the position doe...
python
def order_target_value(self, asset, target, limit_price=None, stop_price=None, style=None): """Place an order to adjust a position to a target value. If the position doe...
[ "def", "order_target_value", "(", "self", ",", "asset", ",", "target", ",", "limit_price", "=", "None", ",", "stop_price", "=", "None", ",", "style", "=", "None", ")", ":", "if", "not", "self", ".", "_can_order_asset", "(", "asset", ")", ":", "return", ...
Place an order to adjust a position to a target value. If the position doesn't already exist, this is equivalent to placing a new order. If the position does exist, this is equivalent to placing an order for the difference between the target value and the current value. If the As...
[ "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",...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1743-L1807
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.order_target_percent
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. ...
python
def order_target_percent(self, asset, target, limit_price=None, stop_price=None, style=None): """Place an order to adjust a position to a target percent of the current portfolio value. If the position doesn't already exist, this is equivalent to placing a new order. ...
[ "def", "order_target_percent", "(", "self", ",", "asset", ",", "target", ",", "limit_price", "=", "None", ",", "stop_price", "=", "None", ",", "style", "=", "None", ")", ":", "if", "not", "self", ".", "_can_order_asset", "(", "asset", ")", ":", "return",...
Place an order to adjust a position to a target percent of the current portfolio value. If the position doesn't already exist, this is equivalent to placing a new order. If the position does exist, this is equivalent to placing an order for the difference between the target percent and t...
[ "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", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1811-L1870
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.batch_market_order
def batch_market_order(self, share_counts): """Place a batch market order for multiple assets. Parameters ---------- share_counts : pd.Series[Asset -> int] Map from asset to number of shares to order for that asset. Returns ------- order_ids : pd.Ind...
python
def batch_market_order(self, share_counts): """Place a batch market order for multiple assets. Parameters ---------- share_counts : pd.Series[Asset -> int] Map from asset to number of shares to order for that asset. Returns ------- order_ids : pd.Ind...
[ "def", "batch_market_order", "(", "self", ",", "share_counts", ")", ":", "style", "=", "MarketOrder", "(", ")", "order_args", "=", "[", "(", "asset", ",", "amount", ",", "style", ")", "for", "(", "asset", ",", "amount", ")", "in", "iteritems", "(", "sh...
Place a batch market order for multiple assets. Parameters ---------- share_counts : pd.Series[Asset -> int] Map from asset to number of shares to order for that asset. Returns ------- order_ids : pd.Index[str] Index of ids for newly-created orde...
[ "Place", "a", "batch", "market", "order", "for", "multiple", "assets", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1879-L1898
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.get_open_orders
def get_open_orders(self, asset=None): """Retrieve all of the current open orders. Parameters ---------- asset : Asset If passed and not None, return only the open orders for the given asset instead of all open orders. Returns ------- ope...
python
def get_open_orders(self, asset=None): """Retrieve all of the current open orders. Parameters ---------- asset : Asset If passed and not None, return only the open orders for the given asset instead of all open orders. Returns ------- ope...
[ "def", "get_open_orders", "(", "self", ",", "asset", "=", "None", ")", ":", "if", "asset", "is", "None", ":", "return", "{", "key", ":", "[", "order", ".", "to_api_obj", "(", ")", "for", "order", "in", "orders", "]", "for", "key", ",", "orders", "i...
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] ...
[ "Retrieve", "all", "of", "the", "current", "open", "orders", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1903-L1929
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.get_order
def get_order(self, order_id): """Lookup an order based on the order id returned from one of the order functions. Parameters ---------- order_id : str The unique identifier for the order. Returns ------- order : Order The order ob...
python
def get_order(self, order_id): """Lookup an order based on the order id returned from one of the order functions. Parameters ---------- order_id : str The unique identifier for the order. Returns ------- order : Order The order ob...
[ "def", "get_order", "(", "self", ",", "order_id", ")", ":", "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. Parameters ---------- order_id : str The unique identifier for the order. Returns ------- order : Order The order object.
[ "Lookup", "an", "order", "based", "on", "the", "order", "id", "returned", "from", "one", "of", "the", "order", "functions", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1932-L1947
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.cancel_order
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 ...
python
def cancel_order(self, order_param): """Cancel an open order. Parameters ---------- order_param : str or Order The order_id or order object to cancel. """ order_id = order_param if isinstance(order_param, zipline.protocol.Order): order_id ...
[ "def", "cancel_order", "(", "self", ",", "order_param", ")", ":", "order_id", "=", "order_param", "if", "isinstance", "(", "order_param", ",", "zipline", ".", "protocol", ".", "Order", ")", ":", "order_id", "=", "order_param", ".", "id", "self", ".", "blot...
Cancel an open order. Parameters ---------- order_param : str or Order The order_id or order object to cancel.
[ "Cancel", "an", "open", "order", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1950-L1962
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.history
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 ) ...
python
def history(self, bar_count, frequency, field, ffill=True): """DEPRECATED: use ``data.history`` instead. """ warnings.warn( "The `history` method is deprecated. Use `data.history` instead.", category=ZiplineDeprecationWarning, stacklevel=4 ) ...
[ "def", "history", "(", "self", ",", "bar_count", ",", "frequency", ",", "field", ",", "ffill", "=", "True", ")", ":", "warnings", ".", "warn", "(", "\"The `history` method is deprecated. Use `data.history` instead.\"", ",", "category", "=", "ZiplineDeprecationWarning...
DEPRECATED: use ``data.history`` instead.
[ "DEPRECATED", ":", "use", "data", ".", "history", "instead", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L1966-L1981
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.register_account_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)
python
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", ")", ":", "if", "self", ".", "initialized", ":", "raise", "RegisterAccountControlPostInit", "(", ")", "self", ".", "account_controls", ".", "append", "(", "control", ")" ]
Register a new AccountControl to be checked on each bar.
[ "Register", "a", "new", "AccountControl", "to", "be", "checked", "on", "each", "bar", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L2028-L2034
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.set_min_leverage
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 ...
python
def set_min_leverage(self, min_leverage, grace_period): """Set a limit on the minimum leverage of the algorithm. Parameters ---------- min_leverage : float The minimum leverage for the algorithm. grace_period : pd.Timedelta The offset from the start date ...
[ "def", "set_min_leverage", "(", "self", ",", "min_leverage", ",", "grace_period", ")", ":", "deadline", "=", "self", ".", "sim_params", ".", "start_session", "+", "grace_period", "control", "=", "MinLeverage", "(", "min_leverage", ",", "deadline", ")", "self", ...
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.
[ "Set", "a", "limit", "on", "the", "minimum", "leverage", "of", "the", "algorithm", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L2057-L2069
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.register_trading_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)
python
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", ")", ":", "if", "self", ".", "initialized", ":", "raise", "RegisterTradingControlPostInit", "(", ")", "self", ".", "trading_controls", ".", "append", "(", "control", ")" ]
Register a new TradingControl to be checked prior to order calls.
[ "Register", "a", "new", "TradingControl", "to", "be", "checked", "prior", "to", "order", "calls", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L2075-L2081
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.set_max_position_size
def set_max_position_size(self, asset=None, max_shares=None, max_notional=None, on_error='fail'): """Set a limit on the number of shares and/or dollar value held for the given sid. Lim...
python
def set_max_position_size(self, asset=None, max_shares=None, max_notional=None, on_error='fail'): """Set a limit on the number of shares and/or dollar value held for the given sid. Lim...
[ "def", "set_max_position_size", "(", "self", ",", "asset", "=", "None", ",", "max_shares", "=", "None", ",", "max_notional", "=", "None", ",", "on_error", "=", "'fail'", ")", ":", "control", "=", "MaxPositionSize", "(", "asset", "=", "asset", ",", "max_sha...
Set a limit on the number of shares and/or dollar value held for the given sid. Limits are treated as absolute values and are enforced at the time that the algo attempts to place an order for sid. This means that it's possible to end up with more than the max number of shares due to spli...
[ "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", "...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L2084-L2114
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.set_max_order_size
def set_max_order_size(self, asset=None, max_shares=None, max_notional=None, on_error='fail'): """Set a limit on the number of shares and/or dollar value of any single order placed for sid. Limit...
python
def set_max_order_size(self, asset=None, max_shares=None, max_notional=None, on_error='fail'): """Set a limit on the number of shares and/or dollar value of any single order placed for sid. Limit...
[ "def", "set_max_order_size", "(", "self", ",", "asset", "=", "None", ",", "max_shares", "=", "None", ",", "max_notional", "=", "None", ",", "on_error", "=", "'fail'", ")", ":", "control", "=", "MaxOrderSize", "(", "asset", "=", "asset", ",", "max_shares", ...
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...
[ "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", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L2117-L2143
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.set_max_order_count
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 ...
python
def set_max_order_count(self, max_count, on_error='fail'): """Set a limit on the number of orders that can be placed in a single day. Parameters ---------- max_count : int The maximum number of orders that can be placed on any single day. """ control ...
[ "def", "set_max_order_count", "(", "self", ",", "max_count", ",", "on_error", "=", "'fail'", ")", ":", "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. Parameters ---------- max_count : int The maximum number of orders that can be placed on any single day.
[ "Set", "a", "limit", "on", "the", "number", "of", "orders", "that", "can", "be", "placed", "in", "a", "single", "day", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L2146-L2156
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.set_asset_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 -------- zipl...
python
def set_asset_restrictions(self, restrictions, on_error='fail'): """Set a restriction on which assets can be ordered. Parameters ---------- restricted_list : Restrictions An object providing information about restricted assets. See Also -------- zipl...
[ "def", "set_asset_restrictions", "(", "self", ",", "restrictions", ",", "on_error", "=", "'fail'", ")", ":", "control", "=", "RestrictedListOrder", "(", "on_error", ",", "restrictions", ")", "self", ".", "register_trading_control", "(", "control", ")", "self", "...
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
[ "Set", "a", "restriction", "on", "which", "assets", "can", "be", "ordered", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L2195-L2209
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.attach_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. chunk...
python
def attach_pipeline(self, pipeline, name, chunks=None, eager=True): """Register a pipeline to be computed at the start of each day. Parameters ---------- pipeline : Pipeline The pipeline to have computed. name : str The name of the pipeline. chunk...
[ "def", "attach_pipeline", "(", "self", ",", "pipeline", ",", "name", ",", "chunks", "=", "None", ",", "eager", "=", "True", ")", ":", "if", "chunks", "is", "None", ":", "# Make the first chunk smaller to get more immediate results:", "# (one week, then every half year...
Register a pipeline to be computed at the start of each day. Parameters ---------- pipeline : Pipeline The pipeline to have computed. name : str The name of the pipeline. chunks : int or iterator, optional The number of days to compute pipelin...
[ "Register", "a", "pipeline", "to", "be", "computed", "at", "the", "start", "of", "each", "day", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L2228-L2270
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.pipeline_output
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 ...
python
def pipeline_output(self, name): """Get the results of the pipeline that was attached with the name: ``name``. Parameters ---------- name : str Name of the pipeline for which results are requested. Returns ------- results : pd.DataFrame ...
[ "def", "pipeline_output", "(", "self", ",", "name", ")", ":", "try", ":", "pipe", ",", "chunks", ",", "_", "=", "self", ".", "_pipelines", "[", "name", "]", "except", "KeyError", ":", "raise", "NoSuchPipeline", "(", "name", "=", "name", ",", "valid", ...
Get the results of the pipeline that was attached with the name: ``name``. Parameters ---------- name : str Name of the pipeline for which results are requested. Returns ------- results : pd.DataFrame DataFrame containing the results of t...
[ "Get", "the", "results", "of", "the", "pipeline", "that", "was", "attached", "with", "the", "name", ":", "name", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L2274-L2306
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm._pipeline_output
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. ...
python
def _pipeline_output(self, pipeline, chunks, name): """ Internal implementation of `pipeline_output`. """ today = normalize_date(self.get_datetime()) try: data = self._pipeline_cache.get(name, today) except KeyError: # Calculate the next block. ...
[ "def", "_pipeline_output", "(", "self", ",", "pipeline", ",", "chunks", ",", "name", ")", ":", "today", "=", "normalize_date", "(", "self", ".", "get_datetime", "(", ")", ")", "try", ":", "data", "=", "self", ".", "_pipeline_cache", ".", "get", "(", "n...
Internal implementation of `pipeline_output`.
[ "Internal", "implementation", "of", "pipeline_output", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L2308-L2328
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.run_pipeline
def run_pipeline(self, pipeline, start_session, chunksize): """ Compute `pipeline`, providing values for at least `start_date`. Produces a DataFrame containing data for days between `start_date` and `end_date`, where `end_date` is defined by: `end_date = min(start_date + ch...
python
def run_pipeline(self, pipeline, start_session, chunksize): """ Compute `pipeline`, providing values for at least `start_date`. Produces a DataFrame containing data for days between `start_date` and `end_date`, where `end_date` is defined by: `end_date = min(start_date + ch...
[ "def", "run_pipeline", "(", "self", ",", "pipeline", ",", "start_session", ",", "chunksize", ")", ":", "sessions", "=", "self", ".", "trading_calendar", ".", "all_sessions", "# Load data starting from the previous trading day...", "start_date_loc", "=", "sessions", ".",...
Compute `pipeline`, providing values for at least `start_date`. Produces a DataFrame containing data for days between `start_date` and `end_date`, where `end_date` is defined by: `end_date = min(start_date + chunksize trading days, simulation_end)` Retu...
[ "Compute", "pipeline", "providing", "values", "for", "at", "least", "start_date", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L2330-L2366
train
quantopian/zipline
zipline/algorithm.py
TradingAlgorithm.all_api_methods
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) ]
python
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", "[", "fn", "for", "fn", "in", "itervalues", "(", "vars", "(", "cls", ")", ")", "if", "getattr", "(", "fn", ",", "'is_api_method'", ",", "False", ")", "]" ]
Return a list of all the TradingAlgorithm API methods.
[ "Return", "a", "list", "of", "all", "the", "TradingAlgorithm", "API", "methods", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/algorithm.py#L2394-L2401
train
quantopian/zipline
zipline/utils/string_formatting.py
bulleted_list
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 = (" ...
python
def bulleted_list(items, max_count=None, indent=2): """Format a bulleted list of values. """ if max_count is not None and len(items) > max_count: item_list = list(items) items = item_list[:max_count - 1] items.append('...') items.append(item_list[-1]) line_template = (" ...
[ "def", "bulleted_list", "(", "items", ",", "max_count", "=", "None", ",", "indent", "=", "2", ")", ":", "if", "max_count", "is", "not", "None", "and", "len", "(", "items", ")", ">", "max_count", ":", "item_list", "=", "list", "(", "items", ")", "item...
Format a bulleted list of values.
[ "Format", "a", "bulleted", "list", "of", "values", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/string_formatting.py#L1-L11
train
quantopian/zipline
zipline/utils/argcheck.py
_expect_extra
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) ...
python
def _expect_extra(expected, present, exc_unexpected, exc_missing, exc_args): """ Checks for the presence of an extra to the argument list. Raises expections if this is unexpected or if it is missing and expected. """ if present: if not expected: raise exc_unexpected(*exc_args) ...
[ "def", "_expect_extra", "(", "expected", ",", "present", ",", "exc_unexpected", ",", "exc_missing", ",", "exc_args", ")", ":", "if", "present", ":", "if", "not", "expected", ":", "raise", "exc_unexpected", "(", "*", "exc_args", ")", "elif", "expected", "and"...
Checks for the presence of an extra to the argument list. Raises expections if this is unexpected or if it is missing and expected.
[ "Checks", "for", "the", "presence", "of", "an", "extra", "to", "the", "argument", "list", ".", "Raises", "expections", "if", "this", "is", "unexpected", "or", "if", "it", "is", "missing", "and", "expected", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/argcheck.py#L131-L140
train
quantopian/zipline
zipline/utils/argcheck.py
verify_callable_argspec
def verify_callable_argspec(callable_, expected_args=Argument.ignore, expect_starargs=Argument.ignore, expect_kwargs=Argument.ignore): """ Checks the callable_ to make sure that it satisfies the given expectations. expec...
python
def verify_callable_argspec(callable_, expected_args=Argument.ignore, expect_starargs=Argument.ignore, expect_kwargs=Argument.ignore): """ Checks the callable_ to make sure that it satisfies the given expectations. expec...
[ "def", "verify_callable_argspec", "(", "callable_", ",", "expected_args", "=", "Argument", ".", "ignore", ",", "expect_starargs", "=", "Argument", ".", "ignore", ",", "expect_kwargs", "=", "Argument", ".", "ignore", ")", ":", "if", "not", "callable", "(", "cal...
Checks the callable_ to make sure that it satisfies the given expectations. expected_args should be an iterable of Arguments in the order you expect to receive them. expect_starargs means that the function should or should not take a *args param. expect_kwargs says the callable should or should not ...
[ "Checks", "the", "callable_", "to", "make", "sure", "that", "it", "satisfies", "the", "given", "expectations", ".", "expected_args", "should", "be", "an", "iterable", "of", "Arguments", "in", "the", "order", "you", "expect", "to", "receive", "them", ".", "ex...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/argcheck.py#L143-L222
train
quantopian/zipline
zipline/utils/argcheck.py
Argument.parse_argspec
def parse_argspec(callable_): """ Takes a callable and returns a tuple with the list of Argument objects, the name of *args, and the name of **kwargs. If *args or **kwargs is not present, it will be None. This returns a namedtuple called Argspec that has three fields named: ...
python
def parse_argspec(callable_): """ Takes a callable and returns a tuple with the list of Argument objects, the name of *args, and the name of **kwargs. If *args or **kwargs is not present, it will be None. This returns a namedtuple called Argspec that has three fields named: ...
[ "def", "parse_argspec", "(", "callable_", ")", ":", "args", ",", "varargs", ",", "keywords", ",", "defaults", "=", "getargspec", "(", "callable_", ")", "defaults", "=", "list", "(", "defaults", "or", "[", "]", ")", "if", "getattr", "(", "callable_", ",",...
Takes a callable and returns a tuple with the list of Argument objects, the name of *args, and the name of **kwargs. If *args or **kwargs is not present, it will be None. This returns a namedtuple called Argspec that has three fields named: args, starargs, and kwargs.
[ "Takes", "a", "callable", "and", "returns", "a", "tuple", "with", "the", "list", "of", "Argument", "objects", "the", "name", "of", "*", "args", "and", "the", "name", "of", "**", "kwargs", ".", "If", "*", "args", "or", "**", "kwargs", "is", "not", "pr...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/argcheck.py#L98-L120
train
quantopian/zipline
zipline/finance/asset_restrictions.py
StaticRestrictions.is_restricted
def is_restricted(self, assets, dt): """ An asset is restricted for all dts if it is in the static list. """ if isinstance(assets, Asset): return assets in self._restricted_set return pd.Series( index=pd.Index(assets), data=vectorized_is_elemen...
python
def is_restricted(self, assets, dt): """ An asset is restricted for all dts if it is in the static list. """ if isinstance(assets, Asset): return assets in self._restricted_set return pd.Series( index=pd.Index(assets), data=vectorized_is_elemen...
[ "def", "is_restricted", "(", "self", ",", "assets", ",", "dt", ")", ":", "if", "isinstance", "(", "assets", ",", "Asset", ")", ":", "return", "assets", "in", "self", ".", "_restricted_set", "return", "pd", ".", "Series", "(", "index", "=", "pd", ".", ...
An asset is restricted for all dts if it is in the static list.
[ "An", "asset", "is", "restricted", "for", "all", "dts", "if", "it", "is", "in", "the", "static", "list", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/asset_restrictions.py#L143-L152
train
quantopian/zipline
zipline/finance/asset_restrictions.py
HistoricalRestrictions.is_restricted
def is_restricted(self, assets, dt): """ Returns whether or not an asset or iterable of assets is restricted on a dt. """ if isinstance(assets, Asset): return self._is_restricted_for_asset(assets, dt) is_restricted = partial(self._is_restricted_for_asset, dt=...
python
def is_restricted(self, assets, dt): """ Returns whether or not an asset or iterable of assets is restricted on a dt. """ if isinstance(assets, Asset): return self._is_restricted_for_asset(assets, dt) is_restricted = partial(self._is_restricted_for_asset, dt=...
[ "def", "is_restricted", "(", "self", ",", "assets", ",", "dt", ")", ":", "if", "isinstance", "(", "assets", ",", "Asset", ")", ":", "return", "self", ".", "_is_restricted_for_asset", "(", "assets", ",", "dt", ")", "is_restricted", "=", "partial", "(", "s...
Returns whether or not an asset or iterable of assets is restricted on a dt.
[ "Returns", "whether", "or", "not", "an", "asset", "or", "iterable", "of", "assets", "is", "restricted", "on", "a", "dt", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/asset_restrictions.py#L177-L189
train
quantopian/zipline
zipline/finance/ledger.py
PositionTracker.handle_splits
def handle_splits(self, splits): """Processes a list of splits by modifying any positions as needed. Parameters ---------- splits: list A list of splits. Each split is a tuple of (asset, ratio). Returns ------- int: The leftover cash from fractional...
python
def handle_splits(self, splits): """Processes a list of splits by modifying any positions as needed. Parameters ---------- splits: list A list of splits. Each split is a tuple of (asset, ratio). Returns ------- int: The leftover cash from fractional...
[ "def", "handle_splits", "(", "self", ",", "splits", ")", ":", "total_leftover_cash", "=", "0", "for", "asset", ",", "ratio", "in", "splits", ":", "if", "asset", "in", "self", ".", "positions", ":", "self", ".", "_dirty_stats", "=", "True", "# Make the posi...
Processes a list of splits by modifying any positions as needed. Parameters ---------- splits: list A list of splits. Each split is a tuple of (asset, ratio). Returns ------- int: The leftover cash from fractional shares after modifying each pos...
[ "Processes", "a", "list", "of", "splits", "by", "modifying", "any", "positions", "as", "needed", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/ledger.py#L114-L139
train
quantopian/zipline
zipline/finance/ledger.py
PositionTracker.earn_dividends
def earn_dividends(self, cash_dividends, stock_dividends): """Given a list of dividends whose ex_dates are all the next trading day, calculate and store the cash and/or stock payments to be paid on each dividend's pay date. Parameters ---------- cash_dividends : iterable...
python
def earn_dividends(self, cash_dividends, stock_dividends): """Given a list of dividends whose ex_dates are all the next trading day, calculate and store the cash and/or stock payments to be paid on each dividend's pay date. Parameters ---------- cash_dividends : iterable...
[ "def", "earn_dividends", "(", "self", ",", "cash_dividends", ",", "stock_dividends", ")", ":", "for", "cash_dividend", "in", "cash_dividends", ":", "self", ".", "_dirty_stats", "=", "True", "# only mark dirty if we pay a dividend", "# Store the earned dividends so that they...
Given a list of dividends whose ex_dates are all the next trading day, calculate and store the cash and/or stock payments to be paid on each dividend's pay date. Parameters ---------- cash_dividends : iterable of (asset, amount, pay_date) namedtuples stock_dividends: it...
[ "Given", "a", "list", "of", "dividends", "whose", "ex_dates", "are", "all", "the", "next", "trading", "day", "calculate", "and", "store", "the", "cash", "and", "/", "or", "stock", "payments", "to", "be", "paid", "on", "each", "dividend", "s", "pay", "dat...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/ledger.py#L141-L179
train
quantopian/zipline
zipline/finance/ledger.py
PositionTracker.pay_dividends
def pay_dividends(self, next_trading_day): """ Returns a cash payment based on the dividends that should be paid out according to the accumulated bookkeeping of earned, unpaid, and stock dividends. """ net_cash_payment = 0.0 try: payments = self._unpa...
python
def pay_dividends(self, next_trading_day): """ Returns a cash payment based on the dividends that should be paid out according to the accumulated bookkeeping of earned, unpaid, and stock dividends. """ net_cash_payment = 0.0 try: payments = self._unpa...
[ "def", "pay_dividends", "(", "self", ",", "next_trading_day", ")", ":", "net_cash_payment", "=", "0.0", "try", ":", "payments", "=", "self", ".", "_unpaid_dividends", "[", "next_trading_day", "]", "# Mark these dividends as paid by dropping them from our unpaid", "del", ...
Returns a cash payment based on the dividends that should be paid out according to the accumulated bookkeeping of earned, unpaid, and stock dividends.
[ "Returns", "a", "cash", "payment", "based", "on", "the", "dividends", "that", "should", "be", "paid", "out", "according", "to", "the", "accumulated", "bookkeeping", "of", "earned", "unpaid", "and", "stock", "dividends", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/ledger.py#L181-L222
train
quantopian/zipline
zipline/finance/ledger.py
PositionTracker.stats
def stats(self): """The current status of the positions. Returns ------- stats : PositionStats The current stats position stats. Notes ----- This is cached, repeated access will not recompute the stats until the stats may have changed. ...
python
def stats(self): """The current status of the positions. Returns ------- stats : PositionStats The current stats position stats. Notes ----- This is cached, repeated access will not recompute the stats until the stats may have changed. ...
[ "def", "stats", "(", "self", ")", ":", "if", "self", ".", "_dirty_stats", ":", "calculate_position_tracker_stats", "(", "self", ".", "positions", ",", "self", ".", "_stats", ")", "self", ".", "_dirty_stats", "=", "False", "return", "self", ".", "_stats" ]
The current status of the positions. Returns ------- stats : PositionStats The current stats position stats. Notes ----- This is cached, repeated access will not recompute the stats until the stats may have changed.
[ "The", "current", "status", "of", "the", "positions", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/ledger.py#L288-L305
train
quantopian/zipline
zipline/finance/ledger.py
Ledger.process_transaction
def process_transaction(self, transaction): """Add a transaction to ledger, updating the current state as needed. Parameters ---------- transaction : zp.Transaction The transaction to execute. """ asset = transaction.asset if isinstance(asset, Future)...
python
def process_transaction(self, transaction): """Add a transaction to ledger, updating the current state as needed. Parameters ---------- transaction : zp.Transaction The transaction to execute. """ asset = transaction.asset if isinstance(asset, Future)...
[ "def", "process_transaction", "(", "self", ",", "transaction", ")", ":", "asset", "=", "transaction", ".", "asset", "if", "isinstance", "(", "asset", ",", "Future", ")", ":", "try", ":", "old_price", "=", "self", ".", "_payout_last_sale_prices", "[", "asset"...
Add a transaction to ledger, updating the current state as needed. Parameters ---------- transaction : zp.Transaction The transaction to execute.
[ "Add", "a", "transaction", "to", "ledger", "updating", "the", "current", "state", "as", "needed", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/ledger.py#L479-L523
train
quantopian/zipline
zipline/finance/ledger.py
Ledger.process_splits
def process_splits(self, splits): """Processes a list of splits by modifying any positions as needed. Parameters ---------- splits: list[(Asset, float)] A list of splits. Each split is a tuple of (asset, ratio). """ leftover_cash = self.position_tracker.handl...
python
def process_splits(self, splits): """Processes a list of splits by modifying any positions as needed. Parameters ---------- splits: list[(Asset, float)] A list of splits. Each split is a tuple of (asset, ratio). """ leftover_cash = self.position_tracker.handl...
[ "def", "process_splits", "(", "self", ",", "splits", ")", ":", "leftover_cash", "=", "self", ".", "position_tracker", ".", "handle_splits", "(", "splits", ")", "if", "leftover_cash", ">", "0", ":", "self", ".", "_cash_flow", "(", "leftover_cash", ")" ]
Processes a list of splits by modifying any positions as needed. Parameters ---------- splits: list[(Asset, float)] A list of splits. Each split is a tuple of (asset, ratio).
[ "Processes", "a", "list", "of", "splits", "by", "modifying", "any", "positions", "as", "needed", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/ledger.py#L525-L535
train
quantopian/zipline
zipline/finance/ledger.py
Ledger.process_order
def process_order(self, order): """Keep track of an order that was placed. Parameters ---------- order : zp.Order The order to record. """ try: dt_orders = self._orders_by_modified[order.dt] except KeyError: self._orders_by_mod...
python
def process_order(self, order): """Keep track of an order that was placed. Parameters ---------- order : zp.Order The order to record. """ try: dt_orders = self._orders_by_modified[order.dt] except KeyError: self._orders_by_mod...
[ "def", "process_order", "(", "self", ",", "order", ")", ":", "try", ":", "dt_orders", "=", "self", ".", "_orders_by_modified", "[", "order", ".", "dt", "]", "except", "KeyError", ":", "self", ".", "_orders_by_modified", "[", "order", ".", "dt", "]", "=",...
Keep track of an order that was placed. Parameters ---------- order : zp.Order The order to record.
[ "Keep", "track", "of", "an", "order", "that", "was", "placed", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/ledger.py#L537-L557
train
quantopian/zipline
zipline/finance/ledger.py
Ledger.process_commission
def process_commission(self, commission): """Process the commission. Parameters ---------- commission : zp.Event The commission being paid. """ asset = commission['asset'] cost = commission['cost'] self.position_tracker.handle_commission(asse...
python
def process_commission(self, commission): """Process the commission. Parameters ---------- commission : zp.Event The commission being paid. """ asset = commission['asset'] cost = commission['cost'] self.position_tracker.handle_commission(asse...
[ "def", "process_commission", "(", "self", ",", "commission", ")", ":", "asset", "=", "commission", "[", "'asset'", "]", "cost", "=", "commission", "[", "'cost'", "]", "self", ".", "position_tracker", ".", "handle_commission", "(", "asset", ",", "cost", ")", ...
Process the commission. Parameters ---------- commission : zp.Event The commission being paid.
[ "Process", "the", "commission", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/ledger.py#L559-L571
train
quantopian/zipline
zipline/finance/ledger.py
Ledger.process_dividends
def process_dividends(self, next_session, asset_finder, adjustment_reader): """Process dividends for the next session. This will earn us any dividends whose ex-date is the next session as well as paying out any dividends whose pay-date is the next session """ position_tracker = ...
python
def process_dividends(self, next_session, asset_finder, adjustment_reader): """Process dividends for the next session. This will earn us any dividends whose ex-date is the next session as well as paying out any dividends whose pay-date is the next session """ position_tracker = ...
[ "def", "process_dividends", "(", "self", ",", "next_session", ",", "asset_finder", ",", "adjustment_reader", ")", ":", "position_tracker", "=", "self", ".", "position_tracker", "# Earn dividends whose ex_date is the next trading day. We need to", "# check if we own any of these s...
Process dividends for the next session. This will earn us any dividends whose ex-date is the next session as well as paying out any dividends whose pay-date is the next session
[ "Process", "dividends", "for", "the", "next", "session", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/ledger.py#L582-L621
train
quantopian/zipline
zipline/finance/ledger.py
Ledger.transactions
def transactions(self, dt=None): """Retrieve the dict-form of all of the transactions in a given bar or for the whole simulation. Parameters ---------- dt : pd.Timestamp or None, optional The particular datetime to look up transactions for. If not passed, ...
python
def transactions(self, dt=None): """Retrieve the dict-form of all of the transactions in a given bar or for the whole simulation. Parameters ---------- dt : pd.Timestamp or None, optional The particular datetime to look up transactions for. If not passed, ...
[ "def", "transactions", "(", "self", ",", "dt", "=", "None", ")", ":", "if", "dt", "is", "None", ":", "# flatten the by-day transactions", "return", "[", "txn", "for", "by_day", "in", "itervalues", "(", "self", ".", "_processed_transactions", ")", "for", "txn...
Retrieve the dict-form of all of the transactions in a given bar or for the whole simulation. Parameters ---------- dt : pd.Timestamp or None, optional The particular datetime to look up transactions for. If not passed, or None is explicitly passed, all of the tr...
[ "Retrieve", "the", "dict", "-", "form", "of", "all", "of", "the", "transactions", "in", "a", "given", "bar", "or", "for", "the", "whole", "simulation", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/ledger.py#L631-L655
train
quantopian/zipline
zipline/finance/ledger.py
Ledger.orders
def orders(self, dt=None): """Retrieve the dict-form of all of the orders in a given bar or for the whole simulation. Parameters ---------- dt : pd.Timestamp or None, optional The particular datetime to look up order for. If not passed, or None is explici...
python
def orders(self, dt=None): """Retrieve the dict-form of all of the orders in a given bar or for the whole simulation. Parameters ---------- dt : pd.Timestamp or None, optional The particular datetime to look up order for. If not passed, or None is explici...
[ "def", "orders", "(", "self", ",", "dt", "=", "None", ")", ":", "if", "dt", "is", "None", ":", "# orders by id is already flattened", "return", "[", "o", ".", "to_dict", "(", ")", "for", "o", "in", "itervalues", "(", "self", ".", "_orders_by_id", ")", ...
Retrieve the dict-form of all of the orders in a given bar or for the whole simulation. Parameters ---------- dt : pd.Timestamp or None, optional The particular datetime to look up order for. If not passed, or None is explicitly passed, all of the orders will be ...
[ "Retrieve", "the", "dict", "-", "form", "of", "all", "of", "the", "orders", "in", "a", "given", "bar", "or", "for", "the", "whole", "simulation", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/ledger.py#L657-L679
train
quantopian/zipline
zipline/finance/ledger.py
Ledger.update_portfolio
def update_portfolio(self): """Force a computation of the current portfolio state. """ if not self._dirty_portfolio: return portfolio = self._portfolio pt = self.position_tracker portfolio.positions = pt.get_positions() position_stats = pt.stats ...
python
def update_portfolio(self): """Force a computation of the current portfolio state. """ if not self._dirty_portfolio: return portfolio = self._portfolio pt = self.position_tracker portfolio.positions = pt.get_positions() position_stats = pt.stats ...
[ "def", "update_portfolio", "(", "self", ")", ":", "if", "not", "self", ".", "_dirty_portfolio", ":", "return", "portfolio", "=", "self", ".", "_portfolio", "pt", "=", "self", ".", "position_tracker", "portfolio", ".", "positions", "=", "pt", ".", "get_positi...
Force a computation of the current portfolio state.
[ "Force", "a", "computation", "of", "the", "current", "portfolio", "state", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/ledger.py#L703-L740
train
quantopian/zipline
zipline/finance/ledger.py
Ledger.override_account_fields
def override_account_fields(self, settled_cash=not_overridden, accrued_interest=not_overridden, buying_power=not_overridden, equity_with_loan=not_overridden, to...
python
def override_account_fields(self, settled_cash=not_overridden, accrued_interest=not_overridden, buying_power=not_overridden, equity_with_loan=not_overridden, to...
[ "def", "override_account_fields", "(", "self", ",", "settled_cash", "=", "not_overridden", ",", "accrued_interest", "=", "not_overridden", ",", "buying_power", "=", "not_overridden", ",", "equity_with_loan", "=", "not_overridden", ",", "total_positions_value", "=", "not...
Override fields on ``self.account``.
[ "Override", "fields", "on", "self", ".", "account", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/ledger.py#L766-L791
train
quantopian/zipline
zipline/pipeline/loaders/blaze/core.py
datashape_type_to_numpy
def datashape_type_to_numpy(type_): """ Given a datashape type, return the associated numpy type. Maps datashape's DateTime type to numpy's `datetime64[ns]` dtype, since the numpy datetime returned by datashape isn't supported by pipeline. Parameters ---------- type_: datashape.coretypes.Ty...
python
def datashape_type_to_numpy(type_): """ Given a datashape type, return the associated numpy type. Maps datashape's DateTime type to numpy's `datetime64[ns]` dtype, since the numpy datetime returned by datashape isn't supported by pipeline. Parameters ---------- type_: datashape.coretypes.Ty...
[ "def", "datashape_type_to_numpy", "(", "type_", ")", ":", "if", "isinstance", "(", "type_", ",", "Option", ")", ":", "type_", "=", "type_", ".", "ty", "if", "isinstance", "(", "type_", ",", "DateTime", ")", ":", "return", "np", ".", "dtype", "(", "'dat...
Given a datashape type, return the associated numpy type. Maps datashape's DateTime type to numpy's `datetime64[ns]` dtype, since the numpy datetime returned by datashape isn't supported by pipeline. Parameters ---------- type_: datashape.coretypes.Type The datashape type. Returns ...
[ "Given", "a", "datashape", "type", "return", "the", "associated", "numpy", "type", ".", "Maps", "datashape", "s", "DateTime", "type", "to", "numpy", "s", "datetime64", "[", "ns", "]", "dtype", "since", "the", "numpy", "datetime", "returned", "by", "datashape...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/blaze/core.py#L246-L272
train
quantopian/zipline
zipline/pipeline/loaders/blaze/core.py
new_dataset
def new_dataset(expr, missing_values, domain): """ Creates or returns a dataset from a blaze expression. Parameters ---------- expr : Expr The blaze expression representing the values. missing_values : frozenset((name, value) pairs Association pairs column name and missing_value...
python
def new_dataset(expr, missing_values, domain): """ Creates or returns a dataset from a blaze expression. Parameters ---------- expr : Expr The blaze expression representing the values. missing_values : frozenset((name, value) pairs Association pairs column name and missing_value...
[ "def", "new_dataset", "(", "expr", ",", "missing_values", ",", "domain", ")", ":", "missing_values", "=", "dict", "(", "missing_values", ")", "class_dict", "=", "{", "'ndim'", ":", "2", "if", "SID_FIELD_NAME", "in", "expr", ".", "fields", "else", "1", "}",...
Creates or returns a dataset from a blaze expression. Parameters ---------- expr : Expr The blaze expression representing the values. missing_values : frozenset((name, value) pairs Association pairs column name and missing_value for that column. This needs to be a frozenset rat...
[ "Creates", "or", "returns", "a", "dataset", "from", "a", "blaze", "expression", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/blaze/core.py#L276-L334
train
quantopian/zipline
zipline/pipeline/loaders/blaze/core.py
_check_resources
def _check_resources(name, expr, resources): """Validate that the expression and resources passed match up. Parameters ---------- name : str The name of the argument we are checking. expr : Expr The potentially bound expr. resources The explicitly passed resources to com...
python
def _check_resources(name, expr, resources): """Validate that the expression and resources passed match up. Parameters ---------- name : str The name of the argument we are checking. expr : Expr The potentially bound expr. resources The explicitly passed resources to com...
[ "def", "_check_resources", "(", "name", ",", "expr", ",", "resources", ")", ":", "if", "expr", "is", "None", ":", "return", "bound", "=", "expr", ".", "_resources", "(", ")", "if", "not", "bound", "and", "resources", "is", "None", ":", "raise", "ValueE...
Validate that the expression and resources passed match up. Parameters ---------- name : str The name of the argument we are checking. expr : Expr The potentially bound expr. resources The explicitly passed resources to compute expr. Raises ------ ValueError ...
[ "Validate", "that", "the", "expression", "and", "resources", "passed", "match", "up", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/blaze/core.py#L337-L362
train
quantopian/zipline
zipline/pipeline/loaders/blaze/core.py
_check_datetime_field
def _check_datetime_field(name, measure): """Check that a field is a datetime inside some measure. Parameters ---------- name : str The name of the field to check. measure : Record The record to check the field of. Raises ------ TypeError If the field is not a d...
python
def _check_datetime_field(name, measure): """Check that a field is a datetime inside some measure. Parameters ---------- name : str The name of the field to check. measure : Record The record to check the field of. Raises ------ TypeError If the field is not a d...
[ "def", "_check_datetime_field", "(", "name", ",", "measure", ")", ":", "if", "not", "isinstance", "(", "measure", "[", "name", "]", ",", "(", "Date", ",", "DateTime", ")", ")", ":", "raise", "TypeError", "(", "\"'{name}' field must be a '{dt}', not: '{dshape}'\"...
Check that a field is a datetime inside some measure. Parameters ---------- name : str The name of the field to check. measure : Record The record to check the field of. Raises ------ TypeError If the field is not a datetime inside ``measure``.
[ "Check", "that", "a", "field", "is", "a", "datetime", "inside", "some", "measure", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/blaze/core.py#L365-L387
train
quantopian/zipline
zipline/pipeline/loaders/blaze/core.py
_get_metadata
def _get_metadata(field, expr, metadata_expr, no_metadata_rule): """Find the correct metadata expression for the expression. Parameters ---------- field : {'deltas', 'checkpoints'} The kind of metadata expr to lookup. expr : Expr The baseline expression. metadata_expr : Expr, 'a...
python
def _get_metadata(field, expr, metadata_expr, no_metadata_rule): """Find the correct metadata expression for the expression. Parameters ---------- field : {'deltas', 'checkpoints'} The kind of metadata expr to lookup. expr : Expr The baseline expression. metadata_expr : Expr, 'a...
[ "def", "_get_metadata", "(", "field", ",", "expr", ",", "metadata_expr", ",", "no_metadata_rule", ")", ":", "if", "isinstance", "(", "metadata_expr", ",", "bz", ".", "Expr", ")", "or", "metadata_expr", "is", "None", ":", "return", "metadata_expr", "try", ":"...
Find the correct metadata expression for the expression. Parameters ---------- field : {'deltas', 'checkpoints'} The kind of metadata expr to lookup. expr : Expr The baseline expression. metadata_expr : Expr, 'auto', or None The metadata argument. If this is 'auto', then the...
[ "Find", "the", "correct", "metadata", "expression", "for", "the", "expression", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/blaze/core.py#L415-L450
train
quantopian/zipline
zipline/pipeline/loaders/blaze/core.py
_ensure_timestamp_field
def _ensure_timestamp_field(dataset_expr, deltas, checkpoints): """Verify that the baseline and deltas expressions have a timestamp field. If there is not a ``TS_FIELD_NAME`` on either of the expressions, it will be copied from the ``AD_FIELD_NAME``. If one is provided, then we will verify that it is t...
python
def _ensure_timestamp_field(dataset_expr, deltas, checkpoints): """Verify that the baseline and deltas expressions have a timestamp field. If there is not a ``TS_FIELD_NAME`` on either of the expressions, it will be copied from the ``AD_FIELD_NAME``. If one is provided, then we will verify that it is t...
[ "def", "_ensure_timestamp_field", "(", "dataset_expr", ",", "deltas", ",", "checkpoints", ")", ":", "measure", "=", "dataset_expr", ".", "dshape", ".", "measure", "if", "TS_FIELD_NAME", "not", "in", "measure", ".", "names", ":", "dataset_expr", "=", "bz", ".",...
Verify that the baseline and deltas expressions have a timestamp field. If there is not a ``TS_FIELD_NAME`` on either of the expressions, it will be copied from the ``AD_FIELD_NAME``. If one is provided, then we will verify that it is the correct dshape. Parameters ---------- dataset_expr : Ex...
[ "Verify", "that", "the", "baseline", "and", "deltas", "expressions", "have", "a", "timestamp", "field", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/blaze/core.py#L473-L505
train
quantopian/zipline
zipline/pipeline/loaders/blaze/core.py
from_blaze
def from_blaze(expr, deltas='auto', checkpoints='auto', loader=None, resources=None, odo_kwargs=None, missing_values=None, domain=GENERIC, no_deltas_rule='warn', no_checkpoints_rule='wa...
python
def from_blaze(expr, deltas='auto', checkpoints='auto', loader=None, resources=None, odo_kwargs=None, missing_values=None, domain=GENERIC, no_deltas_rule='warn', no_checkpoints_rule='wa...
[ "def", "from_blaze", "(", "expr", ",", "deltas", "=", "'auto'", ",", "checkpoints", "=", "'auto'", ",", "loader", "=", "None", ",", "resources", "=", "None", ",", "odo_kwargs", "=", "None", ",", "missing_values", "=", "None", ",", "domain", "=", "GENERIC...
Create a Pipeline API object from a blaze expression. Parameters ---------- expr : Expr The blaze expression to use. deltas : Expr, 'auto' or None, optional The expression to use for the point in time adjustments. If the string 'auto' is passed, a deltas expr will be looked up ...
[ "Create", "a", "Pipeline", "API", "object", "from", "a", "blaze", "expression", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/blaze/core.py#L512-L695
train
quantopian/zipline
zipline/pipeline/loaders/blaze/core.py
bind_expression_to_resources
def bind_expression_to_resources(expr, resources): """ Bind a Blaze expression to resources. Parameters ---------- expr : bz.Expr The expression to which we want to bind resources. resources : dict[bz.Symbol -> any] Mapping from the loadable terms of ``expr`` to actual data reso...
python
def bind_expression_to_resources(expr, resources): """ Bind a Blaze expression to resources. Parameters ---------- expr : bz.Expr The expression to which we want to bind resources. resources : dict[bz.Symbol -> any] Mapping from the loadable terms of ``expr`` to actual data reso...
[ "def", "bind_expression_to_resources", "(", "expr", ",", "resources", ")", ":", "# bind the resources into the expression", "if", "resources", "is", "None", ":", "resources", "=", "{", "}", "# _subs stands for substitute. It's not actually private, blaze just", "# prefixes sym...
Bind a Blaze expression to resources. Parameters ---------- expr : bz.Expr The expression to which we want to bind resources. resources : dict[bz.Symbol -> any] Mapping from the loadable terms of ``expr`` to actual data resources. Returns ------- bound_expr : bz.Expr ...
[ "Bind", "a", "Blaze", "expression", "to", "resources", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/blaze/core.py#L1038-L1063
train
quantopian/zipline
zipline/pipeline/loaders/blaze/core.py
get_materialized_checkpoints
def get_materialized_checkpoints(checkpoints, colnames, lower_dt, odo_kwargs): """ Computes a lower bound and a DataFrame checkpoints. Parameters ---------- checkpoints : Expr Bound blaze expression for a checkpoints table from which to get a computed lower bound. colnames : ite...
python
def get_materialized_checkpoints(checkpoints, colnames, lower_dt, odo_kwargs): """ Computes a lower bound and a DataFrame checkpoints. Parameters ---------- checkpoints : Expr Bound blaze expression for a checkpoints table from which to get a computed lower bound. colnames : ite...
[ "def", "get_materialized_checkpoints", "(", "checkpoints", ",", "colnames", ",", "lower_dt", ",", "odo_kwargs", ")", ":", "if", "checkpoints", "is", "not", "None", ":", "ts", "=", "checkpoints", "[", "TS_FIELD_NAME", "]", "checkpoints_ts", "=", "odo", "(", "ts...
Computes a lower bound and a DataFrame checkpoints. Parameters ---------- checkpoints : Expr Bound blaze expression for a checkpoints table from which to get a computed lower bound. colnames : iterable of str The names of the columns for which checkpoints should be computed. ...
[ "Computes", "a", "lower", "bound", "and", "a", "DataFrame", "checkpoints", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/blaze/core.py#L1066-L1105
train
quantopian/zipline
zipline/pipeline/loaders/blaze/core.py
ffill_query_in_range
def ffill_query_in_range(expr, lower, upper, checkpoints=None, odo_kwargs=None, ts_field=TS_FIELD_NAME): """Query a blaze expression in a given time range properly forward filling from va...
python
def ffill_query_in_range(expr, lower, upper, checkpoints=None, odo_kwargs=None, ts_field=TS_FIELD_NAME): """Query a blaze expression in a given time range properly forward filling from va...
[ "def", "ffill_query_in_range", "(", "expr", ",", "lower", ",", "upper", ",", "checkpoints", "=", "None", ",", "odo_kwargs", "=", "None", ",", "ts_field", "=", "TS_FIELD_NAME", ")", ":", "odo_kwargs", "=", "odo_kwargs", "or", "{", "}", "computed_lower", ",", ...
Query a blaze expression in a given time range properly forward filling from values that fall before the lower date. Parameters ---------- expr : Expr Bound blaze expression. lower : datetime The lower date to query for. upper : datetime The upper date to query for. ...
[ "Query", "a", "blaze", "expression", "in", "a", "given", "time", "range", "properly", "forward", "filling", "from", "values", "that", "fall", "before", "the", "lower", "date", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/blaze/core.py#L1108-L1165
train
quantopian/zipline
zipline/pipeline/loaders/blaze/core.py
BlazeLoader.register_dataset
def register_dataset(self, dataset, expr, deltas=None, checkpoints=None, odo_kwargs=None): """Explicitly map a datset to a collection of blaze expressions. Parameters ---...
python
def register_dataset(self, dataset, expr, deltas=None, checkpoints=None, odo_kwargs=None): """Explicitly map a datset to a collection of blaze expressions. Parameters ---...
[ "def", "register_dataset", "(", "self", ",", "dataset", ",", "expr", ",", "deltas", "=", "None", ",", "checkpoints", "=", "None", ",", "odo_kwargs", "=", "None", ")", ":", "expr_data", "=", "ExprData", "(", "expr", ",", "deltas", ",", "checkpoints", ",",...
Explicitly map a datset to a collection of blaze expressions. Parameters ---------- dataset : DataSet The pipeline dataset to map to the given expressions. expr : Expr The baseline values. deltas : Expr, optional The deltas for the data. ...
[ "Explicitly", "map", "a", "datset", "to", "a", "collection", "of", "blaze", "expressions", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/blaze/core.py#L847-L879
train
quantopian/zipline
zipline/pipeline/loaders/blaze/core.py
BlazeLoader.register_column
def register_column(self, column, expr, deltas=None, checkpoints=None, odo_kwargs=None): """Explicitly map a single bound column to a collection of blaze expressions. The expressions n...
python
def register_column(self, column, expr, deltas=None, checkpoints=None, odo_kwargs=None): """Explicitly map a single bound column to a collection of blaze expressions. The expressions n...
[ "def", "register_column", "(", "self", ",", "column", ",", "expr", ",", "deltas", "=", "None", ",", "checkpoints", "=", "None", ",", "odo_kwargs", "=", "None", ")", ":", "self", ".", "_table_expressions", "[", "column", "]", "=", "ExprData", "(", "expr",...
Explicitly map a single bound column to a collection of blaze expressions. The expressions need to have ``timestamp`` and ``as_of`` columns. Parameters ---------- column : BoundColumn The pipeline dataset to map to the given expressions. expr : Expr ...
[ "Explicitly", "map", "a", "single", "bound", "column", "to", "a", "collection", "of", "blaze", "expressions", ".", "The", "expressions", "need", "to", "have", "timestamp", "and", "as_of", "columns", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/blaze/core.py#L881-L913
train
quantopian/zipline
zipline/assets/assets.py
merge_ownership_periods
def merge_ownership_periods(mappings): """ Given a dict of mappings where the values are lists of OwnershipPeriod objects, returns a dict with the same structure with new OwnershipPeriod objects adjusted so that the periods have no gaps. Orders the periods chronologically, and pushes forward th...
python
def merge_ownership_periods(mappings): """ Given a dict of mappings where the values are lists of OwnershipPeriod objects, returns a dict with the same structure with new OwnershipPeriod objects adjusted so that the periods have no gaps. Orders the periods chronologically, and pushes forward th...
[ "def", "merge_ownership_periods", "(", "mappings", ")", ":", "return", "valmap", "(", "lambda", "v", ":", "tuple", "(", "OwnershipPeriod", "(", "a", ".", "start", ",", "b", ".", "start", ",", "a", ".", "sid", ",", "a", ".", "value", ",", ")", "for", ...
Given a dict of mappings where the values are lists of OwnershipPeriod objects, returns a dict with the same structure with new OwnershipPeriod objects adjusted so that the periods have no gaps. Orders the periods chronologically, and pushes forward the end date of each period to match the start da...
[ "Given", "a", "dict", "of", "mappings", "where", "the", "values", "are", "lists", "of", "OwnershipPeriod", "objects", "returns", "a", "dict", "with", "the", "same", "structure", "with", "new", "OwnershipPeriod", "objects", "adjusted", "so", "that", "the", "per...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L104-L138
train
quantopian/zipline
zipline/assets/assets.py
build_ownership_map
def build_ownership_map(table, key_from_row, value_from_row): """ Builds a dict mapping to lists of OwnershipPeriods, from a db table. """ return _build_ownership_map_from_rows( sa.select(table.c).execute().fetchall(), key_from_row, value_from_row, )
python
def build_ownership_map(table, key_from_row, value_from_row): """ Builds a dict mapping to lists of OwnershipPeriods, from a db table. """ return _build_ownership_map_from_rows( sa.select(table.c).execute().fetchall(), key_from_row, value_from_row, )
[ "def", "build_ownership_map", "(", "table", ",", "key_from_row", ",", "value_from_row", ")", ":", "return", "_build_ownership_map_from_rows", "(", "sa", ".", "select", "(", "table", ".", "c", ")", ".", "execute", "(", ")", ".", "fetchall", "(", ")", ",", "...
Builds a dict mapping to lists of OwnershipPeriods, from a db table.
[ "Builds", "a", "dict", "mapping", "to", "lists", "of", "OwnershipPeriods", "from", "a", "db", "table", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L159-L167
train
quantopian/zipline
zipline/assets/assets.py
build_grouped_ownership_map
def build_grouped_ownership_map(table, key_from_row, value_from_row, group_key): """ Builds a dict mapping group keys to maps of keys to to lists of OwnershipPeriods, from a db table. """ grouped_rows = g...
python
def build_grouped_ownership_map(table, key_from_row, value_from_row, group_key): """ Builds a dict mapping group keys to maps of keys to to lists of OwnershipPeriods, from a db table. """ grouped_rows = g...
[ "def", "build_grouped_ownership_map", "(", "table", ",", "key_from_row", ",", "value_from_row", ",", "group_key", ")", ":", "grouped_rows", "=", "groupby", "(", "group_key", ",", "sa", ".", "select", "(", "table", ".", "c", ")", ".", "execute", "(", ")", "...
Builds a dict mapping group keys to maps of keys to to lists of OwnershipPeriods, from a db table.
[ "Builds", "a", "dict", "mapping", "group", "keys", "to", "maps", "of", "keys", "to", "to", "lists", "of", "OwnershipPeriods", "from", "a", "db", "table", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L170-L189
train
quantopian/zipline
zipline/assets/assets.py
_filter_kwargs
def _filter_kwargs(names, dict_): """Filter out kwargs from a dictionary. Parameters ---------- names : set[str] The names to select from ``dict_``. dict_ : dict[str, any] The dictionary to select from. Returns ------- kwargs : dict[str, any] ``dict_`` where the...
python
def _filter_kwargs(names, dict_): """Filter out kwargs from a dictionary. Parameters ---------- names : set[str] The names to select from ``dict_``. dict_ : dict[str, any] The dictionary to select from. Returns ------- kwargs : dict[str, any] ``dict_`` where the...
[ "def", "_filter_kwargs", "(", "names", ",", "dict_", ")", ":", "return", "{", "k", ":", "v", "for", "k", ",", "v", "in", "dict_", ".", "items", "(", ")", "if", "k", "in", "names", "and", "v", "is", "not", "None", "}" ]
Filter out kwargs from a dictionary. Parameters ---------- names : set[str] The names to select from ``dict_``. dict_ : dict[str, any] The dictionary to select from. Returns ------- kwargs : dict[str, any] ``dict_`` where the keys intersect with ``names`` and the va...
[ "Filter", "out", "kwargs", "from", "a", "dictionary", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L193-L209
train
quantopian/zipline
zipline/assets/assets.py
_convert_asset_timestamp_fields
def _convert_asset_timestamp_fields(dict_): """ Takes in a dict of Asset init args and converts dates to pd.Timestamps """ for key in _asset_timestamp_fields & viewkeys(dict_): value = pd.Timestamp(dict_[key], tz='UTC') dict_[key] = None if isnull(value) else value return dict_
python
def _convert_asset_timestamp_fields(dict_): """ Takes in a dict of Asset init args and converts dates to pd.Timestamps """ for key in _asset_timestamp_fields & viewkeys(dict_): value = pd.Timestamp(dict_[key], tz='UTC') dict_[key] = None if isnull(value) else value return dict_
[ "def", "_convert_asset_timestamp_fields", "(", "dict_", ")", ":", "for", "key", "in", "_asset_timestamp_fields", "&", "viewkeys", "(", "dict_", ")", ":", "value", "=", "pd", ".", "Timestamp", "(", "dict_", "[", "key", "]", ",", "tz", "=", "'UTC'", ")", "...
Takes in a dict of Asset init args and converts dates to pd.Timestamps
[ "Takes", "in", "a", "dict", "of", "Asset", "init", "args", "and", "converts", "dates", "to", "pd", ".", "Timestamps" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L216-L223
train
quantopian/zipline
zipline/assets/assets.py
was_active
def was_active(reference_date_value, asset): """ Whether or not `asset` was active at the time corresponding to `reference_date_value`. Parameters ---------- reference_date_value : int Date, represented as nanoseconds since EPOCH, for which we want to know if `asset` was alive. ...
python
def was_active(reference_date_value, asset): """ Whether or not `asset` was active at the time corresponding to `reference_date_value`. Parameters ---------- reference_date_value : int Date, represented as nanoseconds since EPOCH, for which we want to know if `asset` was alive. ...
[ "def", "was_active", "(", "reference_date_value", ",", "asset", ")", ":", "return", "(", "asset", ".", "start_date", ".", "value", "<=", "reference_date_value", "<=", "asset", ".", "end_date", ".", "value", ")" ]
Whether or not `asset` was active at the time corresponding to `reference_date_value`. Parameters ---------- reference_date_value : int Date, represented as nanoseconds since EPOCH, for which we want to know if `asset` was alive. This is generally the result of accessing the `v...
[ "Whether", "or", "not", "asset", "was", "active", "at", "the", "time", "corresponding", "to", "reference_date_value", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L1568-L1591
train
quantopian/zipline
zipline/assets/assets.py
AssetFinder.lookup_asset_types
def lookup_asset_types(self, sids): """ Retrieve asset types for a list of sids. Parameters ---------- sids : list[int] Returns ------- types : dict[sid -> str or None] Asset types for the provided sids. """ found = {} ...
python
def lookup_asset_types(self, sids): """ Retrieve asset types for a list of sids. Parameters ---------- sids : list[int] Returns ------- types : dict[sid -> str or None] Asset types for the provided sids. """ found = {} ...
[ "def", "lookup_asset_types", "(", "self", ",", "sids", ")", ":", "found", "=", "{", "}", "missing", "=", "set", "(", ")", "for", "sid", "in", "sids", ":", "try", ":", "found", "[", "sid", "]", "=", "self", ".", "_asset_type_cache", "[", "sid", "]",...
Retrieve asset types for a list of sids. Parameters ---------- sids : list[int] Returns ------- types : dict[sid -> str or None] Asset types for the provided sids.
[ "Retrieve", "asset", "types", "for", "a", "list", "of", "sids", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L405-L443
train
quantopian/zipline
zipline/assets/assets.py
AssetFinder.retrieve_all
def retrieve_all(self, sids, default_none=False): """ Retrieve all assets in `sids`. Parameters ---------- sids : iterable of int Assets to retrieve. default_none : bool If True, return None for failed lookups. If False, raise `SidsNot...
python
def retrieve_all(self, sids, default_none=False): """ Retrieve all assets in `sids`. Parameters ---------- sids : iterable of int Assets to retrieve. default_none : bool If True, return None for failed lookups. If False, raise `SidsNot...
[ "def", "retrieve_all", "(", "self", ",", "sids", ",", "default_none", "=", "False", ")", ":", "sids", "=", "list", "(", "sids", ")", "hits", ",", "missing", ",", "failures", "=", "{", "}", ",", "set", "(", ")", ",", "[", "]", "for", "sid", "in", ...
Retrieve all assets in `sids`. Parameters ---------- sids : iterable of int Assets to retrieve. default_none : bool If True, return None for failed lookups. If False, raise `SidsNotFound`. Returns ------- assets : list[Asset o...
[ "Retrieve", "all", "assets", "in", "sids", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L473-L539
train
quantopian/zipline
zipline/assets/assets.py
AssetFinder._select_most_recent_symbols_chunk
def _select_most_recent_symbols_chunk(self, sid_group): """Retrieve the most recent symbol for a set of sids. Parameters ---------- sid_group : iterable[int] The sids to lookup. The length of this sequence must be less than or equal to SQLITE_MAX_VARIABLE_NUMBER ...
python
def _select_most_recent_symbols_chunk(self, sid_group): """Retrieve the most recent symbol for a set of sids. Parameters ---------- sid_group : iterable[int] The sids to lookup. The length of this sequence must be less than or equal to SQLITE_MAX_VARIABLE_NUMBER ...
[ "def", "_select_most_recent_symbols_chunk", "(", "self", ",", "sid_group", ")", ":", "cols", "=", "self", ".", "equity_symbol_mappings", ".", "c", "# These are the columns we actually want.", "data_cols", "=", "(", "cols", ".", "sid", ",", ")", "+", "tuple", "(", ...
Retrieve the most recent symbol for a set of sids. Parameters ---------- sid_group : iterable[int] The sids to lookup. The length of this sequence must be less than or equal to SQLITE_MAX_VARIABLE_NUMBER because the sids will be passed in as sql bind params. ...
[ "Retrieve", "the", "most", "recent", "symbol", "for", "a", "set", "of", "sids", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L600-L647
train
quantopian/zipline
zipline/assets/assets.py
AssetFinder._retrieve_assets
def _retrieve_assets(self, sids, asset_tbl, asset_type): """ Internal function for loading assets from a table. This should be the only method of `AssetFinder` that writes Assets into self._asset_cache. Parameters --------- sids : iterable of int Ass...
python
def _retrieve_assets(self, sids, asset_tbl, asset_type): """ Internal function for loading assets from a table. This should be the only method of `AssetFinder` that writes Assets into self._asset_cache. Parameters --------- sids : iterable of int Ass...
[ "def", "_retrieve_assets", "(", "self", ",", "sids", ",", "asset_tbl", ",", "asset_type", ")", ":", "# Fastpath for empty request.", "if", "not", "sids", ":", "return", "{", "}", "cache", "=", "self", ".", "_asset_cache", "hits", "=", "{", "}", "querying_equ...
Internal function for loading assets from a table. This should be the only method of `AssetFinder` that writes Assets into self._asset_cache. Parameters --------- sids : iterable of int Asset ids to look up. asset_tbl : sqlalchemy.Table Table fro...
[ "Internal", "function", "for", "loading", "assets", "from", "a", "table", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L689-L740
train
quantopian/zipline
zipline/assets/assets.py
AssetFinder._lookup_symbol_strict
def _lookup_symbol_strict(self, ownership_map, multi_country, symbol, as_of_date): """ Resolve a symbol to an asset object without fuzzy matching. Parameters ---------...
python
def _lookup_symbol_strict(self, ownership_map, multi_country, symbol, as_of_date): """ Resolve a symbol to an asset object without fuzzy matching. Parameters ---------...
[ "def", "_lookup_symbol_strict", "(", "self", ",", "ownership_map", ",", "multi_country", ",", "symbol", ",", "as_of_date", ")", ":", "# split the symbol into the components, if there are no", "# company/share class parts then share_class_symbol will be empty", "company_symbol", ","...
Resolve a symbol to an asset object without fuzzy matching. Parameters ---------- ownership_map : dict[(str, str), list[OwnershipPeriod]] The mapping from split symbols to ownership periods. multi_country : bool Does this mapping span multiple countries? ...
[ "Resolve", "a", "symbol", "to", "an", "asset", "object", "without", "fuzzy", "matching", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L742-L865
train
quantopian/zipline
zipline/assets/assets.py
AssetFinder.lookup_symbol
def lookup_symbol(self, symbol, as_of_date, fuzzy=False, country_code=None): """Lookup an equity by symbol. Parameters ---------- symbol : str The ticker symbol to resolve. as_of_...
python
def lookup_symbol(self, symbol, as_of_date, fuzzy=False, country_code=None): """Lookup an equity by symbol. Parameters ---------- symbol : str The ticker symbol to resolve. as_of_...
[ "def", "lookup_symbol", "(", "self", ",", "symbol", ",", "as_of_date", ",", "fuzzy", "=", "False", ",", "country_code", "=", "None", ")", ":", "if", "symbol", "is", "None", ":", "raise", "TypeError", "(", "\"Cannot lookup asset for symbol of None for \"", "\"as ...
Lookup an equity by symbol. Parameters ---------- symbol : str The ticker symbol to resolve. as_of_date : datetime or None Look up the last owner of this symbol as of this datetime. If ``as_of_date`` is None, then this can only resolve the equity ...
[ "Lookup", "an", "equity", "by", "symbol", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L955-L1016
train
quantopian/zipline
zipline/assets/assets.py
AssetFinder.lookup_symbols
def lookup_symbols(self, symbols, as_of_date, fuzzy=False, country_code=None): """ Lookup a list of equities by symbol. Equivalent to:: [finder.lookup_symbol(s, as_of, fuzzy) for s in symbol...
python
def lookup_symbols(self, symbols, as_of_date, fuzzy=False, country_code=None): """ Lookup a list of equities by symbol. Equivalent to:: [finder.lookup_symbol(s, as_of, fuzzy) for s in symbol...
[ "def", "lookup_symbols", "(", "self", ",", "symbols", ",", "as_of_date", ",", "fuzzy", "=", "False", ",", "country_code", "=", "None", ")", ":", "if", "not", "symbols", ":", "return", "[", "]", "multi_country", "=", "country_code", "is", "None", "if", "f...
Lookup a list of equities by symbol. Equivalent to:: [finder.lookup_symbol(s, as_of, fuzzy) for s in symbols] but potentially faster because repeated lookups are memoized. Parameters ---------- symbols : sequence[str] Sequence of ticker symbols to reso...
[ "Lookup", "a", "list", "of", "equities", "by", "symbol", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L1018-L1077
train
quantopian/zipline
zipline/assets/assets.py
AssetFinder.lookup_future_symbol
def lookup_future_symbol(self, symbol): """Lookup a future contract by symbol. Parameters ---------- symbol : str The symbol of the desired contract. Returns ------- future : Future The future contract referenced by ``symbol``. R...
python
def lookup_future_symbol(self, symbol): """Lookup a future contract by symbol. Parameters ---------- symbol : str The symbol of the desired contract. Returns ------- future : Future The future contract referenced by ``symbol``. R...
[ "def", "lookup_future_symbol", "(", "self", ",", "symbol", ")", ":", "data", "=", "self", ".", "_select_asset_by_symbol", "(", "self", ".", "futures_contracts", ",", "symbol", ")", ".", "execute", "(", ")", ".", "fetchone", "(", ")", "# If no data found, raise...
Lookup a future contract by symbol. Parameters ---------- symbol : str The symbol of the desired contract. Returns ------- future : Future The future contract referenced by ``symbol``. Raises ------ SymbolNotFound ...
[ "Lookup", "a", "future", "contract", "by", "symbol", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L1079-L1105
train
quantopian/zipline
zipline/assets/assets.py
AssetFinder.get_supplementary_field
def get_supplementary_field(self, sid, field_name, as_of_date): """Get the value of a supplementary field for an asset. Parameters ---------- sid : int The sid of the asset to query. field_name : str Name of the supplementary field. as_of_date : p...
python
def get_supplementary_field(self, sid, field_name, as_of_date): """Get the value of a supplementary field for an asset. Parameters ---------- sid : int The sid of the asset to query. field_name : str Name of the supplementary field. as_of_date : p...
[ "def", "get_supplementary_field", "(", "self", ",", "sid", ",", "field_name", ",", "as_of_date", ")", ":", "try", ":", "periods", "=", "self", ".", "equity_supplementary_map_by_sid", "[", "field_name", ",", "sid", ",", "]", "assert", "periods", ",", "'empty pe...
Get the value of a supplementary field for an asset. Parameters ---------- sid : int The sid of the asset to query. field_name : str Name of the supplementary field. as_of_date : pd.Timestamp, None The last known value on this date is returned...
[ "Get", "the", "value", "of", "a", "supplementary", "field", "for", "an", "asset", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L1142-L1193
train
quantopian/zipline
zipline/assets/assets.py
AssetFinder._lookup_generic_scalar
def _lookup_generic_scalar(self, obj, as_of_date, country_code, matches, missing): """ Convert asset_convertible to an asset. On success, ap...
python
def _lookup_generic_scalar(self, obj, as_of_date, country_code, matches, missing): """ Convert asset_convertible to an asset. On success, ap...
[ "def", "_lookup_generic_scalar", "(", "self", ",", "obj", ",", "as_of_date", ",", "country_code", ",", "matches", ",", "missing", ")", ":", "result", "=", "self", ".", "_lookup_generic_scalar_helper", "(", "obj", ",", "as_of_date", ",", "country_code", ",", ")...
Convert asset_convertible to an asset. On success, append to matches. On failure, append to missing.
[ "Convert", "asset_convertible", "to", "an", "asset", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L1298-L1316
train
quantopian/zipline
zipline/assets/assets.py
AssetFinder.lookup_generic
def lookup_generic(self, obj, as_of_date, country_code): """ Convert an object into an Asset or sequence of Assets. This method exists primarily as a convenience for implementing user-facing APIs that can handle multiple kinds of input. It should not be used for internal code w...
python
def lookup_generic(self, obj, as_of_date, country_code): """ Convert an object into an Asset or sequence of Assets. This method exists primarily as a convenience for implementing user-facing APIs that can handle multiple kinds of input. It should not be used for internal code w...
[ "def", "lookup_generic", "(", "self", ",", "obj", ",", "as_of_date", ",", "country_code", ")", ":", "matches", "=", "[", "]", "missing", "=", "[", "]", "# Interpret input as scalar.", "if", "isinstance", "(", "obj", ",", "(", "AssetConvertible", ",", "Contin...
Convert an object into an Asset or sequence of Assets. This method exists primarily as a convenience for implementing user-facing APIs that can handle multiple kinds of input. It should not be used for internal code where we already know the expected types of our inputs. Param...
[ "Convert", "an", "object", "into", "an", "Asset", "or", "sequence", "of", "Assets", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L1347-L1414
train
quantopian/zipline
zipline/assets/assets.py
AssetFinder._compute_asset_lifetimes
def _compute_asset_lifetimes(self, country_codes): """ Compute and cache a recarray of asset lifetimes. """ equities_cols = self.equities.c if country_codes: buf = np.array( tuple( sa.select(( equities_cols.s...
python
def _compute_asset_lifetimes(self, country_codes): """ Compute and cache a recarray of asset lifetimes. """ equities_cols = self.equities.c if country_codes: buf = np.array( tuple( sa.select(( equities_cols.s...
[ "def", "_compute_asset_lifetimes", "(", "self", ",", "country_codes", ")", ":", "equities_cols", "=", "self", ".", "equities", ".", "c", "if", "country_codes", ":", "buf", "=", "np", ".", "array", "(", "tuple", "(", "sa", ".", "select", "(", "(", "equiti...
Compute and cache a recarray of asset lifetimes.
[ "Compute", "and", "cache", "a", "recarray", "of", "asset", "lifetimes", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L1416-L1456
train
quantopian/zipline
zipline/assets/assets.py
AssetFinder.lifetimes
def lifetimes(self, dates, include_start_date, country_codes): """ Compute a DataFrame representing asset lifetimes for the specified date range. Parameters ---------- dates : pd.DatetimeIndex The dates for which to compute lifetimes. include_start_da...
python
def lifetimes(self, dates, include_start_date, country_codes): """ Compute a DataFrame representing asset lifetimes for the specified date range. Parameters ---------- dates : pd.DatetimeIndex The dates for which to compute lifetimes. include_start_da...
[ "def", "lifetimes", "(", "self", ",", "dates", ",", "include_start_date", ",", "country_codes", ")", ":", "if", "isinstance", "(", "country_codes", ",", "string_types", ")", ":", "raise", "TypeError", "(", "\"Got string {!r} instead of an iterable of strings in \"", "...
Compute a DataFrame representing asset lifetimes for the specified date range. Parameters ---------- dates : pd.DatetimeIndex The dates for which to compute lifetimes. include_start_date : bool Whether or not to count the asset as alive on its start_date....
[ "Compute", "a", "DataFrame", "representing", "asset", "lifetimes", "for", "the", "specified", "date", "range", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L1458-L1514
train
quantopian/zipline
zipline/assets/assets.py
AssetFinder.equities_sids_for_country_code
def equities_sids_for_country_code(self, country_code): """Return all of the sids for a given country. Parameters ---------- country_code : str An ISO 3166 alpha-2 country code. Returns ------- tuple[int] The sids whose exchanges are in t...
python
def equities_sids_for_country_code(self, country_code): """Return all of the sids for a given country. Parameters ---------- country_code : str An ISO 3166 alpha-2 country code. Returns ------- tuple[int] The sids whose exchanges are in t...
[ "def", "equities_sids_for_country_code", "(", "self", ",", "country_code", ")", ":", "sids", "=", "self", ".", "_compute_asset_lifetimes", "(", "[", "country_code", "]", ")", ".", "sid", "return", "tuple", "(", "sids", ".", "tolist", "(", ")", ")" ]
Return all of the sids for a given country. Parameters ---------- country_code : str An ISO 3166 alpha-2 country code. Returns ------- tuple[int] The sids whose exchanges are in this country.
[ "Return", "all", "of", "the", "sids", "for", "a", "given", "country", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L1516-L1530
train
quantopian/zipline
zipline/data/continuous_future_reader.py
ContinuousFutureSessionBarReader.load_raw_arrays
def load_raw_arrays(self, columns, start_date, end_date, assets): """ Parameters ---------- fields : list of str 'sid' start_dt: Timestamp Beginning of the window range. end_dt: Timestamp End of the window range. sids : list of in...
python
def load_raw_arrays(self, columns, start_date, end_date, assets): """ Parameters ---------- fields : list of str 'sid' start_dt: Timestamp Beginning of the window range. end_dt: Timestamp End of the window range. sids : list of in...
[ "def", "load_raw_arrays", "(", "self", ",", "columns", ",", "start_date", ",", "end_date", ",", "assets", ")", ":", "rolls_by_asset", "=", "{", "}", "for", "asset", "in", "assets", ":", "rf", "=", "self", ".", "_roll_finders", "[", "asset", ".", "roll_st...
Parameters ---------- fields : list of str 'sid' start_dt: Timestamp Beginning of the window range. end_dt: Timestamp End of the window range. sids : list of int The asset identifiers in the window. Returns ------- ...
[ "Parameters", "----------", "fields", ":", "list", "of", "str", "sid", "start_dt", ":", "Timestamp", "Beginning", "of", "the", "window", "range", ".", "end_dt", ":", "Timestamp", "End", "of", "the", "window", "range", ".", "sids", ":", "list", "of", "int",...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/continuous_future_reader.py#L12-L96
train
quantopian/zipline
zipline/data/continuous_future_reader.py
ContinuousFutureSessionBarReader.get_value
def get_value(self, continuous_future, dt, field): """ Retrieve the value at the given coordinates. Parameters ---------- sid : int The asset identifier. dt : pd.Timestamp The timestamp for the desired data point. field : string ...
python
def get_value(self, continuous_future, dt, field): """ Retrieve the value at the given coordinates. Parameters ---------- sid : int The asset identifier. dt : pd.Timestamp The timestamp for the desired data point. field : string ...
[ "def", "get_value", "(", "self", ",", "continuous_future", ",", "dt", ",", "field", ")", ":", "rf", "=", "self", ".", "_roll_finders", "[", "continuous_future", ".", "roll_style", "]", "sid", "=", "(", "rf", ".", "get_contract_center", "(", "continuous_futur...
Retrieve the value at the given coordinates. Parameters ---------- sid : int The asset identifier. dt : pd.Timestamp The timestamp for the desired data point. field : string The OHLVC name for the desired data point. Returns -...
[ "Retrieve", "the", "value", "at", "the", "given", "coordinates", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/continuous_future_reader.py#L127-L156
train
quantopian/zipline
zipline/data/continuous_future_reader.py
ContinuousFutureSessionBarReader.get_last_traded_dt
def get_last_traded_dt(self, asset, dt): """ Get the latest minute on or before ``dt`` in which ``asset`` traded. If there are no trades on or before ``dt``, returns ``pd.NaT``. Parameters ---------- asset : zipline.asset.Asset The asset for which to get the...
python
def get_last_traded_dt(self, asset, dt): """ Get the latest minute on or before ``dt`` in which ``asset`` traded. If there are no trades on or before ``dt``, returns ``pd.NaT``. Parameters ---------- asset : zipline.asset.Asset The asset for which to get the...
[ "def", "get_last_traded_dt", "(", "self", ",", "asset", ",", "dt", ")", ":", "rf", "=", "self", ".", "_roll_finders", "[", "asset", ".", "roll_style", "]", "sid", "=", "(", "rf", ".", "get_contract_center", "(", "asset", ".", "root_symbol", ",", "dt", ...
Get the latest minute on or before ``dt`` in which ``asset`` traded. If there are no trades on or before ``dt``, returns ``pd.NaT``. Parameters ---------- asset : zipline.asset.Asset The asset for which to get the last traded minute. dt : pd.Timestamp Th...
[ "Get", "the", "latest", "minute", "on", "or", "before", "dt", "in", "which", "asset", "traded", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/continuous_future_reader.py#L158-L184
train
quantopian/zipline
zipline/data/continuous_future_reader.py
ContinuousFutureMinuteBarReader.load_raw_arrays
def load_raw_arrays(self, columns, start_date, end_date, assets): """ Parameters ---------- fields : list of str 'open', 'high', 'low', 'close', or 'volume' start_dt: Timestamp Beginning of the window range. end_dt: Timestamp End of the wi...
python
def load_raw_arrays(self, columns, start_date, end_date, assets): """ Parameters ---------- fields : list of str 'open', 'high', 'low', 'close', or 'volume' start_dt: Timestamp Beginning of the window range. end_dt: Timestamp End of the wi...
[ "def", "load_raw_arrays", "(", "self", ",", "columns", ",", "start_date", ",", "end_date", ",", "assets", ")", ":", "rolls_by_asset", "=", "{", "}", "tc", "=", "self", ".", "trading_calendar", "start_session", "=", "tc", ".", "minute_to_session_label", "(", ...
Parameters ---------- fields : list of str 'open', 'high', 'low', 'close', or 'volume' start_dt: Timestamp Beginning of the window range. end_dt: Timestamp End of the window range. sids : list of int The asset identifiers in the window....
[ "Parameters", "----------", "fields", ":", "list", "of", "str", "open", "high", "low", "close", "or", "volume", "start_dt", ":", "Timestamp", "Beginning", "of", "the", "window", "range", ".", "end_dt", ":", "Timestamp", "End", "of", "the", "window", "range",...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/continuous_future_reader.py#L204-L282
train
quantopian/zipline
zipline/protocol.py
Portfolio.current_portfolio_weights
def current_portfolio_weights(self): """ Compute each asset's weight in the portfolio by calculating its held value divided by the total value of all positions. Each equity's value is its price times the number of shares held. Each futures contract's value is its unit price time...
python
def current_portfolio_weights(self): """ Compute each asset's weight in the portfolio by calculating its held value divided by the total value of all positions. Each equity's value is its price times the number of shares held. Each futures contract's value is its unit price time...
[ "def", "current_portfolio_weights", "(", "self", ")", ":", "position_values", "=", "pd", ".", "Series", "(", "{", "asset", ":", "(", "position", ".", "last_sale_price", "*", "position", ".", "amount", "*", "asset", ".", "price_multiplier", ")", "for", "asset...
Compute each asset's weight in the portfolio by calculating its held value divided by the total value of all positions. Each equity's value is its price times the number of shares held. Each futures contract's value is its unit price times number of shares held times the multiplier.
[ "Compute", "each", "asset", "s", "weight", "in", "the", "portfolio", "by", "calculating", "its", "held", "value", "divided", "by", "the", "total", "value", "of", "all", "positions", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/protocol.py#L216-L233
train
Chyroc/WechatSogou
wechatsogou/api.py
WechatSogouAPI.__hosting_wechat_img
def __hosting_wechat_img(self, content_info, hosting_callback): """将微信明细中图片托管到云端,同时将html页面中的对应图片替换 Parameters ---------- content_info : dict 微信文章明细字典 { 'content_img_list': [], # 从微信文章解析出的原始图片列表 'content_html': '', # 从微信文章解析出文章的内容 }...
python
def __hosting_wechat_img(self, content_info, hosting_callback): """将微信明细中图片托管到云端,同时将html页面中的对应图片替换 Parameters ---------- content_info : dict 微信文章明细字典 { 'content_img_list': [], # 从微信文章解析出的原始图片列表 'content_html': '', # 从微信文章解析出文章的内容 }...
[ "def", "__hosting_wechat_img", "(", "self", ",", "content_info", ",", "hosting_callback", ")", ":", "assert", "callable", "(", "hosting_callback", ")", "content_img_list", "=", "content_info", ".", "pop", "(", "\"content_img_list\"", ")", "content_html", "=", "conte...
将微信明细中图片托管到云端,同时将html页面中的对应图片替换 Parameters ---------- content_info : dict 微信文章明细字典 { 'content_img_list': [], # 从微信文章解析出的原始图片列表 'content_html': '', # 从微信文章解析出文章的内容 } hosting_callback : callable 托管回调函数,传入单个图片链接,返回托管后的图片链接...
[ "将微信明细中图片托管到云端,同时将html页面中的对应图片替换" ]
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/api.py#L138-L171
train
Chyroc/WechatSogou
wechatsogou/api.py
WechatSogouAPI.get_gzh_info
def get_gzh_info(self, wecgat_id_or_name, unlock_callback=None, identify_image_callback=None, decode_url=True): """获取公众号微信号 wechatid 的信息 因为wechatid唯一确定,所以第一个就是要搜索的公众号 Parameters ---------- wecgat_id_or_name : str or unicode wechat_id or wechat_name unlock_ca...
python
def get_gzh_info(self, wecgat_id_or_name, unlock_callback=None, identify_image_callback=None, decode_url=True): """获取公众号微信号 wechatid 的信息 因为wechatid唯一确定,所以第一个就是要搜索的公众号 Parameters ---------- wecgat_id_or_name : str or unicode wechat_id or wechat_name unlock_ca...
[ "def", "get_gzh_info", "(", "self", ",", "wecgat_id_or_name", ",", "unlock_callback", "=", "None", ",", "identify_image_callback", "=", "None", ",", "decode_url", "=", "True", ")", ":", "info", "=", "self", ".", "search_gzh", "(", "wecgat_id_or_name", ",", "1"...
获取公众号微信号 wechatid 的信息 因为wechatid唯一确定,所以第一个就是要搜索的公众号 Parameters ---------- wecgat_id_or_name : str or unicode wechat_id or wechat_name unlock_callback : callable 处理出现验证码页面的函数,参见 unlock_callback_example identify_image_callback : callable ...
[ "获取公众号微信号", "wechatid", "的信息" ]
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/api.py#L208-L241
train
Chyroc/WechatSogou
wechatsogou/api.py
WechatSogouAPI.search_gzh
def search_gzh(self, keyword, page=1, unlock_callback=None, identify_image_callback=None, decode_url=True): """搜索 公众号 对于出现验证码的情况,可以由使用者自己提供: 1、函数 unlock_callback ,这个函数 handle 出现验证码到解决的整个流程 2、也可以 只提供函数 identify_image_callback,这个函数输入验证码二进制数据,输出验证码文字,剩下的由 wechatsogou 包来解决 注...
python
def search_gzh(self, keyword, page=1, unlock_callback=None, identify_image_callback=None, decode_url=True): """搜索 公众号 对于出现验证码的情况,可以由使用者自己提供: 1、函数 unlock_callback ,这个函数 handle 出现验证码到解决的整个流程 2、也可以 只提供函数 identify_image_callback,这个函数输入验证码二进制数据,输出验证码文字,剩下的由 wechatsogou 包来解决 注...
[ "def", "search_gzh", "(", "self", ",", "keyword", ",", "page", "=", "1", ",", "unlock_callback", "=", "None", ",", "identify_image_callback", "=", "None", ",", "decode_url", "=", "True", ")", ":", "url", "=", "WechatSogouRequest", ".", "gen_search_gzh_url", ...
搜索 公众号 对于出现验证码的情况,可以由使用者自己提供: 1、函数 unlock_callback ,这个函数 handle 出现验证码到解决的整个流程 2、也可以 只提供函数 identify_image_callback,这个函数输入验证码二进制数据,输出验证码文字,剩下的由 wechatsogou 包来解决 注意: 函数 unlock_callback 和 identify_image_callback 只需要提供一个,如果都提供了,那么 identify_image_callback 不起作用 Par...
[ "搜索", "公众号" ]
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/api.py#L243-L296
train
Chyroc/WechatSogou
wechatsogou/api.py
WechatSogouAPI.search_article
def search_article(self, keyword, page=1, timesn=WechatSogouConst.search_article_time.anytime, article_type=WechatSogouConst.search_article_type.all, ft=None, et=None, unlock_callback=None, identify_image_callback=None, decode_u...
python
def search_article(self, keyword, page=1, timesn=WechatSogouConst.search_article_time.anytime, article_type=WechatSogouConst.search_article_type.all, ft=None, et=None, unlock_callback=None, identify_image_callback=None, decode_u...
[ "def", "search_article", "(", "self", ",", "keyword", ",", "page", "=", "1", ",", "timesn", "=", "WechatSogouConst", ".", "search_article_time", ".", "anytime", ",", "article_type", "=", "WechatSogouConst", ".", "search_article_type", ".", "all", ",", "ft", "=...
搜索 文章 对于出现验证码的情况,可以由使用者自己提供: 1、函数 unlock_callback ,这个函数 handle 出现验证码到解决的整个流程 2、也可以 只提供函数 identify_image_callback,这个函数输入验证码二进制数据,输出验证码文字,剩下的由 wechatsogou 包来解决 注意: 函数 unlock_callback 和 identify_image_callback 只需要提供一个,如果都提供了,那么 identify_image_callback 不起作用 Para...
[ "搜索", "文章" ]
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/api.py#L298-L369
train
Chyroc/WechatSogou
wechatsogou/api.py
WechatSogouAPI.get_gzh_article_by_history
def get_gzh_article_by_history(self, keyword=None, url=None, unlock_callback_sogou=None, identify_image_callback_sogou=None, unlock_callback_weixin=None, identify_image_callback_we...
python
def get_gzh_article_by_history(self, keyword=None, url=None, unlock_callback_sogou=None, identify_image_callback_sogou=None, unlock_callback_weixin=None, identify_image_callback_we...
[ "def", "get_gzh_article_by_history", "(", "self", ",", "keyword", "=", "None", ",", "url", "=", "None", ",", "unlock_callback_sogou", "=", "None", ",", "identify_image_callback_sogou", "=", "None", ",", "unlock_callback_weixin", "=", "None", ",", "identify_image_cal...
从 公众号的最近10条群发页面 提取公众号信息 和 文章列表信息 对于出现验证码的情况,可以由使用者自己提供: 1、函数 unlock_callback ,这个函数 handle 出现验证码到解决的整个流程 2、也可以 只提供函数 identify_image_callback,这个函数输入验证码二进制数据,输出验证码文字,剩下的由 wechatsogou 包来解决 注意: 函数 unlock_callback 和 identify_image_callback 只需要提供一个,如果都提供了,那么 identify_image_...
[ "从", "公众号的最近10条群发页面", "提取公众号信息", "和", "文章列表信息" ]
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/api.py#L371-L448
train
Chyroc/WechatSogou
wechatsogou/api.py
WechatSogouAPI.get_gzh_article_by_hot
def get_gzh_article_by_hot(self, hot_index, page=1, unlock_callback=None, identify_image_callback=None): """获取 首页热门文章 Parameters ---------- hot_index : WechatSogouConst.hot_index 首页热门文章的分类(常量):WechatSogouConst.hot_index.xxx page : int 页数 Returns ...
python
def get_gzh_article_by_hot(self, hot_index, page=1, unlock_callback=None, identify_image_callback=None): """获取 首页热门文章 Parameters ---------- hot_index : WechatSogouConst.hot_index 首页热门文章的分类(常量):WechatSogouConst.hot_index.xxx page : int 页数 Returns ...
[ "def", "get_gzh_article_by_hot", "(", "self", ",", "hot_index", ",", "page", "=", "1", ",", "unlock_callback", "=", "None", ",", "identify_image_callback", "=", "None", ")", ":", "assert", "hasattr", "(", "WechatSogouConst", ".", "hot_index", ",", "hot_index", ...
获取 首页热门文章 Parameters ---------- hot_index : WechatSogouConst.hot_index 首页热门文章的分类(常量):WechatSogouConst.hot_index.xxx page : int 页数 Returns ------- list[dict] { 'gzh': { 'headimage': str, # 公...
[ "获取", "首页热门文章" ]
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/api.py#L450-L489
train
Chyroc/WechatSogou
wechatsogou/api.py
WechatSogouAPI.get_article_content
def get_article_content(self, url, del_qqmusic=True, del_mpvoice=True, unlock_callback=None, identify_image_callback=None, hosting_callback=None, raw=False): """获取文章原文,避免临时链接失效 Parameters ---------- url : str or unicode 原文链接,临时链接 raw : boo...
python
def get_article_content(self, url, del_qqmusic=True, del_mpvoice=True, unlock_callback=None, identify_image_callback=None, hosting_callback=None, raw=False): """获取文章原文,避免临时链接失效 Parameters ---------- url : str or unicode 原文链接,临时链接 raw : boo...
[ "def", "get_article_content", "(", "self", ",", "url", ",", "del_qqmusic", "=", "True", ",", "del_mpvoice", "=", "True", ",", "unlock_callback", "=", "None", ",", "identify_image_callback", "=", "None", ",", "hosting_callback", "=", "None", ",", "raw", "=", ...
获取文章原文,避免临时链接失效 Parameters ---------- url : str or unicode 原文链接,临时链接 raw : bool True: 返回原始html False: 返回处理后的html del_qqmusic: bool True:微信原文中有插入的qq音乐,则删除 False:微信源文中有插入的qq音乐,则保留 del_mpvoice: bool Tru...
[ "获取文章原文,避免临时链接失效" ]
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/api.py#L491-L541
train
Chyroc/WechatSogou
wechatsogou/api.py
WechatSogouAPI.get_sugg
def get_sugg(self, keyword): """获取微信搜狗搜索关键词联想 Parameters ---------- keyword : str or unicode 关键词 Returns ------- list[str] 联想关键词列表 Raises ------ WechatSogouRequestsException """ url = 'http://w.sug...
python
def get_sugg(self, keyword): """获取微信搜狗搜索关键词联想 Parameters ---------- keyword : str or unicode 关键词 Returns ------- list[str] 联想关键词列表 Raises ------ WechatSogouRequestsException """ url = 'http://w.sug...
[ "def", "get_sugg", "(", "self", ",", "keyword", ")", ":", "url", "=", "'http://w.sugg.sogou.com/sugg/ajaj_json.jsp?key={}&type=wxpub&pr=web'", ".", "format", "(", "quote", "(", "keyword", ".", "encode", "(", "'utf-8'", ")", ")", ")", "r", "=", "requests", ".", ...
获取微信搜狗搜索关键词联想 Parameters ---------- keyword : str or unicode 关键词 Returns ------- list[str] 联想关键词列表 Raises ------ WechatSogouRequestsException
[ "获取微信搜狗搜索关键词联想" ]
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/api.py#L543-L567
train
Chyroc/WechatSogou
wechatsogou/identify_image.py
unlock_sogou_callback_example
def unlock_sogou_callback_example(url, req, resp, img, identify_image_callback): """手动打码解锁 Parameters ---------- url : str or unicode 验证码页面 之前的 url req : requests.sessions.Session requests.Session() 供调用解锁 resp : requests.models.Response requests 访问页面返回的,已经跳转了 img : b...
python
def unlock_sogou_callback_example(url, req, resp, img, identify_image_callback): """手动打码解锁 Parameters ---------- url : str or unicode 验证码页面 之前的 url req : requests.sessions.Session requests.Session() 供调用解锁 resp : requests.models.Response requests 访问页面返回的,已经跳转了 img : b...
[ "def", "unlock_sogou_callback_example", "(", "url", ",", "req", ",", "resp", ",", "img", ",", "identify_image_callback", ")", ":", "# no use resp", "url_quote", "=", "url", ".", "split", "(", "'weixin.sogou.com/'", ")", "[", "-", "1", "]", "unlock_url", "=", ...
手动打码解锁 Parameters ---------- url : str or unicode 验证码页面 之前的 url req : requests.sessions.Session requests.Session() 供调用解锁 resp : requests.models.Response requests 访问页面返回的,已经跳转了 img : bytes 验证码图片二进制数据 identify_image_callback : callable 处理验证码函数,输入验证码二进制数...
[ "手动打码解锁" ]
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/identify_image.py#L34-L76
train
Chyroc/WechatSogou
wechatsogou/identify_image.py
unlock_weixin_callback_example
def unlock_weixin_callback_example(url, req, resp, img, identify_image_callback): """手动打码解锁 Parameters ---------- url : str or unicode 验证码页面 之前的 url req : requests.sessions.Session requests.Session() 供调用解锁 resp : requests.models.Response requests 访问页面返回的,已经跳转了 img : ...
python
def unlock_weixin_callback_example(url, req, resp, img, identify_image_callback): """手动打码解锁 Parameters ---------- url : str or unicode 验证码页面 之前的 url req : requests.sessions.Session requests.Session() 供调用解锁 resp : requests.models.Response requests 访问页面返回的,已经跳转了 img : ...
[ "def", "unlock_weixin_callback_example", "(", "url", ",", "req", ",", "resp", ",", "img", ",", "identify_image_callback", ")", ":", "# no use resp", "unlock_url", "=", "'https://mp.weixin.qq.com/mp/verifycode'", "data", "=", "{", "'cert'", ":", "time", ".", "time", ...
手动打码解锁 Parameters ---------- url : str or unicode 验证码页面 之前的 url req : requests.sessions.Session requests.Session() 供调用解锁 resp : requests.models.Response requests 访问页面返回的,已经跳转了 img : bytes 验证码图片二进制数据 identify_image_callback : callable 处理验证码函数,输入验证码二进制数...
[ "手动打码解锁" ]
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/identify_image.py#L79-L121
train
Chyroc/WechatSogou
wechatsogou/request.py
WechatSogouRequest.gen_search_article_url
def gen_search_article_url(keyword, page=1, timesn=WechatSogouConst.search_article_time.anytime, article_type=WechatSogouConst.search_article_type.all, ft=None, et=None): """拼接搜索 文章 URL Parameters ---------- keyword : str or unicode 搜索文字 ...
python
def gen_search_article_url(keyword, page=1, timesn=WechatSogouConst.search_article_time.anytime, article_type=WechatSogouConst.search_article_type.all, ft=None, et=None): """拼接搜索 文章 URL Parameters ---------- keyword : str or unicode 搜索文字 ...
[ "def", "gen_search_article_url", "(", "keyword", ",", "page", "=", "1", ",", "timesn", "=", "WechatSogouConst", ".", "search_article_time", ".", "anytime", ",", "article_type", "=", "WechatSogouConst", ".", "search_article_type", ".", "all", ",", "ft", "=", "Non...
拼接搜索 文章 URL Parameters ---------- keyword : str or unicode 搜索文字 page : int, optional 页数 the default is 1 timesn : WechatSogouConst.search_article_time 时间 anytime 没有限制 / day 一天 / week 一周 / month 一月 / year 一年 / specific 自定 默认是 anytim...
[ "拼接搜索", "文章", "URL" ]
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/request.py#L17-L86
train
Chyroc/WechatSogou
wechatsogou/request.py
WechatSogouRequest.gen_search_gzh_url
def gen_search_gzh_url(keyword, page=1): """拼接搜索 公众号 URL Parameters ---------- keyword : str or unicode 搜索文字 page : int, optional 页数 the default is 1 Returns ------- str search_gzh_url """ assert isinst...
python
def gen_search_gzh_url(keyword, page=1): """拼接搜索 公众号 URL Parameters ---------- keyword : str or unicode 搜索文字 page : int, optional 页数 the default is 1 Returns ------- str search_gzh_url """ assert isinst...
[ "def", "gen_search_gzh_url", "(", "keyword", ",", "page", "=", "1", ")", ":", "assert", "isinstance", "(", "page", ",", "int", ")", "and", "page", ">", "0", "qs_dict", "=", "OrderedDict", "(", ")", "qs_dict", "[", "'type'", "]", "=", "_search_type_gzh", ...
拼接搜索 公众号 URL Parameters ---------- keyword : str or unicode 搜索文字 page : int, optional 页数 the default is 1 Returns ------- str search_gzh_url
[ "拼接搜索", "公众号", "URL" ]
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/request.py#L89-L112
train
Chyroc/WechatSogou
wechatsogou/request.py
WechatSogouRequest.gen_hot_url
def gen_hot_url(hot_index, page=1): """拼接 首页热门文章 URL Parameters ---------- hot_index : WechatSogouConst.hot_index 首页热门文章的分类(常量):WechatSogouConst.hot_index.xxx page : int 页数 Returns ------- str 热门文章分类的url """ ...
python
def gen_hot_url(hot_index, page=1): """拼接 首页热门文章 URL Parameters ---------- hot_index : WechatSogouConst.hot_index 首页热门文章的分类(常量):WechatSogouConst.hot_index.xxx page : int 页数 Returns ------- str 热门文章分类的url """ ...
[ "def", "gen_hot_url", "(", "hot_index", ",", "page", "=", "1", ")", ":", "assert", "hasattr", "(", "WechatSogouConst", ".", "hot_index", ",", "hot_index", ")", "assert", "isinstance", "(", "page", ",", "int", ")", "and", "page", ">", "0", "index_urls", "...
拼接 首页热门文章 URL Parameters ---------- hot_index : WechatSogouConst.hot_index 首页热门文章的分类(常量):WechatSogouConst.hot_index.xxx page : int 页数 Returns ------- str 热门文章分类的url
[ "拼接", "首页热门文章", "URL" ]
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/request.py#L115-L158
train
Chyroc/WechatSogou
wechatsogou/tools.py
get_first_of_element
def get_first_of_element(element, sub, contype=None): """抽取lxml.etree库中elem对象中文字 Args: element: lxml.etree.Element sub: str Returns: elem中文字 """ content = element.xpath(sub) return list_or_empty(content, contype)
python
def get_first_of_element(element, sub, contype=None): """抽取lxml.etree库中elem对象中文字 Args: element: lxml.etree.Element sub: str Returns: elem中文字 """ content = element.xpath(sub) return list_or_empty(content, contype)
[ "def", "get_first_of_element", "(", "element", ",", "sub", ",", "contype", "=", "None", ")", ":", "content", "=", "element", ".", "xpath", "(", "sub", ")", "return", "list_or_empty", "(", "content", ",", "contype", ")" ]
抽取lxml.etree库中elem对象中文字 Args: element: lxml.etree.Element sub: str Returns: elem中文字
[ "抽取lxml", ".", "etree库中elem对象中文字" ]
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/tools.py#L46-L57
train
Chyroc/WechatSogou
wechatsogou/tools.py
get_encoding_from_reponse
def get_encoding_from_reponse(r): """获取requests库get或post返回的对象编码 Args: r: requests库get或post返回的对象 Returns: 对象编码 """ encoding = requests.utils.get_encodings_from_content(r.text) return encoding[0] if encoding else requests.utils.get_encoding_from_headers(r.headers)
python
def get_encoding_from_reponse(r): """获取requests库get或post返回的对象编码 Args: r: requests库get或post返回的对象 Returns: 对象编码 """ encoding = requests.utils.get_encodings_from_content(r.text) return encoding[0] if encoding else requests.utils.get_encoding_from_headers(r.headers)
[ "def", "get_encoding_from_reponse", "(", "r", ")", ":", "encoding", "=", "requests", ".", "utils", ".", "get_encodings_from_content", "(", "r", ".", "text", ")", "return", "encoding", "[", "0", "]", "if", "encoding", "else", "requests", ".", "utils", ".", ...
获取requests库get或post返回的对象编码 Args: r: requests库get或post返回的对象 Returns: 对象编码
[ "获取requests库get或post返回的对象编码" ]
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/tools.py#L60-L70
train
Chyroc/WechatSogou
wechatsogou/tools.py
_replace_str_html
def _replace_str_html(s): """替换html‘&quot;’等转义内容为正常内容 Args: s: 文字内容 Returns: s: 处理反转义后的文字 """ html_str_list = [ ('&#39;', '\''), ('&quot;', '"'), ('&amp;', '&'), ('&yen;', '¥'), ('amp;', ''), ('&lt;', '<'), ('&gt;', '>'), ...
python
def _replace_str_html(s): """替换html‘&quot;’等转义内容为正常内容 Args: s: 文字内容 Returns: s: 处理反转义后的文字 """ html_str_list = [ ('&#39;', '\''), ('&quot;', '"'), ('&amp;', '&'), ('&yen;', '¥'), ('amp;', ''), ('&lt;', '<'), ('&gt;', '>'), ...
[ "def", "_replace_str_html", "(", "s", ")", ":", "html_str_list", "=", "[", "(", "'&#39;'", ",", "'\\''", ")", ",", "(", "'&quot;'", ",", "'\"'", ")", ",", "(", "'&amp;'", ",", "'&'", ")", ",", "(", "'&yen;'", ",", "'¥')", ",", "", "(", "'amp;'", ...
替换html‘&quot;’等转义内容为正常内容 Args: s: 文字内容 Returns: s: 处理反转义后的文字
[ "替换html‘&quot", ";", "’等转义内容为正常内容" ]
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/tools.py#L73-L95
train
Chyroc/WechatSogou
wechatsogou/structuring.py
WechatSogouStructuring.get_gzh_by_search
def get_gzh_by_search(text): """从搜索公众号获得的文本 提取公众号信息 Parameters ---------- text : str or unicode 搜索公众号获得的文本 Returns ------- list[dict] { 'open_id': '', # 微信号唯一ID 'profile_url': '', # 最近10条群发页链接 ...
python
def get_gzh_by_search(text): """从搜索公众号获得的文本 提取公众号信息 Parameters ---------- text : str or unicode 搜索公众号获得的文本 Returns ------- list[dict] { 'open_id': '', # 微信号唯一ID 'profile_url': '', # 最近10条群发页链接 ...
[ "def", "get_gzh_by_search", "(", "text", ")", ":", "post_view_perms", "=", "WechatSogouStructuring", ".", "__get_post_view_perm", "(", "text", ")", "page", "=", "etree", ".", "HTML", "(", "text", ")", "lis", "=", "page", ".", "xpath", "(", "'//ul[@class=\"news...
从搜索公众号获得的文本 提取公众号信息 Parameters ---------- text : str or unicode 搜索公众号获得的文本 Returns ------- list[dict] { 'open_id': '', # 微信号唯一ID 'profile_url': '', # 最近10条群发页链接 'headimage': '', # 头像 ...
[ "从搜索公众号获得的文本", "提取公众号信息" ]
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/structuring.py#L46-L104
train
Chyroc/WechatSogou
wechatsogou/structuring.py
WechatSogouStructuring.get_article_by_search
def get_article_by_search(text): """从搜索文章获得的文本 提取章列表信息 Parameters ---------- text : str or unicode 搜索文章获得的文本 Returns ------- list[dict] { 'article': { 'title': '', # 文章标题 'url': '',...
python
def get_article_by_search(text): """从搜索文章获得的文本 提取章列表信息 Parameters ---------- text : str or unicode 搜索文章获得的文本 Returns ------- list[dict] { 'article': { 'title': '', # 文章标题 'url': '',...
[ "def", "get_article_by_search", "(", "text", ")", ":", "page", "=", "etree", ".", "HTML", "(", "text", ")", "lis", "=", "page", ".", "xpath", "(", "'//ul[@class=\"news-list\"]/li'", ")", "articles", "=", "[", "]", "for", "li", "in", "lis", ":", "url", ...
从搜索文章获得的文本 提取章列表信息 Parameters ---------- text : str or unicode 搜索文章获得的文本 Returns ------- list[dict] { 'article': { 'title': '', # 文章标题 'url': '', # 文章链接 'imgs': '', # ...
[ "从搜索文章获得的文本", "提取章列表信息" ]
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/structuring.py#L136-L215
train
Chyroc/WechatSogou
wechatsogou/structuring.py
WechatSogouStructuring.get_gzh_info_by_history
def get_gzh_info_by_history(text): """从 历史消息页的文本 提取公众号信息 Parameters ---------- text : str or unicode 历史消息页的文本 Returns ------- dict { 'wechat_name': '', # 名称 'wechat_id': '', # 微信id 'introd...
python
def get_gzh_info_by_history(text): """从 历史消息页的文本 提取公众号信息 Parameters ---------- text : str or unicode 历史消息页的文本 Returns ------- dict { 'wechat_name': '', # 名称 'wechat_id': '', # 微信id 'introd...
[ "def", "get_gzh_info_by_history", "(", "text", ")", ":", "page", "=", "etree", ".", "HTML", "(", "text", ")", "profile_area", "=", "get_first_of_element", "(", "page", ",", "'//div[@class=\"profile_info_area\"]'", ")", "profile_img", "=", "get_first_of_element", "("...
从 历史消息页的文本 提取公众号信息 Parameters ---------- text : str or unicode 历史消息页的文本 Returns ------- dict { 'wechat_name': '', # 名称 'wechat_id': '', # 微信id 'introduction': '', # 描述 'authentica...
[ "从", "历史消息页的文本", "提取公众号信息" ]
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/structuring.py#L218-L253
train
Chyroc/WechatSogou
wechatsogou/structuring.py
WechatSogouStructuring.get_article_by_history_json
def get_article_by_history_json(text, article_json=None): """从 历史消息页的文本 提取文章列表信息 Parameters ---------- text : str or unicode 历史消息页的文本 article_json : dict 历史消息页的文本 提取出来的文章json dict Returns ------- list[dict] { ...
python
def get_article_by_history_json(text, article_json=None): """从 历史消息页的文本 提取文章列表信息 Parameters ---------- text : str or unicode 历史消息页的文本 article_json : dict 历史消息页的文本 提取出来的文章json dict Returns ------- list[dict] { ...
[ "def", "get_article_by_history_json", "(", "text", ",", "article_json", "=", "None", ")", ":", "if", "article_json", "is", "None", ":", "article_json", "=", "find_article_json_re", ".", "findall", "(", "text", ")", "if", "not", "article_json", ":", "return", "...
从 历史消息页的文本 提取文章列表信息 Parameters ---------- text : str or unicode 历史消息页的文本 article_json : dict 历史消息页的文本 提取出来的文章json dict Returns ------- list[dict] { 'send_id': '', # 群发id,注意不唯一,因为同一次群发多个消息,而群发id一致 ...
[ "从", "历史消息页的文本", "提取文章列表信息" ]
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/structuring.py#L256-L334
train
Chyroc/WechatSogou
wechatsogou/structuring.py
WechatSogouStructuring.get_gzh_article_by_hot
def get_gzh_article_by_hot(text): """从 首页热门搜索 提取公众号信息 和 文章列表信息 Parameters ---------- text : str or unicode 首页热门搜索 页 中 某一页 的文本 Returns ------- list[dict] { 'gzh': { 'headimage': str, # 公众号头像 ...
python
def get_gzh_article_by_hot(text): """从 首页热门搜索 提取公众号信息 和 文章列表信息 Parameters ---------- text : str or unicode 首页热门搜索 页 中 某一页 的文本 Returns ------- list[dict] { 'gzh': { 'headimage': str, # 公众号头像 ...
[ "def", "get_gzh_article_by_hot", "(", "text", ")", ":", "page", "=", "etree", ".", "HTML", "(", "text", ")", "lis", "=", "page", ".", "xpath", "(", "'/html/body/li'", ")", "gzh_article_list", "=", "[", "]", "for", "li", "in", "lis", ":", "url", "=", ...
从 首页热门搜索 提取公众号信息 和 文章列表信息 Parameters ---------- text : str or unicode 首页热门搜索 页 中 某一页 的文本 Returns ------- list[dict] { 'gzh': { 'headimage': str, # 公众号头像 'wechat_name': str, # 公众号名称 ...
[ "从", "首页热门搜索", "提取公众号信息", "和", "文章列表信息" ]
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/structuring.py#L381-L441
train
Chyroc/WechatSogou
wechatsogou/structuring.py
WechatSogouStructuring.get_article_detail
def get_article_detail(text, del_qqmusic=True, del_voice=True): """根据微信文章的临时链接获取明细 1. 获取文本中所有的图片链接列表 2. 获取微信文章的html内容页面(去除标题等信息) Parameters ---------- text : str or unicode 一篇微信文章的文本 del_qqmusic: bool 删除文章中的qq音乐 del_voice: bool ...
python
def get_article_detail(text, del_qqmusic=True, del_voice=True): """根据微信文章的临时链接获取明细 1. 获取文本中所有的图片链接列表 2. 获取微信文章的html内容页面(去除标题等信息) Parameters ---------- text : str or unicode 一篇微信文章的文本 del_qqmusic: bool 删除文章中的qq音乐 del_voice: bool ...
[ "def", "get_article_detail", "(", "text", ",", "del_qqmusic", "=", "True", ",", "del_voice", "=", "True", ")", ":", "# 1. 获取微信文本content", "html_obj", "=", "BeautifulSoup", "(", "text", ",", "\"lxml\"", ")", "content_text", "=", "html_obj", ".", "find", "(", ...
根据微信文章的临时链接获取明细 1. 获取文本中所有的图片链接列表 2. 获取微信文章的html内容页面(去除标题等信息) Parameters ---------- text : str or unicode 一篇微信文章的文本 del_qqmusic: bool 删除文章中的qq音乐 del_voice: bool 删除文章中的语音内容 Returns ------- dict ...
[ "根据微信文章的临时链接获取明细" ]
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/structuring.py#L444-L527
train