partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
verify_callable_argspec
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 ...
zipline/utils/argcheck.py
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): """ Checks the callable_ to make sure that it satisfies the given expectations. expec...
[ "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...
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/argcheck.py#L143-L222
[ "def", "verify_callable_argspec", "(", "callable_", ",", "expected_args", "=", "Argument", ".", "ignore", ",", "expect_starargs", "=", "Argument", ".", "ignore", ",", "expect_kwargs", "=", "Argument", ".", "ignore", ")", ":", "if", "not", "callable", "(", "cal...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
Argument.parse_argspec
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.
zipline/utils/argcheck.py
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_): """ 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: ...
[ "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...
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/argcheck.py#L98-L120
[ "def", "parse_argspec", "(", "callable_", ")", ":", "args", ",", "varargs", ",", "keywords", ",", "defaults", "=", "getargspec", "(", "callable_", ")", "defaults", "=", "list", "(", "defaults", "or", "[", "]", ")", "if", "getattr", "(", "callable_", ",",...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
StaticRestrictions.is_restricted
An asset is restricted for all dts if it is in the static list.
zipline/finance/asset_restrictions.py
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): """ 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...
[ "An", "asset", "is", "restricted", "for", "all", "dts", "if", "it", "is", "in", "the", "static", "list", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/asset_restrictions.py#L143-L152
[ "def", "is_restricted", "(", "self", ",", "assets", ",", "dt", ")", ":", "if", "isinstance", "(", "assets", ",", "Asset", ")", ":", "return", "assets", "in", "self", ".", "_restricted_set", "return", "pd", ".", "Series", "(", "index", "=", "pd", ".", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
HistoricalRestrictions.is_restricted
Returns whether or not an asset or iterable of assets is restricted on a dt.
zipline/finance/asset_restrictions.py
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): """ 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=...
[ "Returns", "whether", "or", "not", "an", "asset", "or", "iterable", "of", "assets", "is", "restricted", "on", "a", "dt", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/asset_restrictions.py#L177-L189
[ "def", "is_restricted", "(", "self", ",", "assets", ",", "dt", ")", ":", "if", "isinstance", "(", "assets", ",", "Asset", ")", ":", "return", "self", ".", "_is_restricted_for_asset", "(", "assets", ",", "dt", ")", "is_restricted", "=", "partial", "(", "s...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
PositionTracker.handle_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 shares after modifying each pos...
zipline/finance/ledger.py
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): """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...
[ "Processes", "a", "list", "of", "splits", "by", "modifying", "any", "positions", "as", "needed", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/ledger.py#L114-L139
[ "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...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
PositionTracker.earn_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 of (asset, amount, pay_date) namedtuples stock_dividends: it...
zipline/finance/ledger.py
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): """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...
[ "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...
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/ledger.py#L141-L179
[ "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...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
PositionTracker.pay_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.
zipline/finance/ledger.py
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): """ 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...
[ "Returns", "a", "cash", "payment", "based", "on", "the", "dividends", "that", "should", "be", "paid", "out", "according", "to", "the", "accumulated", "bookkeeping", "of", "earned", "unpaid", "and", "stock", "dividends", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/ledger.py#L181-L222
[ "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", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
PositionTracker.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.
zipline/finance/ledger.py
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): """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", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/ledger.py#L288-L305
[ "def", "stats", "(", "self", ")", ":", "if", "self", ".", "_dirty_stats", ":", "calculate_position_tracker_stats", "(", "self", ".", "positions", ",", "self", ".", "_stats", ")", "self", ".", "_dirty_stats", "=", "False", "return", "self", ".", "_stats" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
Ledger.process_transaction
Add a transaction to ledger, updating the current state as needed. Parameters ---------- transaction : zp.Transaction The transaction to execute.
zipline/finance/ledger.py
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): """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)...
[ "Add", "a", "transaction", "to", "ledger", "updating", "the", "current", "state", "as", "needed", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/ledger.py#L479-L523
[ "def", "process_transaction", "(", "self", ",", "transaction", ")", ":", "asset", "=", "transaction", ".", "asset", "if", "isinstance", "(", "asset", ",", "Future", ")", ":", "try", ":", "old_price", "=", "self", ".", "_payout_last_sale_prices", "[", "asset"...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
Ledger.process_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).
zipline/finance/ledger.py
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): """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...
[ "Processes", "a", "list", "of", "splits", "by", "modifying", "any", "positions", "as", "needed", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/ledger.py#L525-L535
[ "def", "process_splits", "(", "self", ",", "splits", ")", ":", "leftover_cash", "=", "self", ".", "position_tracker", ".", "handle_splits", "(", "splits", ")", "if", "leftover_cash", ">", "0", ":", "self", ".", "_cash_flow", "(", "leftover_cash", ")" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
Ledger.process_order
Keep track of an order that was placed. Parameters ---------- order : zp.Order The order to record.
zipline/finance/ledger.py
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): """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...
[ "Keep", "track", "of", "an", "order", "that", "was", "placed", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/ledger.py#L537-L557
[ "def", "process_order", "(", "self", ",", "order", ")", ":", "try", ":", "dt_orders", "=", "self", ".", "_orders_by_modified", "[", "order", ".", "dt", "]", "except", "KeyError", ":", "self", ".", "_orders_by_modified", "[", "order", ".", "dt", "]", "=",...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
Ledger.process_commission
Process the commission. Parameters ---------- commission : zp.Event The commission being paid.
zipline/finance/ledger.py
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): """Process the commission. Parameters ---------- commission : zp.Event The commission being paid. """ asset = commission['asset'] cost = commission['cost'] self.position_tracker.handle_commission(asse...
[ "Process", "the", "commission", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/ledger.py#L559-L571
[ "def", "process_commission", "(", "self", ",", "commission", ")", ":", "asset", "=", "commission", "[", "'asset'", "]", "cost", "=", "commission", "[", "'cost'", "]", "self", ".", "position_tracker", ".", "handle_commission", "(", "asset", ",", "cost", ")", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
Ledger.process_dividends
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
zipline/finance/ledger.py
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): """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 = ...
[ "Process", "dividends", "for", "the", "next", "session", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/ledger.py#L582-L621
[ "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...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
Ledger.transactions
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...
zipline/finance/ledger.py
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): """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, ...
[ "Retrieve", "the", "dict", "-", "form", "of", "all", "of", "the", "transactions", "in", "a", "given", "bar", "or", "for", "the", "whole", "simulation", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/ledger.py#L631-L655
[ "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...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
Ledger.orders
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 ...
zipline/finance/ledger.py
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): """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...
[ "Retrieve", "the", "dict", "-", "form", "of", "all", "of", "the", "orders", "in", "a", "given", "bar", "or", "for", "the", "whole", "simulation", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/ledger.py#L657-L679
[ "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", ")", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
Ledger.update_portfolio
Force a computation of the current portfolio state.
zipline/finance/ledger.py
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): """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 ...
[ "Force", "a", "computation", "of", "the", "current", "portfolio", "state", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/ledger.py#L703-L740
[ "def", "update_portfolio", "(", "self", ")", ":", "if", "not", "self", ".", "_dirty_portfolio", ":", "return", "portfolio", "=", "self", ".", "_portfolio", "pt", "=", "self", ".", "position_tracker", "portfolio", ".", "positions", "=", "pt", ".", "get_positi...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
Ledger.override_account_fields
Override fields on ``self.account``.
zipline/finance/ledger.py
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, to...
[ "Override", "fields", "on", "self", ".", "account", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/ledger.py#L766-L791
[ "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...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
datashape_type_to_numpy
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 ...
zipline/pipeline/loaders/blaze/core.py
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_): """ 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...
[ "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...
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/blaze/core.py#L246-L272
[ "def", "datashape_type_to_numpy", "(", "type_", ")", ":", "if", "isinstance", "(", "type_", ",", "Option", ")", ":", "type_", "=", "type_", ".", "ty", "if", "isinstance", "(", "type_", ",", "DateTime", ")", ":", "return", "np", ".", "dtype", "(", "'dat...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
new_dataset
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...
zipline/pipeline/loaders/blaze/core.py
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): """ 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...
[ "Creates", "or", "returns", "a", "dataset", "from", "a", "blaze", "expression", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/blaze/core.py#L276-L334
[ "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", "}",...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
_check_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 compute expr. Raises ------ ValueError ...
zipline/pipeline/loaders/blaze/core.py
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): """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...
[ "Validate", "that", "the", "expression", "and", "resources", "passed", "match", "up", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/blaze/core.py#L337-L362
[ "def", "_check_resources", "(", "name", ",", "expr", ",", "resources", ")", ":", "if", "expr", "is", "None", ":", "return", "bound", "=", "expr", ".", "_resources", "(", ")", "if", "not", "bound", "and", "resources", "is", "None", ":", "raise", "ValueE...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
_check_datetime_field
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``.
zipline/pipeline/loaders/blaze/core.py
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): """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...
[ "Check", "that", "a", "field", "is", "a", "datetime", "inside", "some", "measure", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/blaze/core.py#L365-L387
[ "def", "_check_datetime_field", "(", "name", ",", "measure", ")", ":", "if", "not", "isinstance", "(", "measure", "[", "name", "]", ",", "(", "Date", ",", "DateTime", ")", ")", ":", "raise", "TypeError", "(", "\"'{name}' field must be a '{dt}', not: '{dshape}'\"...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
_get_metadata
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...
zipline/pipeline/loaders/blaze/core.py
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): """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...
[ "Find", "the", "correct", "metadata", "expression", "for", "the", "expression", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/blaze/core.py#L415-L450
[ "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", ":"...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
_ensure_timestamp_field
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...
zipline/pipeline/loaders/blaze/core.py
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): """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...
[ "Verify", "that", "the", "baseline", "and", "deltas", "expressions", "have", "a", "timestamp", "field", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/blaze/core.py#L473-L505
[ "def", "_ensure_timestamp_field", "(", "dataset_expr", ",", "deltas", ",", "checkpoints", ")", ":", "measure", "=", "dataset_expr", ".", "dshape", ".", "measure", "if", "TS_FIELD_NAME", "not", "in", "measure", ".", "names", ":", "dataset_expr", "=", "bz", ".",...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
from_blaze
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 ...
zipline/pipeline/loaders/blaze/core.py
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, no_deltas_rule='warn', no_checkpoints_rule='wa...
[ "Create", "a", "Pipeline", "API", "object", "from", "a", "blaze", "expression", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/blaze/core.py#L512-L695
[ "def", "from_blaze", "(", "expr", ",", "deltas", "=", "'auto'", ",", "checkpoints", "=", "'auto'", ",", "loader", "=", "None", ",", "resources", "=", "None", ",", "odo_kwargs", "=", "None", ",", "missing_values", "=", "None", ",", "domain", "=", "GENERIC...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
bind_expression_to_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 resources. Returns ------- bound_expr : bz.Expr ...
zipline/pipeline/loaders/blaze/core.py
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 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...
[ "Bind", "a", "Blaze", "expression", "to", "resources", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/blaze/core.py#L1038-L1063
[ "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...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
get_materialized_checkpoints
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. ...
zipline/pipeline/loaders/blaze/core.py
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): """ 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...
[ "Computes", "a", "lower", "bound", "and", "a", "DataFrame", "checkpoints", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/blaze/core.py#L1066-L1105
[ "def", "get_materialized_checkpoints", "(", "checkpoints", ",", "colnames", ",", "lower_dt", ",", "odo_kwargs", ")", ":", "if", "checkpoints", "is", "not", "None", ":", "ts", "=", "checkpoints", "[", "TS_FIELD_NAME", "]", "checkpoints_ts", "=", "odo", "(", "ts...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
ffill_query_in_range
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. ...
zipline/pipeline/loaders/blaze/core.py
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): """Query a blaze expression in a given time range properly forward filling from va...
[ "Query", "a", "blaze", "expression", "in", "a", "given", "time", "range", "properly", "forward", "filling", "from", "values", "that", "fall", "before", "the", "lower", "date", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/blaze/core.py#L1108-L1165
[ "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", ",", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
BlazeLoader.register_dataset
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. ...
zipline/pipeline/loaders/blaze/core.py
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): """Explicitly map a datset to a collection of blaze expressions. Parameters ---...
[ "Explicitly", "map", "a", "datset", "to", "a", "collection", "of", "blaze", "expressions", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/blaze/core.py#L847-L879
[ "def", "register_dataset", "(", "self", ",", "dataset", ",", "expr", ",", "deltas", "=", "None", ",", "checkpoints", "=", "None", ",", "odo_kwargs", "=", "None", ")", ":", "expr_data", "=", "ExprData", "(", "expr", ",", "deltas", ",", "checkpoints", ",",...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
BlazeLoader.register_column
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 ...
zipline/pipeline/loaders/blaze/core.py
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): """Explicitly map a single bound column to a collection of blaze expressions. The expressions n...
[ "Explicitly", "map", "a", "single", "bound", "column", "to", "a", "collection", "of", "blaze", "expressions", ".", "The", "expressions", "need", "to", "have", "timestamp", "and", "as_of", "columns", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/blaze/core.py#L881-L913
[ "def", "register_column", "(", "self", ",", "column", ",", "expr", ",", "deltas", "=", "None", ",", "checkpoints", "=", "None", ",", "odo_kwargs", "=", "None", ")", ":", "self", ".", "_table_expressions", "[", "column", "]", "=", "ExprData", "(", "expr",...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
merge_ownership_periods
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...
zipline/assets/assets.py
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): """ 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...
[ "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...
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L104-L138
[ "def", "merge_ownership_periods", "(", "mappings", ")", ":", "return", "valmap", "(", "lambda", "v", ":", "tuple", "(", "OwnershipPeriod", "(", "a", ".", "start", ",", "b", ".", "start", ",", "a", ".", "sid", ",", "a", ".", "value", ",", ")", "for", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
build_ownership_map
Builds a dict mapping to lists of OwnershipPeriods, from a db table.
zipline/assets/assets.py
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): """ 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, )
[ "Builds", "a", "dict", "mapping", "to", "lists", "of", "OwnershipPeriods", "from", "a", "db", "table", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L159-L167
[ "def", "build_ownership_map", "(", "table", ",", "key_from_row", ",", "value_from_row", ")", ":", "return", "_build_ownership_map_from_rows", "(", "sa", ".", "select", "(", "table", ".", "c", ")", ".", "execute", "(", ")", ".", "fetchall", "(", ")", ",", "...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
build_grouped_ownership_map
Builds a dict mapping group keys to maps of keys to to lists of OwnershipPeriods, from a db table.
zipline/assets/assets.py
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): """ Builds a dict mapping group keys to maps of keys to to lists of OwnershipPeriods, from a db table. """ grouped_rows = g...
[ "Builds", "a", "dict", "mapping", "group", "keys", "to", "maps", "of", "keys", "to", "to", "lists", "of", "OwnershipPeriods", "from", "a", "db", "table", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L170-L189
[ "def", "build_grouped_ownership_map", "(", "table", ",", "key_from_row", ",", "value_from_row", ",", "group_key", ")", ":", "grouped_rows", "=", "groupby", "(", "group_key", ",", "sa", ".", "select", "(", "table", ".", "c", ")", ".", "execute", "(", ")", "...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
_filter_kwargs
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...
zipline/assets/assets.py
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_): """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...
[ "Filter", "out", "kwargs", "from", "a", "dictionary", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L193-L209
[ "def", "_filter_kwargs", "(", "names", ",", "dict_", ")", ":", "return", "{", "k", ":", "v", "for", "k", ",", "v", "in", "dict_", ".", "items", "(", ")", "if", "k", "in", "names", "and", "v", "is", "not", "None", "}" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
_convert_asset_timestamp_fields
Takes in a dict of Asset init args and converts dates to pd.Timestamps
zipline/assets/assets.py
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_): """ 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_
[ "Takes", "in", "a", "dict", "of", "Asset", "init", "args", "and", "converts", "dates", "to", "pd", ".", "Timestamps" ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L216-L223
[ "def", "_convert_asset_timestamp_fields", "(", "dict_", ")", ":", "for", "key", "in", "_asset_timestamp_fields", "&", "viewkeys", "(", "dict_", ")", ":", "value", "=", "pd", ".", "Timestamp", "(", "dict_", "[", "key", "]", ",", "tz", "=", "'UTC'", ")", "...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
was_active
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...
zipline/assets/assets.py
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): """ 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. ...
[ "Whether", "or", "not", "asset", "was", "active", "at", "the", "time", "corresponding", "to", "reference_date_value", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L1568-L1591
[ "def", "was_active", "(", "reference_date_value", ",", "asset", ")", ":", "return", "(", "asset", ".", "start_date", ".", "value", "<=", "reference_date_value", "<=", "asset", ".", "end_date", ".", "value", ")" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
AssetFinder.lookup_asset_types
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.
zipline/assets/assets.py
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): """ 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 = {} ...
[ "Retrieve", "asset", "types", "for", "a", "list", "of", "sids", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L405-L443
[ "def", "lookup_asset_types", "(", "self", ",", "sids", ")", ":", "found", "=", "{", "}", "missing", "=", "set", "(", ")", "for", "sid", "in", "sids", ":", "try", ":", "found", "[", "sid", "]", "=", "self", ".", "_asset_type_cache", "[", "sid", "]",...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
AssetFinder.retrieve_all
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...
zipline/assets/assets.py
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): """ 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...
[ "Retrieve", "all", "assets", "in", "sids", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L473-L539
[ "def", "retrieve_all", "(", "self", ",", "sids", ",", "default_none", "=", "False", ")", ":", "sids", "=", "list", "(", "sids", ")", "hits", ",", "missing", ",", "failures", "=", "{", "}", ",", "set", "(", ")", ",", "[", "]", "for", "sid", "in", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
AssetFinder._select_most_recent_symbols_chunk
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. ...
zipline/assets/assets.py
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): """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 ...
[ "Retrieve", "the", "most", "recent", "symbol", "for", "a", "set", "of", "sids", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L600-L647
[ "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", "(", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
AssetFinder._retrieve_assets
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...
zipline/assets/assets.py
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): """ 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...
[ "Internal", "function", "for", "loading", "assets", "from", "a", "table", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L689-L740
[ "def", "_retrieve_assets", "(", "self", ",", "sids", ",", "asset_tbl", ",", "asset_type", ")", ":", "# Fastpath for empty request.", "if", "not", "sids", ":", "return", "{", "}", "cache", "=", "self", ".", "_asset_cache", "hits", "=", "{", "}", "querying_equ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
AssetFinder._lookup_symbol_strict
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? ...
zipline/assets/assets.py
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): """ Resolve a symbol to an asset object without fuzzy matching. Parameters ---------...
[ "Resolve", "a", "symbol", "to", "an", "asset", "object", "without", "fuzzy", "matching", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L742-L865
[ "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", ","...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
AssetFinder.lookup_symbol
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 ...
zipline/assets/assets.py
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): """Lookup an equity by symbol. Parameters ---------- symbol : str The ticker symbol to resolve. as_of_...
[ "Lookup", "an", "equity", "by", "symbol", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L955-L1016
[ "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 ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
AssetFinder.lookup_symbols
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...
zipline/assets/assets.py
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): """ Lookup a list of equities by symbol. Equivalent to:: [finder.lookup_symbol(s, as_of, fuzzy) for s in symbol...
[ "Lookup", "a", "list", "of", "equities", "by", "symbol", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L1018-L1077
[ "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...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
AssetFinder.lookup_future_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``. Raises ------ SymbolNotFound ...
zipline/assets/assets.py
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): """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...
[ "Lookup", "a", "future", "contract", "by", "symbol", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L1079-L1105
[ "def", "lookup_future_symbol", "(", "self", ",", "symbol", ")", ":", "data", "=", "self", ".", "_select_asset_by_symbol", "(", "self", ".", "futures_contracts", ",", "symbol", ")", ".", "execute", "(", ")", ".", "fetchone", "(", ")", "# If no data found, raise...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
AssetFinder.get_supplementary_field
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...
zipline/assets/assets.py
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): """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...
[ "Get", "the", "value", "of", "a", "supplementary", "field", "for", "an", "asset", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L1142-L1193
[ "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...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
AssetFinder._lookup_generic_scalar
Convert asset_convertible to an asset. On success, append to matches. On failure, append to missing.
zipline/assets/assets.py
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): """ Convert asset_convertible to an asset. On success, ap...
[ "Convert", "asset_convertible", "to", "an", "asset", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L1298-L1316
[ "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", ",", ")...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
AssetFinder.lookup_generic
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...
zipline/assets/assets.py
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): """ 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...
[ "Convert", "an", "object", "into", "an", "Asset", "or", "sequence", "of", "Assets", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L1347-L1414
[ "def", "lookup_generic", "(", "self", ",", "obj", ",", "as_of_date", ",", "country_code", ")", ":", "matches", "=", "[", "]", "missing", "=", "[", "]", "# Interpret input as scalar.", "if", "isinstance", "(", "obj", ",", "(", "AssetConvertible", ",", "Contin...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
AssetFinder._compute_asset_lifetimes
Compute and cache a recarray of asset lifetimes.
zipline/assets/assets.py
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): """ 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...
[ "Compute", "and", "cache", "a", "recarray", "of", "asset", "lifetimes", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L1416-L1456
[ "def", "_compute_asset_lifetimes", "(", "self", ",", "country_codes", ")", ":", "equities_cols", "=", "self", ".", "equities", ".", "c", "if", "country_codes", ":", "buf", "=", "np", ".", "array", "(", "tuple", "(", "sa", ".", "select", "(", "(", "equiti...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
AssetFinder.lifetimes
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....
zipline/assets/assets.py
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): """ 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...
[ "Compute", "a", "DataFrame", "representing", "asset", "lifetimes", "for", "the", "specified", "date", "range", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L1458-L1514
[ "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 \"", "...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
AssetFinder.equities_sids_for_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 this country.
zipline/assets/assets.py
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): """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...
[ "Return", "all", "of", "the", "sids", "for", "a", "given", "country", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L1516-L1530
[ "def", "equities_sids_for_country_code", "(", "self", ",", "country_code", ")", ":", "sids", "=", "self", ".", "_compute_asset_lifetimes", "(", "[", "country_code", "]", ")", ".", "sid", "return", "tuple", "(", "sids", ".", "tolist", "(", ")", ")" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
ContinuousFutureSessionBarReader.load_raw_arrays
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 ------- ...
zipline/data/continuous_future_reader.py
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): """ 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...
[ "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",...
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/continuous_future_reader.py#L12-L96
[ "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...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
ContinuousFutureSessionBarReader.get_value
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 -...
zipline/data/continuous_future_reader.py
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): """ 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 ...
[ "Retrieve", "the", "value", "at", "the", "given", "coordinates", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/continuous_future_reader.py#L127-L156
[ "def", "get_value", "(", "self", ",", "continuous_future", ",", "dt", ",", "field", ")", ":", "rf", "=", "self", ".", "_roll_finders", "[", "continuous_future", ".", "roll_style", "]", "sid", "=", "(", "rf", ".", "get_contract_center", "(", "continuous_futur...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
ContinuousFutureSessionBarReader.get_last_traded_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...
zipline/data/continuous_future_reader.py
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): """ 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...
[ "Get", "the", "latest", "minute", "on", "or", "before", "dt", "in", "which", "asset", "traded", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/continuous_future_reader.py#L158-L184
[ "def", "get_last_traded_dt", "(", "self", ",", "asset", ",", "dt", ")", ":", "rf", "=", "self", ".", "_roll_finders", "[", "asset", ".", "roll_style", "]", "sid", "=", "(", "rf", ".", "get_contract_center", "(", "asset", ".", "root_symbol", ",", "dt", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
ContinuousFutureMinuteBarReader.load_raw_arrays
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....
zipline/data/continuous_future_reader.py
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): """ 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...
[ "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",...
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/continuous_future_reader.py#L204-L282
[ "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", "(", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
Portfolio.current_portfolio_weights
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.
zipline/protocol.py
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): """ 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...
[ "Compute", "each", "asset", "s", "weight", "in", "the", "portfolio", "by", "calculating", "its", "held", "value", "divided", "by", "the", "total", "value", "of", "all", "positions", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/protocol.py#L216-L233
[ "def", "current_portfolio_weights", "(", "self", ")", ":", "position_values", "=", "pd", ".", "Series", "(", "{", "asset", ":", "(", "position", ".", "last_sale_price", "*", "position", ".", "amount", "*", "asset", ".", "price_multiplier", ")", "for", "asset...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
WechatSogouAPI.__hosting_wechat_img
将微信明细中图片托管到云端,同时将html页面中的对应图片替换 Parameters ---------- content_info : dict 微信文章明细字典 { 'content_img_list': [], # 从微信文章解析出的原始图片列表 'content_html': '', # 从微信文章解析出文章的内容 } hosting_callback : callable 托管回调函数,传入单个图片链接,返回托管后的图片链接...
wechatsogou/api.py
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): """将微信明细中图片托管到云端,同时将html页面中的对应图片替换 Parameters ---------- content_info : dict 微信文章明细字典 { 'content_img_list': [], # 从微信文章解析出的原始图片列表 'content_html': '', # 从微信文章解析出文章的内容 }...
[ "将微信明细中图片托管到云端,同时将html页面中的对应图片替换" ]
Chyroc/WechatSogou
python
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/api.py#L138-L171
[ "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...
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
train
WechatSogouAPI.get_gzh_info
获取公众号微信号 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 ...
wechatsogou/api.py
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): """获取公众号微信号 wechatid 的信息 因为wechatid唯一确定,所以第一个就是要搜索的公众号 Parameters ---------- wecgat_id_or_name : str or unicode wechat_id or wechat_name unlock_ca...
[ "获取公众号微信号", "wechatid", "的信息" ]
Chyroc/WechatSogou
python
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/api.py#L208-L241
[ "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"...
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
train
WechatSogouAPI.search_gzh
搜索 公众号 对于出现验证码的情况,可以由使用者自己提供: 1、函数 unlock_callback ,这个函数 handle 出现验证码到解决的整个流程 2、也可以 只提供函数 identify_image_callback,这个函数输入验证码二进制数据,输出验证码文字,剩下的由 wechatsogou 包来解决 注意: 函数 unlock_callback 和 identify_image_callback 只需要提供一个,如果都提供了,那么 identify_image_callback 不起作用 Par...
wechatsogou/api.py
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): """搜索 公众号 对于出现验证码的情况,可以由使用者自己提供: 1、函数 unlock_callback ,这个函数 handle 出现验证码到解决的整个流程 2、也可以 只提供函数 identify_image_callback,这个函数输入验证码二进制数据,输出验证码文字,剩下的由 wechatsogou 包来解决 注...
[ "搜索", "公众号" ]
Chyroc/WechatSogou
python
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/api.py#L243-L296
[ "def", "search_gzh", "(", "self", ",", "keyword", ",", "page", "=", "1", ",", "unlock_callback", "=", "None", ",", "identify_image_callback", "=", "None", ",", "decode_url", "=", "True", ")", ":", "url", "=", "WechatSogouRequest", ".", "gen_search_gzh_url", ...
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
train
WechatSogouAPI.search_article
搜索 文章 对于出现验证码的情况,可以由使用者自己提供: 1、函数 unlock_callback ,这个函数 handle 出现验证码到解决的整个流程 2、也可以 只提供函数 identify_image_callback,这个函数输入验证码二进制数据,输出验证码文字,剩下的由 wechatsogou 包来解决 注意: 函数 unlock_callback 和 identify_image_callback 只需要提供一个,如果都提供了,那么 identify_image_callback 不起作用 Para...
wechatsogou/api.py
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=None, et=None, unlock_callback=None, identify_image_callback=None, decode_u...
[ "搜索", "文章" ]
Chyroc/WechatSogou
python
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/api.py#L298-L369
[ "def", "search_article", "(", "self", ",", "keyword", ",", "page", "=", "1", ",", "timesn", "=", "WechatSogouConst", ".", "search_article_time", ".", "anytime", ",", "article_type", "=", "WechatSogouConst", ".", "search_article_type", ".", "all", ",", "ft", "=...
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
train
WechatSogouAPI.get_gzh_article_by_history
从 公众号的最近10条群发页面 提取公众号信息 和 文章列表信息 对于出现验证码的情况,可以由使用者自己提供: 1、函数 unlock_callback ,这个函数 handle 出现验证码到解决的整个流程 2、也可以 只提供函数 identify_image_callback,这个函数输入验证码二进制数据,输出验证码文字,剩下的由 wechatsogou 包来解决 注意: 函数 unlock_callback 和 identify_image_callback 只需要提供一个,如果都提供了,那么 identify_image_...
wechatsogou/api.py
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_callback_we...
[ "从", "公众号的最近10条群发页面", "提取公众号信息", "和", "文章列表信息" ]
Chyroc/WechatSogou
python
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/api.py#L371-L448
[ "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...
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
train
WechatSogouAPI.get_gzh_article_by_hot
获取 首页热门文章 Parameters ---------- hot_index : WechatSogouConst.hot_index 首页热门文章的分类(常量):WechatSogouConst.hot_index.xxx page : int 页数 Returns ------- list[dict] { 'gzh': { 'headimage': str, # 公...
wechatsogou/api.py
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): """获取 首页热门文章 Parameters ---------- hot_index : WechatSogouConst.hot_index 首页热门文章的分类(常量):WechatSogouConst.hot_index.xxx page : int 页数 Returns ...
[ "获取", "首页热门文章" ]
Chyroc/WechatSogou
python
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/api.py#L450-L489
[ "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", ...
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
train
WechatSogouAPI.get_article_content
获取文章原文,避免临时链接失效 Parameters ---------- url : str or unicode 原文链接,临时链接 raw : bool True: 返回原始html False: 返回处理后的html del_qqmusic: bool True:微信原文中有插入的qq音乐,则删除 False:微信源文中有插入的qq音乐,则保留 del_mpvoice: bool Tru...
wechatsogou/api.py
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=False): """获取文章原文,避免临时链接失效 Parameters ---------- url : str or unicode 原文链接,临时链接 raw : boo...
[ "获取文章原文,避免临时链接失效" ]
Chyroc/WechatSogou
python
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/api.py#L491-L541
[ "def", "get_article_content", "(", "self", ",", "url", ",", "del_qqmusic", "=", "True", ",", "del_mpvoice", "=", "True", ",", "unlock_callback", "=", "None", ",", "identify_image_callback", "=", "None", ",", "hosting_callback", "=", "None", ",", "raw", "=", ...
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
train
WechatSogouAPI.get_sugg
获取微信搜狗搜索关键词联想 Parameters ---------- keyword : str or unicode 关键词 Returns ------- list[str] 联想关键词列表 Raises ------ WechatSogouRequestsException
wechatsogou/api.py
def get_sugg(self, keyword): """获取微信搜狗搜索关键词联想 Parameters ---------- keyword : str or unicode 关键词 Returns ------- list[str] 联想关键词列表 Raises ------ WechatSogouRequestsException """ url = 'http://w.sug...
def get_sugg(self, keyword): """获取微信搜狗搜索关键词联想 Parameters ---------- keyword : str or unicode 关键词 Returns ------- list[str] 联想关键词列表 Raises ------ WechatSogouRequestsException """ url = 'http://w.sug...
[ "获取微信搜狗搜索关键词联想" ]
Chyroc/WechatSogou
python
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/api.py#L543-L567
[ "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", ".", ...
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
train
unlock_sogou_callback_example
手动打码解锁 Parameters ---------- url : str or unicode 验证码页面 之前的 url req : requests.sessions.Session requests.Session() 供调用解锁 resp : requests.models.Response requests 访问页面返回的,已经跳转了 img : bytes 验证码图片二进制数据 identify_image_callback : callable 处理验证码函数,输入验证码二进制数...
wechatsogou/identify_image.py
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): """手动打码解锁 Parameters ---------- url : str or unicode 验证码页面 之前的 url req : requests.sessions.Session requests.Session() 供调用解锁 resp : requests.models.Response requests 访问页面返回的,已经跳转了 img : b...
[ "手动打码解锁" ]
Chyroc/WechatSogou
python
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/identify_image.py#L34-L76
[ "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", "=", ...
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
train
unlock_weixin_callback_example
手动打码解锁 Parameters ---------- url : str or unicode 验证码页面 之前的 url req : requests.sessions.Session requests.Session() 供调用解锁 resp : requests.models.Response requests 访问页面返回的,已经跳转了 img : bytes 验证码图片二进制数据 identify_image_callback : callable 处理验证码函数,输入验证码二进制数...
wechatsogou/identify_image.py
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): """手动打码解锁 Parameters ---------- url : str or unicode 验证码页面 之前的 url req : requests.sessions.Session requests.Session() 供调用解锁 resp : requests.models.Response requests 访问页面返回的,已经跳转了 img : ...
[ "手动打码解锁" ]
Chyroc/WechatSogou
python
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/identify_image.py#L79-L121
[ "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", ...
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
train
WechatSogouRequest.gen_search_article_url
拼接搜索 文章 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...
wechatsogou/request.py
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=None, et=None): """拼接搜索 文章 URL Parameters ---------- keyword : str or unicode 搜索文字 ...
[ "拼接搜索", "文章", "URL" ]
Chyroc/WechatSogou
python
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/request.py#L17-L86
[ "def", "gen_search_article_url", "(", "keyword", ",", "page", "=", "1", ",", "timesn", "=", "WechatSogouConst", ".", "search_article_time", ".", "anytime", ",", "article_type", "=", "WechatSogouConst", ".", "search_article_type", ".", "all", ",", "ft", "=", "Non...
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
train
WechatSogouRequest.gen_search_gzh_url
拼接搜索 公众号 URL Parameters ---------- keyword : str or unicode 搜索文字 page : int, optional 页数 the default is 1 Returns ------- str search_gzh_url
wechatsogou/request.py
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): """拼接搜索 公众号 URL Parameters ---------- keyword : str or unicode 搜索文字 page : int, optional 页数 the default is 1 Returns ------- str search_gzh_url """ assert isinst...
[ "拼接搜索", "公众号", "URL" ]
Chyroc/WechatSogou
python
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/request.py#L89-L112
[ "def", "gen_search_gzh_url", "(", "keyword", ",", "page", "=", "1", ")", ":", "assert", "isinstance", "(", "page", ",", "int", ")", "and", "page", ">", "0", "qs_dict", "=", "OrderedDict", "(", ")", "qs_dict", "[", "'type'", "]", "=", "_search_type_gzh", ...
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
train
WechatSogouRequest.gen_hot_url
拼接 首页热门文章 URL Parameters ---------- hot_index : WechatSogouConst.hot_index 首页热门文章的分类(常量):WechatSogouConst.hot_index.xxx page : int 页数 Returns ------- str 热门文章分类的url
wechatsogou/request.py
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): """拼接 首页热门文章 URL Parameters ---------- hot_index : WechatSogouConst.hot_index 首页热门文章的分类(常量):WechatSogouConst.hot_index.xxx page : int 页数 Returns ------- str 热门文章分类的url """ ...
[ "拼接", "首页热门文章", "URL" ]
Chyroc/WechatSogou
python
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/request.py#L115-L158
[ "def", "gen_hot_url", "(", "hot_index", ",", "page", "=", "1", ")", ":", "assert", "hasattr", "(", "WechatSogouConst", ".", "hot_index", ",", "hot_index", ")", "assert", "isinstance", "(", "page", ",", "int", ")", "and", "page", ">", "0", "index_urls", "...
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
train
get_first_of_element
抽取lxml.etree库中elem对象中文字 Args: element: lxml.etree.Element sub: str Returns: elem中文字
wechatsogou/tools.py
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): """抽取lxml.etree库中elem对象中文字 Args: element: lxml.etree.Element sub: str Returns: elem中文字 """ content = element.xpath(sub) return list_or_empty(content, contype)
[ "抽取lxml", ".", "etree库中elem对象中文字" ]
Chyroc/WechatSogou
python
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/tools.py#L46-L57
[ "def", "get_first_of_element", "(", "element", ",", "sub", ",", "contype", "=", "None", ")", ":", "content", "=", "element", ".", "xpath", "(", "sub", ")", "return", "list_or_empty", "(", "content", ",", "contype", ")" ]
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
train
get_encoding_from_reponse
获取requests库get或post返回的对象编码 Args: r: requests库get或post返回的对象 Returns: 对象编码
wechatsogou/tools.py
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): """获取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)
[ "获取requests库get或post返回的对象编码" ]
Chyroc/WechatSogou
python
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/tools.py#L60-L70
[ "def", "get_encoding_from_reponse", "(", "r", ")", ":", "encoding", "=", "requests", ".", "utils", ".", "get_encodings_from_content", "(", "r", ".", "text", ")", "return", "encoding", "[", "0", "]", "if", "encoding", "else", "requests", ".", "utils", ".", ...
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
train
_replace_str_html
替换html‘&quot;’等转义内容为正常内容 Args: s: 文字内容 Returns: s: 处理反转义后的文字
wechatsogou/tools.py
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‘&quot;’等转义内容为正常内容 Args: s: 文字内容 Returns: s: 处理反转义后的文字 """ html_str_list = [ ('&#39;', '\''), ('&quot;', '"'), ('&amp;', '&'), ('&yen;', '¥'), ('amp;', ''), ('&lt;', '<'), ('&gt;', '>'), ...
[ "替换html‘&quot", ";", "’等转义内容为正常内容" ]
Chyroc/WechatSogou
python
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/tools.py#L73-L95
[ "def", "_replace_str_html", "(", "s", ")", ":", "html_str_list", "=", "[", "(", "'&#39;'", ",", "'\\''", ")", ",", "(", "'&quot;'", ",", "'\"'", ")", ",", "(", "'&amp;'", ",", "'&'", ")", ",", "(", "'&yen;'", ",", "'¥')", ",", "", "(", "'amp;'", ...
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
train
WechatSogouStructuring.get_gzh_by_search
从搜索公众号获得的文本 提取公众号信息 Parameters ---------- text : str or unicode 搜索公众号获得的文本 Returns ------- list[dict] { 'open_id': '', # 微信号唯一ID 'profile_url': '', # 最近10条群发页链接 'headimage': '', # 头像 ...
wechatsogou/structuring.py
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): """从搜索公众号获得的文本 提取公众号信息 Parameters ---------- text : str or unicode 搜索公众号获得的文本 Returns ------- list[dict] { 'open_id': '', # 微信号唯一ID 'profile_url': '', # 最近10条群发页链接 ...
[ "从搜索公众号获得的文本", "提取公众号信息" ]
Chyroc/WechatSogou
python
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/structuring.py#L46-L104
[ "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...
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
train
WechatSogouStructuring.get_article_by_search
从搜索文章获得的文本 提取章列表信息 Parameters ---------- text : str or unicode 搜索文章获得的文本 Returns ------- list[dict] { 'article': { 'title': '', # 文章标题 'url': '', # 文章链接 'imgs': '', # ...
wechatsogou/structuring.py
def get_article_by_search(text): """从搜索文章获得的文本 提取章列表信息 Parameters ---------- text : str or unicode 搜索文章获得的文本 Returns ------- list[dict] { 'article': { 'title': '', # 文章标题 'url': '',...
def get_article_by_search(text): """从搜索文章获得的文本 提取章列表信息 Parameters ---------- text : str or unicode 搜索文章获得的文本 Returns ------- list[dict] { 'article': { 'title': '', # 文章标题 'url': '',...
[ "从搜索文章获得的文本", "提取章列表信息" ]
Chyroc/WechatSogou
python
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/structuring.py#L136-L215
[ "def", "get_article_by_search", "(", "text", ")", ":", "page", "=", "etree", ".", "HTML", "(", "text", ")", "lis", "=", "page", ".", "xpath", "(", "'//ul[@class=\"news-list\"]/li'", ")", "articles", "=", "[", "]", "for", "li", "in", "lis", ":", "url", ...
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
train
WechatSogouStructuring.get_gzh_info_by_history
从 历史消息页的文本 提取公众号信息 Parameters ---------- text : str or unicode 历史消息页的文本 Returns ------- dict { 'wechat_name': '', # 名称 'wechat_id': '', # 微信id 'introduction': '', # 描述 'authentica...
wechatsogou/structuring.py
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): """从 历史消息页的文本 提取公众号信息 Parameters ---------- text : str or unicode 历史消息页的文本 Returns ------- dict { 'wechat_name': '', # 名称 'wechat_id': '', # 微信id 'introd...
[ "从", "历史消息页的文本", "提取公众号信息" ]
Chyroc/WechatSogou
python
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/structuring.py#L218-L253
[ "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", "("...
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
train
WechatSogouStructuring.get_article_by_history_json
从 历史消息页的文本 提取文章列表信息 Parameters ---------- text : str or unicode 历史消息页的文本 article_json : dict 历史消息页的文本 提取出来的文章json dict Returns ------- list[dict] { 'send_id': '', # 群发id,注意不唯一,因为同一次群发多个消息,而群发id一致 ...
wechatsogou/structuring.py
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): """从 历史消息页的文本 提取文章列表信息 Parameters ---------- text : str or unicode 历史消息页的文本 article_json : dict 历史消息页的文本 提取出来的文章json dict Returns ------- list[dict] { ...
[ "从", "历史消息页的文本", "提取文章列表信息" ]
Chyroc/WechatSogou
python
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/structuring.py#L256-L334
[ "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", "...
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
train
WechatSogouStructuring.get_gzh_article_by_hot
从 首页热门搜索 提取公众号信息 和 文章列表信息 Parameters ---------- text : str or unicode 首页热门搜索 页 中 某一页 的文本 Returns ------- list[dict] { 'gzh': { 'headimage': str, # 公众号头像 'wechat_name': str, # 公众号名称 ...
wechatsogou/structuring.py
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): """从 首页热门搜索 提取公众号信息 和 文章列表信息 Parameters ---------- text : str or unicode 首页热门搜索 页 中 某一页 的文本 Returns ------- list[dict] { 'gzh': { 'headimage': str, # 公众号头像 ...
[ "从", "首页热门搜索", "提取公众号信息", "和", "文章列表信息" ]
Chyroc/WechatSogou
python
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/structuring.py#L381-L441
[ "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", "=", ...
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
train
WechatSogouStructuring.get_article_detail
根据微信文章的临时链接获取明细 1. 获取文本中所有的图片链接列表 2. 获取微信文章的html内容页面(去除标题等信息) Parameters ---------- text : str or unicode 一篇微信文章的文本 del_qqmusic: bool 删除文章中的qq音乐 del_voice: bool 删除文章中的语音内容 Returns ------- dict ...
wechatsogou/structuring.py
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. 获取文本中所有的图片链接列表 2. 获取微信文章的html内容页面(去除标题等信息) Parameters ---------- text : str or unicode 一篇微信文章的文本 del_qqmusic: bool 删除文章中的qq音乐 del_voice: bool ...
[ "根据微信文章的临时链接获取明细" ]
Chyroc/WechatSogou
python
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/structuring.py#L444-L527
[ "def", "get_article_detail", "(", "text", ",", "del_qqmusic", "=", "True", ",", "del_voice", "=", "True", ")", ":", "# 1. 获取微信文本content", "html_obj", "=", "BeautifulSoup", "(", "text", ",", "\"lxml\"", ")", "content_text", "=", "html_obj", ".", "find", "(", ...
2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a
train
_decode_image
Reads and decodes an image from a file object as a Numpy array. The SUN dataset contains images in several formats (despite the fact that all of them have .jpg extension). Some of them are: - BMP (RGB) - PNG (grayscale, RGBA, RGB interlaced) - JPEG (RGB) - GIF (1-frame RGB) Since TFDS assumes tha...
tensorflow_datasets/image/sun.py
def _decode_image(fobj, session, filename): """Reads and decodes an image from a file object as a Numpy array. The SUN dataset contains images in several formats (despite the fact that all of them have .jpg extension). Some of them are: - BMP (RGB) - PNG (grayscale, RGBA, RGB interlaced) - JPEG (RGB)...
def _decode_image(fobj, session, filename): """Reads and decodes an image from a file object as a Numpy array. The SUN dataset contains images in several formats (despite the fact that all of them have .jpg extension). Some of them are: - BMP (RGB) - PNG (grayscale, RGBA, RGB interlaced) - JPEG (RGB)...
[ "Reads", "and", "decodes", "an", "image", "from", "a", "file", "object", "as", "a", "Numpy", "array", "." ]
tensorflow/datasets
python
https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/sun.py#L65-L102
[ "def", "_decode_image", "(", "fobj", ",", "session", ",", "filename", ")", ":", "buf", "=", "fobj", ".", "read", "(", ")", "image", "=", "tfds", ".", "core", ".", "lazy_imports", ".", "cv2", ".", "imdecode", "(", "np", ".", "fromstring", "(", "buf", ...
46ceb0cf7b4690f38ecbbc689e4d659a903d08dc
train
_process_image_file
Process image files from the dataset.
tensorflow_datasets/image/sun.py
def _process_image_file(fobj, session, filename): """Process image files from the dataset.""" # We need to read the image files and convert them to JPEG, since some files # actually contain GIF, PNG or BMP data (despite having a .jpg extension) and # some encoding options that will make TF crash in general. i...
def _process_image_file(fobj, session, filename): """Process image files from the dataset.""" # We need to read the image files and convert them to JPEG, since some files # actually contain GIF, PNG or BMP data (despite having a .jpg extension) and # some encoding options that will make TF crash in general. i...
[ "Process", "image", "files", "from", "the", "dataset", "." ]
tensorflow/datasets
python
https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/sun.py#L113-L119
[ "def", "_process_image_file", "(", "fobj", ",", "session", ",", "filename", ")", ":", "# We need to read the image files and convert them to JPEG, since some files", "# actually contain GIF, PNG or BMP data (despite having a .jpg extension) and", "# some encoding options that will make TF cr...
46ceb0cf7b4690f38ecbbc689e4d659a903d08dc
train
Sun397._generate_examples
Yields examples.
tensorflow_datasets/image/sun.py
def _generate_examples(self, archive): """Yields examples.""" prefix_len = len("SUN397") with tf.Graph().as_default(): with utils.nogpu_session() as sess: for filepath, fobj in archive: if (filepath.endswith(".jpg") and filepath not in _SUN397_IGNORE_IMAGES): ...
def _generate_examples(self, archive): """Yields examples.""" prefix_len = len("SUN397") with tf.Graph().as_default(): with utils.nogpu_session() as sess: for filepath, fobj in archive: if (filepath.endswith(".jpg") and filepath not in _SUN397_IGNORE_IMAGES): ...
[ "Yields", "examples", "." ]
tensorflow/datasets
python
https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/sun.py#L157-L176
[ "def", "_generate_examples", "(", "self", ",", "archive", ")", ":", "prefix_len", "=", "len", "(", "\"SUN397\"", ")", "with", "tf", ".", "Graph", "(", ")", ".", "as_default", "(", ")", ":", "with", "utils", ".", "nogpu_session", "(", ")", "as", "sess",...
46ceb0cf7b4690f38ecbbc689e4d659a903d08dc
train
_parse_parallel_sentences
Returns examples from parallel SGML or text files, which may be gzipped.
tensorflow_datasets/translate/wmt.py
def _parse_parallel_sentences(f1, f2): """Returns examples from parallel SGML or text files, which may be gzipped.""" def _parse_text(path): """Returns the sentences from a single text file, which may be gzipped.""" split_path = path.split(".") if split_path[-1] == "gz": lang = split_path[-2] ...
def _parse_parallel_sentences(f1, f2): """Returns examples from parallel SGML or text files, which may be gzipped.""" def _parse_text(path): """Returns the sentences from a single text file, which may be gzipped.""" split_path = path.split(".") if split_path[-1] == "gz": lang = split_path[-2] ...
[ "Returns", "examples", "from", "parallel", "SGML", "or", "text", "files", "which", "may", "be", "gzipped", "." ]
tensorflow/datasets
python
https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/translate/wmt.py#L761-L820
[ "def", "_parse_parallel_sentences", "(", "f1", ",", "f2", ")", ":", "def", "_parse_text", "(", "path", ")", ":", "\"\"\"Returns the sentences from a single text file, which may be gzipped.\"\"\"", "split_path", "=", "path", ".", "split", "(", "\".\"", ")", "if", "spli...
46ceb0cf7b4690f38ecbbc689e4d659a903d08dc
train
_parse_tmx
Generates examples from TMX file.
tensorflow_datasets/translate/wmt.py
def _parse_tmx(path): """Generates examples from TMX file.""" def _get_tuv_lang(tuv): for k, v in tuv.items(): if k.endswith("}lang"): return v raise AssertionError("Language not found in `tuv` attributes.") def _get_tuv_seg(tuv): segs = tuv.findall("seg") assert len(segs) == 1, "In...
def _parse_tmx(path): """Generates examples from TMX file.""" def _get_tuv_lang(tuv): for k, v in tuv.items(): if k.endswith("}lang"): return v raise AssertionError("Language not found in `tuv` attributes.") def _get_tuv_seg(tuv): segs = tuv.findall("seg") assert len(segs) == 1, "In...
[ "Generates", "examples", "from", "TMX", "file", "." ]
tensorflow/datasets
python
https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/translate/wmt.py#L838-L858
[ "def", "_parse_tmx", "(", "path", ")", ":", "def", "_get_tuv_lang", "(", "tuv", ")", ":", "for", "k", ",", "v", "in", "tuv", ".", "items", "(", ")", ":", "if", "k", ".", "endswith", "(", "\"}lang\"", ")", ":", "return", "v", "raise", "AssertionErro...
46ceb0cf7b4690f38ecbbc689e4d659a903d08dc
train
_parse_tsv
Generates examples from TSV file.
tensorflow_datasets/translate/wmt.py
def _parse_tsv(path, language_pair=None): """Generates examples from TSV file.""" if language_pair is None: lang_match = re.match(r".*\.([a-z][a-z])-([a-z][a-z])\.tsv", path) assert lang_match is not None, "Invalid TSV filename: %s" % path l1, l2 = lang_match.groups() else: l1, l2 = language_pair ...
def _parse_tsv(path, language_pair=None): """Generates examples from TSV file.""" if language_pair is None: lang_match = re.match(r".*\.([a-z][a-z])-([a-z][a-z])\.tsv", path) assert lang_match is not None, "Invalid TSV filename: %s" % path l1, l2 = lang_match.groups() else: l1, l2 = language_pair ...
[ "Generates", "examples", "from", "TSV", "file", "." ]
tensorflow/datasets
python
https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/translate/wmt.py#L861-L881
[ "def", "_parse_tsv", "(", "path", ",", "language_pair", "=", "None", ")", ":", "if", "language_pair", "is", "None", ":", "lang_match", "=", "re", ".", "match", "(", "r\".*\\.([a-z][a-z])-([a-z][a-z])\\.tsv\"", ",", "path", ")", "assert", "lang_match", "is", "n...
46ceb0cf7b4690f38ecbbc689e4d659a903d08dc
train
_parse_wikiheadlines
Generates examples from Wikiheadlines dataset file.
tensorflow_datasets/translate/wmt.py
def _parse_wikiheadlines(path): """Generates examples from Wikiheadlines dataset file.""" lang_match = re.match(r".*\.([a-z][a-z])-([a-z][a-z])$", path) assert lang_match is not None, "Invalid Wikiheadlines filename: %s" % path l1, l2 = lang_match.groups() with tf.io.gfile.GFile(path) as f: for line in f:...
def _parse_wikiheadlines(path): """Generates examples from Wikiheadlines dataset file.""" lang_match = re.match(r".*\.([a-z][a-z])-([a-z][a-z])$", path) assert lang_match is not None, "Invalid Wikiheadlines filename: %s" % path l1, l2 = lang_match.groups() with tf.io.gfile.GFile(path) as f: for line in f:...
[ "Generates", "examples", "from", "Wikiheadlines", "dataset", "file", "." ]
tensorflow/datasets
python
https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/translate/wmt.py#L884-L895
[ "def", "_parse_wikiheadlines", "(", "path", ")", ":", "lang_match", "=", "re", ".", "match", "(", "r\".*\\.([a-z][a-z])-([a-z][a-z])$\"", ",", "path", ")", "assert", "lang_match", "is", "not", "None", ",", "\"Invalid Wikiheadlines filename: %s\"", "%", "path", "l1",...
46ceb0cf7b4690f38ecbbc689e4d659a903d08dc
train
_parse_czeng
Generates examples from CzEng v1.6, with optional filtering for v1.7.
tensorflow_datasets/translate/wmt.py
def _parse_czeng(*paths, **kwargs): """Generates examples from CzEng v1.6, with optional filtering for v1.7.""" filter_path = kwargs.get("filter_path", None) if filter_path: re_block = re.compile(r"^[^-]+-b(\d+)-\d\d[tde]") with tf.io.gfile.GFile(filter_path) as f: bad_blocks = { blk for b...
def _parse_czeng(*paths, **kwargs): """Generates examples from CzEng v1.6, with optional filtering for v1.7.""" filter_path = kwargs.get("filter_path", None) if filter_path: re_block = re.compile(r"^[^-]+-b(\d+)-\d\d[tde]") with tf.io.gfile.GFile(filter_path) as f: bad_blocks = { blk for b...
[ "Generates", "examples", "from", "CzEng", "v1", ".", "6", "with", "optional", "filtering", "for", "v1", ".", "7", "." ]
tensorflow/datasets
python
https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/translate/wmt.py#L898-L927
[ "def", "_parse_czeng", "(", "*", "paths", ",", "*", "*", "kwargs", ")", ":", "filter_path", "=", "kwargs", ".", "get", "(", "\"filter_path\"", ",", "None", ")", "if", "filter_path", ":", "re_block", "=", "re", ".", "compile", "(", "r\"^[^-]+-b(\\d+)-\\d\\d...
46ceb0cf7b4690f38ecbbc689e4d659a903d08dc
train
SubDataset._inject_language
Injects languages into (potentially) template strings.
tensorflow_datasets/translate/wmt.py
def _inject_language(self, src, strings): """Injects languages into (potentially) template strings.""" if src not in self.sources: raise ValueError("Invalid source for '{0}': {1}".format(self.name, src)) def _format_string(s): if "{0}" in s and "{1}" and "{src}" in s: return s.format(*so...
def _inject_language(self, src, strings): """Injects languages into (potentially) template strings.""" if src not in self.sources: raise ValueError("Invalid source for '{0}': {1}".format(self.name, src)) def _format_string(s): if "{0}" in s and "{1}" and "{src}" in s: return s.format(*so...
[ "Injects", "languages", "into", "(", "potentially", ")", "template", "strings", "." ]
tensorflow/datasets
python
https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/translate/wmt.py#L97-L110
[ "def", "_inject_language", "(", "self", ",", "src", ",", "strings", ")", ":", "if", "src", "not", "in", "self", ".", "sources", ":", "raise", "ValueError", "(", "\"Invalid source for '{0}': {1}\"", ".", "format", "(", "self", ".", "name", ",", "src", ")", ...
46ceb0cf7b4690f38ecbbc689e4d659a903d08dc
train
WmtTranslate.subsets
Subsets that make up each split of the dataset for the language pair.
tensorflow_datasets/translate/wmt.py
def subsets(self): """Subsets that make up each split of the dataset for the language pair.""" source, target = self.builder_config.language_pair filtered_subsets = {} for split, ss_names in self._subsets.items(): filtered_subsets[split] = [] for ss_name in ss_names: ds = DATASET_MAP...
def subsets(self): """Subsets that make up each split of the dataset for the language pair.""" source, target = self.builder_config.language_pair filtered_subsets = {} for split, ss_names in self._subsets.items(): filtered_subsets[split] = [] for ss_name in ss_names: ds = DATASET_MAP...
[ "Subsets", "that", "make", "up", "each", "split", "of", "the", "dataset", "for", "the", "language", "pair", "." ]
tensorflow/datasets
python
https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/translate/wmt.py#L615-L630
[ "def", "subsets", "(", "self", ")", ":", "source", ",", "target", "=", "self", ".", "builder_config", ".", "language_pair", "filtered_subsets", "=", "{", "}", "for", "split", ",", "ss_names", "in", "self", ".", "_subsets", ".", "items", "(", ")", ":", ...
46ceb0cf7b4690f38ecbbc689e4d659a903d08dc
train
WmtTranslate._generate_examples
Returns the examples in the raw (text) form.
tensorflow_datasets/translate/wmt.py
def _generate_examples(self, split_subsets, extraction_map): """Returns the examples in the raw (text) form.""" source, _ = self.builder_config.language_pair def _get_local_paths(ds, extract_dirs): rel_paths = ds.get_path(source) if len(extract_dirs) == 1: extract_dirs = extract_dirs * ...
def _generate_examples(self, split_subsets, extraction_map): """Returns the examples in the raw (text) form.""" source, _ = self.builder_config.language_pair def _get_local_paths(ds, extract_dirs): rel_paths = ds.get_path(source) if len(extract_dirs) == 1: extract_dirs = extract_dirs * ...
[ "Returns", "the", "examples", "in", "the", "raw", "(", "text", ")", "form", "." ]
tensorflow/datasets
python
https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/translate/wmt.py#L703-L758
[ "def", "_generate_examples", "(", "self", ",", "split_subsets", ",", "extraction_map", ")", ":", "source", ",", "_", "=", "self", ".", "builder_config", ".", "language_pair", "def", "_get_local_paths", "(", "ds", ",", "extract_dirs", ")", ":", "rel_paths", "="...
46ceb0cf7b4690f38ecbbc689e4d659a903d08dc
train
builder
Fetches a `tfds.core.DatasetBuilder` by string name. Args: name: `str`, the registered name of the `DatasetBuilder` (the snake case version of the class name). This can be either `"dataset_name"` or `"dataset_name/config_name"` for datasets with `BuilderConfig`s. As a convenience, this string m...
tensorflow_datasets/core/registered.py
def builder(name, **builder_init_kwargs): """Fetches a `tfds.core.DatasetBuilder` by string name. Args: name: `str`, the registered name of the `DatasetBuilder` (the snake case version of the class name). This can be either `"dataset_name"` or `"dataset_name/config_name"` for datasets with `Builder...
def builder(name, **builder_init_kwargs): """Fetches a `tfds.core.DatasetBuilder` by string name. Args: name: `str`, the registered name of the `DatasetBuilder` (the snake case version of the class name). This can be either `"dataset_name"` or `"dataset_name/config_name"` for datasets with `Builder...
[ "Fetches", "a", "tfds", ".", "core", ".", "DatasetBuilder", "by", "string", "name", "." ]
tensorflow/datasets
python
https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/registered.py#L137-L172
[ "def", "builder", "(", "name", ",", "*", "*", "builder_init_kwargs", ")", ":", "name", ",", "builder_kwargs", "=", "_dataset_name_and_kwargs_from_name_str", "(", "name", ")", "builder_kwargs", ".", "update", "(", "builder_init_kwargs", ")", "if", "name", "in", "...
46ceb0cf7b4690f38ecbbc689e4d659a903d08dc
train
load
Loads the named dataset into a `tf.data.Dataset`. If `split=None` (the default), returns all splits for the dataset. Otherwise, returns the specified split. `load` is a convenience method that fetches the `tfds.core.DatasetBuilder` by string name, optionally calls `DatasetBuilder.download_and_prepare` (if `...
tensorflow_datasets/core/registered.py
def load(name, split=None, data_dir=None, batch_size=1, download=True, as_supervised=False, with_info=False, builder_kwargs=None, download_and_prepare_kwargs=None, as_dataset_kwargs=None, try_gcs=False): """Loads the named datas...
def load(name, split=None, data_dir=None, batch_size=1, download=True, as_supervised=False, with_info=False, builder_kwargs=None, download_and_prepare_kwargs=None, as_dataset_kwargs=None, try_gcs=False): """Loads the named datas...
[ "Loads", "the", "named", "dataset", "into", "a", "tf", ".", "data", ".", "Dataset", "." ]
tensorflow/datasets
python
https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/registered.py#L176-L297
[ "def", "load", "(", "name", ",", "split", "=", "None", ",", "data_dir", "=", "None", ",", "batch_size", "=", "1", ",", "download", "=", "True", ",", "as_supervised", "=", "False", ",", "with_info", "=", "False", ",", "builder_kwargs", "=", "None", ",",...
46ceb0cf7b4690f38ecbbc689e4d659a903d08dc
train
_dataset_name_and_kwargs_from_name_str
Extract kwargs from name str.
tensorflow_datasets/core/registered.py
def _dataset_name_and_kwargs_from_name_str(name_str): """Extract kwargs from name str.""" res = _NAME_REG.match(name_str) if not res: raise ValueError(_NAME_STR_ERR.format(name_str)) name = res.group("dataset_name") kwargs = _kwargs_str_to_kwargs(res.group("kwargs")) try: for attr in ["config", "ver...
def _dataset_name_and_kwargs_from_name_str(name_str): """Extract kwargs from name str.""" res = _NAME_REG.match(name_str) if not res: raise ValueError(_NAME_STR_ERR.format(name_str)) name = res.group("dataset_name") kwargs = _kwargs_str_to_kwargs(res.group("kwargs")) try: for attr in ["config", "ver...
[ "Extract", "kwargs", "from", "name", "str", "." ]
tensorflow/datasets
python
https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/registered.py#L311-L329
[ "def", "_dataset_name_and_kwargs_from_name_str", "(", "name_str", ")", ":", "res", "=", "_NAME_REG", ".", "match", "(", "name_str", ")", "if", "not", "res", ":", "raise", "ValueError", "(", "_NAME_STR_ERR", ".", "format", "(", "name_str", ")", ")", "name", "...
46ceb0cf7b4690f38ecbbc689e4d659a903d08dc
train
_cast_to_pod
Try cast to int, float, bool, str, in that order.
tensorflow_datasets/core/registered.py
def _cast_to_pod(val): """Try cast to int, float, bool, str, in that order.""" bools = {"True": True, "False": False} if val in bools: return bools[val] try: return int(val) except ValueError: try: return float(val) except ValueError: return tf.compat.as_text(val)
def _cast_to_pod(val): """Try cast to int, float, bool, str, in that order.""" bools = {"True": True, "False": False} if val in bools: return bools[val] try: return int(val) except ValueError: try: return float(val) except ValueError: return tf.compat.as_text(val)
[ "Try", "cast", "to", "int", "float", "bool", "str", "in", "that", "order", "." ]
tensorflow/datasets
python
https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/registered.py#L343-L354
[ "def", "_cast_to_pod", "(", "val", ")", ":", "bools", "=", "{", "\"True\"", ":", "True", ",", "\"False\"", ":", "False", "}", "if", "val", "in", "bools", ":", "return", "bools", "[", "val", "]", "try", ":", "return", "int", "(", "val", ")", "except...
46ceb0cf7b4690f38ecbbc689e4d659a903d08dc
train
_try_import
Try importing a module, with an informative error message on failure.
tensorflow_datasets/core/lazy_imports.py
def _try_import(module_name): """Try importing a module, with an informative error message on failure.""" try: mod = importlib.import_module(module_name) return mod except ImportError: err_msg = ("Tried importing %s but failed. See setup.py extras_require. " "The dataset you are trying ...
def _try_import(module_name): """Try importing a module, with an informative error message on failure.""" try: mod = importlib.import_module(module_name) return mod except ImportError: err_msg = ("Tried importing %s but failed. See setup.py extras_require. " "The dataset you are trying ...
[ "Try", "importing", "a", "module", "with", "an", "informative", "error", "message", "on", "failure", "." ]
tensorflow/datasets
python
https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/lazy_imports.py#L27-L36
[ "def", "_try_import", "(", "module_name", ")", ":", "try", ":", "mod", "=", "importlib", ".", "import_module", "(", "module_name", ")", "return", "mod", "except", "ImportError", ":", "err_msg", "=", "(", "\"Tried importing %s but failed. See setup.py extras_require. \...
46ceb0cf7b4690f38ecbbc689e4d659a903d08dc
train
np_to_list
Returns list from list, tuple or ndarray.
tensorflow_datasets/core/features/sequence_feature.py
def np_to_list(elem): """Returns list from list, tuple or ndarray.""" if isinstance(elem, list): return elem elif isinstance(elem, tuple): return list(elem) elif isinstance(elem, np.ndarray): return list(elem) else: raise ValueError( 'Input elements of a sequence should be either a num...
def np_to_list(elem): """Returns list from list, tuple or ndarray.""" if isinstance(elem, list): return elem elif isinstance(elem, tuple): return list(elem) elif isinstance(elem, np.ndarray): return list(elem) else: raise ValueError( 'Input elements of a sequence should be either a num...
[ "Returns", "list", "from", "list", "tuple", "or", "ndarray", "." ]
tensorflow/datasets
python
https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/sequence_feature.py#L257-L268
[ "def", "np_to_list", "(", "elem", ")", ":", "if", "isinstance", "(", "elem", ",", "list", ")", ":", "return", "elem", "elif", "isinstance", "(", "elem", ",", "tuple", ")", ":", "return", "list", "(", "elem", ")", "elif", "isinstance", "(", "elem", ",...
46ceb0cf7b4690f38ecbbc689e4d659a903d08dc
train
_transpose_dict_list
Transpose a nested dict[list] into a list[nested dict].
tensorflow_datasets/core/features/sequence_feature.py
def _transpose_dict_list(dict_list): """Transpose a nested dict[list] into a list[nested dict].""" # 1. Unstack numpy arrays into list dict_list = utils.map_nested(np_to_list, dict_list, dict_only=True) # 2. Extract the sequence length (and ensure the length is constant for all # elements) length = {'value...
def _transpose_dict_list(dict_list): """Transpose a nested dict[list] into a list[nested dict].""" # 1. Unstack numpy arrays into list dict_list = utils.map_nested(np_to_list, dict_list, dict_only=True) # 2. Extract the sequence length (and ensure the length is constant for all # elements) length = {'value...
[ "Transpose", "a", "nested", "dict", "[", "list", "]", "into", "a", "list", "[", "nested", "dict", "]", "." ]
tensorflow/datasets
python
https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/sequence_feature.py#L271-L293
[ "def", "_transpose_dict_list", "(", "dict_list", ")", ":", "# 1. Unstack numpy arrays into list", "dict_list", "=", "utils", ".", "map_nested", "(", "np_to_list", ",", "dict_list", ",", "dict_only", "=", "True", ")", "# 2. Extract the sequence length (and ensure the length ...
46ceb0cf7b4690f38ecbbc689e4d659a903d08dc
train
SequenceDict.get_tensor_info
See base class for details.
tensorflow_datasets/core/features/sequence_feature.py
def get_tensor_info(self): """See base class for details.""" # Add the additional length dimension to every shape def add_length_dim(tensor_info): return feature_lib.TensorInfo( shape=(self._length,) + tensor_info.shape, dtype=tensor_info.dtype, ) tensor_info = super(Se...
def get_tensor_info(self): """See base class for details.""" # Add the additional length dimension to every shape def add_length_dim(tensor_info): return feature_lib.TensorInfo( shape=(self._length,) + tensor_info.shape, dtype=tensor_info.dtype, ) tensor_info = super(Se...
[ "See", "base", "class", "for", "details", "." ]
tensorflow/datasets
python
https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/sequence_feature.py#L90-L101
[ "def", "get_tensor_info", "(", "self", ")", ":", "# Add the additional length dimension to every shape", "def", "add_length_dim", "(", "tensor_info", ")", ":", "return", "feature_lib", ".", "TensorInfo", "(", "shape", "=", "(", "self", ".", "_length", ",", ")", "+...
46ceb0cf7b4690f38ecbbc689e4d659a903d08dc
train
SequenceDict.get_serialized_info
See base class for details.
tensorflow_datasets/core/features/sequence_feature.py
def get_serialized_info(self): """See base class for details.""" # Add the additional length dimension to every serialized features def add_length_dim(serialized_info): """Add the length dimension to the serialized_info. Args: serialized_info: One of tf.io.FixedLenFeature, tf.io.VarLen...
def get_serialized_info(self): """See base class for details.""" # Add the additional length dimension to every serialized features def add_length_dim(serialized_info): """Add the length dimension to the serialized_info. Args: serialized_info: One of tf.io.FixedLenFeature, tf.io.VarLen...
[ "See", "base", "class", "for", "details", "." ]
tensorflow/datasets
python
https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/sequence_feature.py#L103-L137
[ "def", "get_serialized_info", "(", "self", ")", ":", "# Add the additional length dimension to every serialized features", "def", "add_length_dim", "(", "serialized_info", ")", ":", "\"\"\"Add the length dimension to the serialized_info.\n\n Args:\n serialized_info: One of tf.i...
46ceb0cf7b4690f38ecbbc689e4d659a903d08dc
train
MNIST._split_generators
Returns SplitGenerators.
tensorflow_datasets/image/mnist.py
def _split_generators(self, dl_manager): """Returns SplitGenerators.""" # Download the full MNIST Database filenames = { "train_data": _MNIST_TRAIN_DATA_FILENAME, "train_labels": _MNIST_TRAIN_LABELS_FILENAME, "test_data": _MNIST_TEST_DATA_FILENAME, "test_labels": _MNIST_TEST_...
def _split_generators(self, dl_manager): """Returns SplitGenerators.""" # Download the full MNIST Database filenames = { "train_data": _MNIST_TRAIN_DATA_FILENAME, "train_labels": _MNIST_TRAIN_LABELS_FILENAME, "test_data": _MNIST_TEST_DATA_FILENAME, "test_labels": _MNIST_TEST_...
[ "Returns", "SplitGenerators", "." ]
tensorflow/datasets
python
https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/mnist.py#L113-L144
[ "def", "_split_generators", "(", "self", ",", "dl_manager", ")", ":", "# Download the full MNIST Database", "filenames", "=", "{", "\"train_data\"", ":", "_MNIST_TRAIN_DATA_FILENAME", ",", "\"train_labels\"", ":", "_MNIST_TRAIN_LABELS_FILENAME", ",", "\"test_data\"", ":", ...
46ceb0cf7b4690f38ecbbc689e4d659a903d08dc
train
MNIST._generate_examples
Generate MNIST examples as dicts. Args: num_examples (int): The number of example. data_path (str): Path to the data files label_path (str): Path to the labels Yields: Generator yielding the next examples
tensorflow_datasets/image/mnist.py
def _generate_examples(self, num_examples, data_path, label_path): """Generate MNIST examples as dicts. Args: num_examples (int): The number of example. data_path (str): Path to the data files label_path (str): Path to the labels Yields: Generator yielding the next examples """...
def _generate_examples(self, num_examples, data_path, label_path): """Generate MNIST examples as dicts. Args: num_examples (int): The number of example. data_path (str): Path to the data files label_path (str): Path to the labels Yields: Generator yielding the next examples """...
[ "Generate", "MNIST", "examples", "as", "dicts", "." ]
tensorflow/datasets
python
https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/mnist.py#L146-L166
[ "def", "_generate_examples", "(", "self", ",", "num_examples", ",", "data_path", ",", "label_path", ")", ":", "images", "=", "_extract_mnist_images", "(", "data_path", ",", "num_examples", ")", "labels", "=", "_extract_mnist_labels", "(", "label_path", ",", "num_e...
46ceb0cf7b4690f38ecbbc689e4d659a903d08dc
train
OxfordFlowers102._split_generators
Returns SplitGenerators.
tensorflow_datasets/image/oxford_flowers102.py
def _split_generators(self, dl_manager): """Returns SplitGenerators.""" # Download images and annotations that come in separate archives. # Note, that the extension of archives is .tar.gz even though the actual # archives format is uncompressed tar. dl_paths = dl_manager.download_and_extract({ ...
def _split_generators(self, dl_manager): """Returns SplitGenerators.""" # Download images and annotations that come in separate archives. # Note, that the extension of archives is .tar.gz even though the actual # archives format is uncompressed tar. dl_paths = dl_manager.download_and_extract({ ...
[ "Returns", "SplitGenerators", "." ]
tensorflow/datasets
python
https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/oxford_flowers102.py#L70-L102
[ "def", "_split_generators", "(", "self", ",", "dl_manager", ")", ":", "# Download images and annotations that come in separate archives.", "# Note, that the extension of archives is .tar.gz even though the actual", "# archives format is uncompressed tar.", "dl_paths", "=", "dl_manager", ...
46ceb0cf7b4690f38ecbbc689e4d659a903d08dc
train
OxfordFlowers102._generate_examples
Yields examples.
tensorflow_datasets/image/oxford_flowers102.py
def _generate_examples(self, images_dir_path, labels_path, setid_path, split_name): """Yields examples.""" with tf.io.gfile.GFile(labels_path, "rb") as f: labels = tfds.core.lazy_imports.scipy.io.loadmat(f)["labels"][0] with tf.io.gfile.GFile(setid_path, "rb") as f: exam...
def _generate_examples(self, images_dir_path, labels_path, setid_path, split_name): """Yields examples.""" with tf.io.gfile.GFile(labels_path, "rb") as f: labels = tfds.core.lazy_imports.scipy.io.loadmat(f)["labels"][0] with tf.io.gfile.GFile(setid_path, "rb") as f: exam...
[ "Yields", "examples", "." ]
tensorflow/datasets
python
https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/oxford_flowers102.py#L104-L118
[ "def", "_generate_examples", "(", "self", ",", "images_dir_path", ",", "labels_path", ",", "setid_path", ",", "split_name", ")", ":", "with", "tf", ".", "io", ".", "gfile", ".", "GFile", "(", "labels_path", ",", "\"rb\"", ")", "as", "f", ":", "labels", "...
46ceb0cf7b4690f38ecbbc689e4d659a903d08dc