repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
ricequant/rqalpha
rqalpha/mod/rqalpha_mod_sys_transaction_cost/deciders.py
StockTransactionCostDecider.get_trade_commission
def get_trade_commission(self, trade): """ 计算手续费这个逻辑比较复杂,按照如下算法来计算: 1. 定义一个剩余手续费的概念,根据order_id存储在commission_map中,默认为min_commission 2. 当trade来时计算该trade产生的手续费cost_money 3. 如果cost_money > commission 3.1 如果commission 等于 min_commission,说明这是第一笔trade,此时,直接commission置0,返回cost_money即可 3.2 如果commission 不等于 min_commission, 则说明这不是第一笔trade,此时,直接cost_money - commission即可 4. 如果cost_money <= commission 4.1 如果commission 等于 min_commission, 说明是第一笔trade, 此时,返回min_commission(提前把最小手续费收了) 4.2 如果commission 不等于 min_commission, 说明不是第一笔trade, 之前的trade中min_commission已经收过了,所以返回0. """ order_id = trade.order_id if self.env.data_proxy.instruments(trade.order_book_id).type == 'PublicFund': return self._get_public_fund_commission(trade.order_book_id, trade.side, trade.last_price * trade.last_quantity) commission = self.commission_map[order_id] cost_commission = trade.last_price * trade.last_quantity * self.commission_rate * self.commission_multiplier if cost_commission > commission: if commission == self.min_commission: self.commission_map[order_id] = 0 return cost_commission else: self.commission_map[order_id] = 0 return cost_commission - commission else: if commission == self.min_commission: self.commission_map[order_id] -= cost_commission return commission else: self.commission_map[order_id] -= cost_commission return 0
python
def get_trade_commission(self, trade): """ 计算手续费这个逻辑比较复杂,按照如下算法来计算: 1. 定义一个剩余手续费的概念,根据order_id存储在commission_map中,默认为min_commission 2. 当trade来时计算该trade产生的手续费cost_money 3. 如果cost_money > commission 3.1 如果commission 等于 min_commission,说明这是第一笔trade,此时,直接commission置0,返回cost_money即可 3.2 如果commission 不等于 min_commission, 则说明这不是第一笔trade,此时,直接cost_money - commission即可 4. 如果cost_money <= commission 4.1 如果commission 等于 min_commission, 说明是第一笔trade, 此时,返回min_commission(提前把最小手续费收了) 4.2 如果commission 不等于 min_commission, 说明不是第一笔trade, 之前的trade中min_commission已经收过了,所以返回0. """ order_id = trade.order_id if self.env.data_proxy.instruments(trade.order_book_id).type == 'PublicFund': return self._get_public_fund_commission(trade.order_book_id, trade.side, trade.last_price * trade.last_quantity) commission = self.commission_map[order_id] cost_commission = trade.last_price * trade.last_quantity * self.commission_rate * self.commission_multiplier if cost_commission > commission: if commission == self.min_commission: self.commission_map[order_id] = 0 return cost_commission else: self.commission_map[order_id] = 0 return cost_commission - commission else: if commission == self.min_commission: self.commission_map[order_id] -= cost_commission return commission else: self.commission_map[order_id] -= cost_commission return 0
[ "def", "get_trade_commission", "(", "self", ",", "trade", ")", ":", "order_id", "=", "trade", ".", "order_id", "if", "self", ".", "env", ".", "data_proxy", ".", "instruments", "(", "trade", ".", "order_book_id", ")", ".", "type", "==", "'PublicFund'", ":", "return", "self", ".", "_get_public_fund_commission", "(", "trade", ".", "order_book_id", ",", "trade", ".", "side", ",", "trade", ".", "last_price", "*", "trade", ".", "last_quantity", ")", "commission", "=", "self", ".", "commission_map", "[", "order_id", "]", "cost_commission", "=", "trade", ".", "last_price", "*", "trade", ".", "last_quantity", "*", "self", ".", "commission_rate", "*", "self", ".", "commission_multiplier", "if", "cost_commission", ">", "commission", ":", "if", "commission", "==", "self", ".", "min_commission", ":", "self", ".", "commission_map", "[", "order_id", "]", "=", "0", "return", "cost_commission", "else", ":", "self", ".", "commission_map", "[", "order_id", "]", "=", "0", "return", "cost_commission", "-", "commission", "else", ":", "if", "commission", "==", "self", ".", "min_commission", ":", "self", ".", "commission_map", "[", "order_id", "]", "-=", "cost_commission", "return", "commission", "else", ":", "self", ".", "commission_map", "[", "order_id", "]", "-=", "cost_commission", "return", "0" ]
计算手续费这个逻辑比较复杂,按照如下算法来计算: 1. 定义一个剩余手续费的概念,根据order_id存储在commission_map中,默认为min_commission 2. 当trade来时计算该trade产生的手续费cost_money 3. 如果cost_money > commission 3.1 如果commission 等于 min_commission,说明这是第一笔trade,此时,直接commission置0,返回cost_money即可 3.2 如果commission 不等于 min_commission, 则说明这不是第一笔trade,此时,直接cost_money - commission即可 4. 如果cost_money <= commission 4.1 如果commission 等于 min_commission, 说明是第一笔trade, 此时,返回min_commission(提前把最小手续费收了) 4.2 如果commission 不等于 min_commission, 说明不是第一笔trade, 之前的trade中min_commission已经收过了,所以返回0.
[ "计算手续费这个逻辑比较复杂,按照如下算法来计算:", "1", ".", "定义一个剩余手续费的概念,根据order_id存储在commission_map中,默认为min_commission", "2", ".", "当trade来时计算该trade产生的手续费cost_money", "3", ".", "如果cost_money", ">", "commission", "3", ".", "1", "如果commission", "等于", "min_commission,说明这是第一笔trade,此时,直接commission置0,返回cost_money即可", "3", ".", "2", "如果commission", "不等于", "min_commission", "则说明这不是第一笔trade", "此时,直接cost_money", "-", "commission即可", "4", ".", "如果cost_money", "<", "=", "commission", "4", ".", "1", "如果commission", "等于", "min_commission", "说明是第一笔trade", "此时,返回min_commission", "(", "提前把最小手续费收了", ")", "4", ".", "2", "如果commission", "不等于", "min_commission,", "说明不是第一笔trade", "之前的trade中min_commission已经收过了,所以返回0", "." ]
ac40a62d4e7eca9494b4d0a14f46facf5616820c
https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/mod/rqalpha_mod_sys_transaction_cost/deciders.py#L50-L80
train
ricequant/rqalpha
rqalpha/mod/rqalpha_mod_sys_transaction_cost/deciders.py
HKStockTransactionCostDecider._get_tax
def _get_tax(self, order_book_id, _, cost_money): """ 港交所收费项目繁多,按照如下逻辑计算税费: 1. 税费比例为 0.11%,不足 1 元按 1 元记,四舍五入保留两位小数(包括印花税、交易征费、交易系统使用费)。 2,五元固定费用(包括卖方收取的转手纸印花税、买方收取的过户费用)。 """ instrument = Environment.get_instance().get_instrument(order_book_id) if instrument.type != 'CS': return 0 tax = cost_money * self.tax_rate if tax < 1: tax = 1 else: tax = round(tax, 2) return tax + 5
python
def _get_tax(self, order_book_id, _, cost_money): """ 港交所收费项目繁多,按照如下逻辑计算税费: 1. 税费比例为 0.11%,不足 1 元按 1 元记,四舍五入保留两位小数(包括印花税、交易征费、交易系统使用费)。 2,五元固定费用(包括卖方收取的转手纸印花税、买方收取的过户费用)。 """ instrument = Environment.get_instance().get_instrument(order_book_id) if instrument.type != 'CS': return 0 tax = cost_money * self.tax_rate if tax < 1: tax = 1 else: tax = round(tax, 2) return tax + 5
[ "def", "_get_tax", "(", "self", ",", "order_book_id", ",", "_", ",", "cost_money", ")", ":", "instrument", "=", "Environment", ".", "get_instance", "(", ")", ".", "get_instrument", "(", "order_book_id", ")", "if", "instrument", ".", "type", "!=", "'CS'", ":", "return", "0", "tax", "=", "cost_money", "*", "self", ".", "tax_rate", "if", "tax", "<", "1", ":", "tax", "=", "1", "else", ":", "tax", "=", "round", "(", "tax", ",", "2", ")", "return", "tax", "+", "5" ]
港交所收费项目繁多,按照如下逻辑计算税费: 1. 税费比例为 0.11%,不足 1 元按 1 元记,四舍五入保留两位小数(包括印花税、交易征费、交易系统使用费)。 2,五元固定费用(包括卖方收取的转手纸印花税、买方收取的过户费用)。
[ "港交所收费项目繁多,按照如下逻辑计算税费:", "1", ".", "税费比例为", "0", ".", "11%,不足", "1", "元按", "1", "元记,四舍五入保留两位小数(包括印花税、交易征费、交易系统使用费)。", "2,五元固定费用(包括卖方收取的转手纸印花税、买方收取的过户费用)。" ]
ac40a62d4e7eca9494b4d0a14f46facf5616820c
https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/mod/rqalpha_mod_sys_transaction_cost/deciders.py#L108-L122
train
ricequant/rqalpha
rqalpha/model/bar.py
BarObject.prev_close
def prev_close(self): """ [float] 昨日收盘价 """ try: return self._data['prev_close'] except (ValueError, KeyError): pass if self._prev_close is None: trading_dt = Environment.get_instance().trading_dt data_proxy = Environment.get_instance().data_proxy self._prev_close = data_proxy.get_prev_close(self._instrument.order_book_id, trading_dt) return self._prev_close
python
def prev_close(self): """ [float] 昨日收盘价 """ try: return self._data['prev_close'] except (ValueError, KeyError): pass if self._prev_close is None: trading_dt = Environment.get_instance().trading_dt data_proxy = Environment.get_instance().data_proxy self._prev_close = data_proxy.get_prev_close(self._instrument.order_book_id, trading_dt) return self._prev_close
[ "def", "prev_close", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_data", "[", "'prev_close'", "]", "except", "(", "ValueError", ",", "KeyError", ")", ":", "pass", "if", "self", ".", "_prev_close", "is", "None", ":", "trading_dt", "=", "Environment", ".", "get_instance", "(", ")", ".", "trading_dt", "data_proxy", "=", "Environment", ".", "get_instance", "(", ")", ".", "data_proxy", "self", ".", "_prev_close", "=", "data_proxy", ".", "get_prev_close", "(", "self", ".", "_instrument", ".", "order_book_id", ",", "trading_dt", ")", "return", "self", ".", "_prev_close" ]
[float] 昨日收盘价
[ "[", "float", "]", "昨日收盘价" ]
ac40a62d4e7eca9494b4d0a14f46facf5616820c
https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/model/bar.py#L91-L104
train
ricequant/rqalpha
rqalpha/model/bar.py
BarObject._bar_status
def _bar_status(self): """ WARNING: 获取 bar_status 比较耗费性能,而且是lazy_compute,因此不要多次调用!!!! """ if self.isnan or np.isnan(self.limit_up): return BAR_STATUS.ERROR if self.close >= self.limit_up: return BAR_STATUS.LIMIT_UP if self.close <= self.limit_down: return BAR_STATUS.LIMIT_DOWN return BAR_STATUS.NORMAL
python
def _bar_status(self): """ WARNING: 获取 bar_status 比较耗费性能,而且是lazy_compute,因此不要多次调用!!!! """ if self.isnan or np.isnan(self.limit_up): return BAR_STATUS.ERROR if self.close >= self.limit_up: return BAR_STATUS.LIMIT_UP if self.close <= self.limit_down: return BAR_STATUS.LIMIT_DOWN return BAR_STATUS.NORMAL
[ "def", "_bar_status", "(", "self", ")", ":", "if", "self", ".", "isnan", "or", "np", ".", "isnan", "(", "self", ".", "limit_up", ")", ":", "return", "BAR_STATUS", ".", "ERROR", "if", "self", ".", "close", ">=", "self", ".", "limit_up", ":", "return", "BAR_STATUS", ".", "LIMIT_UP", "if", "self", ".", "close", "<=", "self", ".", "limit_down", ":", "return", "BAR_STATUS", ".", "LIMIT_DOWN", "return", "BAR_STATUS", ".", "NORMAL" ]
WARNING: 获取 bar_status 比较耗费性能,而且是lazy_compute,因此不要多次调用!!!!
[ "WARNING", ":", "获取", "bar_status", "比较耗费性能,而且是lazy_compute,因此不要多次调用!!!!" ]
ac40a62d4e7eca9494b4d0a14f46facf5616820c
https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/model/bar.py#L107-L117
train
ricequant/rqalpha
rqalpha/model/bar.py
BarObject.prev_settlement
def prev_settlement(self): """ [float] 昨日结算价(期货专用) """ try: return self._data['prev_settlement'] except (ValueError, KeyError): pass if self._prev_settlement is None: trading_dt = Environment.get_instance().trading_dt data_proxy = Environment.get_instance().data_proxy self._prev_settlement = data_proxy.get_prev_settlement(self._instrument.order_book_id, trading_dt) return self._prev_settlement
python
def prev_settlement(self): """ [float] 昨日结算价(期货专用) """ try: return self._data['prev_settlement'] except (ValueError, KeyError): pass if self._prev_settlement is None: trading_dt = Environment.get_instance().trading_dt data_proxy = Environment.get_instance().data_proxy self._prev_settlement = data_proxy.get_prev_settlement(self._instrument.order_book_id, trading_dt) return self._prev_settlement
[ "def", "prev_settlement", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_data", "[", "'prev_settlement'", "]", "except", "(", "ValueError", ",", "KeyError", ")", ":", "pass", "if", "self", ".", "_prev_settlement", "is", "None", ":", "trading_dt", "=", "Environment", ".", "get_instance", "(", ")", ".", "trading_dt", "data_proxy", "=", "Environment", ".", "get_instance", "(", ")", ".", "data_proxy", "self", ".", "_prev_settlement", "=", "data_proxy", ".", "get_prev_settlement", "(", "self", ".", "_instrument", ".", "order_book_id", ",", "trading_dt", ")", "return", "self", ".", "_prev_settlement" ]
[float] 昨日结算价(期货专用)
[ "[", "float", "]", "昨日结算价(期货专用)" ]
ac40a62d4e7eca9494b4d0a14f46facf5616820c
https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/model/bar.py#L180-L193
train
ricequant/rqalpha
rqalpha/api/api_base.py
submit_order
def submit_order(id_or_ins, amount, side, price=None, position_effect=None): """ 通用下单函数,策略可以通过该函数自由选择参数下单。 :param id_or_ins: 下单标的物 :type id_or_ins: :class:`~Instrument` object | `str` :param float amount: 下单量,需为正数 :param side: 多空方向,多(SIDE.BUY)或空(SIDE.SELL) :type side: :class:`~SIDE` enum :param float price: 下单价格,默认为None,表示市价单 :param position_effect: 开平方向,开仓(POSITION_EFFECT.OPEN),平仓(POSITION.CLOSE)或平今(POSITION_EFFECT.CLOSE_TODAY),交易股票不需要该参数 :type position_effect: :class:`~POSITION_EFFECT` enum :return: :class:`~Order` object | None :example: .. code-block:: python # 购买 2000 股的平安银行股票,并以市价单发送: submit_order('000001.XSHE', 2000, SIDE.BUY) # 平 10 份 RB1812 多方向的今仓,并以 4000 的价格发送限价单 submit_order('RB1812', 10, SIDE.SELL, price=4000, position_effect=POSITION_EFFECT.CLOSE_TODAY) """ order_book_id = assure_order_book_id(id_or_ins) env = Environment.get_instance() if ( env.config.base.run_type != RUN_TYPE.BACKTEST and env.get_instrument(order_book_id).type == "Future" ): if "88" in order_book_id: raise RQInvalidArgument( _(u"Main Future contracts[88] are not supported in paper trading.") ) if "99" in order_book_id: raise RQInvalidArgument( _(u"Index Future contracts[99] are not supported in paper trading.") ) style = cal_style(price, None) market_price = env.get_last_price(order_book_id) if not is_valid_price(market_price): user_system_log.warn( _(u"Order Creation Failed: [{order_book_id}] No market data").format( order_book_id=order_book_id ) ) return amount = int(amount) order = Order.__from_create__( order_book_id=order_book_id, quantity=amount, side=side, style=style, position_effect=position_effect, ) if order.type == ORDER_TYPE.MARKET: order.set_frozen_price(market_price) if env.can_submit_order(order): env.broker.submit_order(order) return order
python
def submit_order(id_or_ins, amount, side, price=None, position_effect=None): """ 通用下单函数,策略可以通过该函数自由选择参数下单。 :param id_or_ins: 下单标的物 :type id_or_ins: :class:`~Instrument` object | `str` :param float amount: 下单量,需为正数 :param side: 多空方向,多(SIDE.BUY)或空(SIDE.SELL) :type side: :class:`~SIDE` enum :param float price: 下单价格,默认为None,表示市价单 :param position_effect: 开平方向,开仓(POSITION_EFFECT.OPEN),平仓(POSITION.CLOSE)或平今(POSITION_EFFECT.CLOSE_TODAY),交易股票不需要该参数 :type position_effect: :class:`~POSITION_EFFECT` enum :return: :class:`~Order` object | None :example: .. code-block:: python # 购买 2000 股的平安银行股票,并以市价单发送: submit_order('000001.XSHE', 2000, SIDE.BUY) # 平 10 份 RB1812 多方向的今仓,并以 4000 的价格发送限价单 submit_order('RB1812', 10, SIDE.SELL, price=4000, position_effect=POSITION_EFFECT.CLOSE_TODAY) """ order_book_id = assure_order_book_id(id_or_ins) env = Environment.get_instance() if ( env.config.base.run_type != RUN_TYPE.BACKTEST and env.get_instrument(order_book_id).type == "Future" ): if "88" in order_book_id: raise RQInvalidArgument( _(u"Main Future contracts[88] are not supported in paper trading.") ) if "99" in order_book_id: raise RQInvalidArgument( _(u"Index Future contracts[99] are not supported in paper trading.") ) style = cal_style(price, None) market_price = env.get_last_price(order_book_id) if not is_valid_price(market_price): user_system_log.warn( _(u"Order Creation Failed: [{order_book_id}] No market data").format( order_book_id=order_book_id ) ) return amount = int(amount) order = Order.__from_create__( order_book_id=order_book_id, quantity=amount, side=side, style=style, position_effect=position_effect, ) if order.type == ORDER_TYPE.MARKET: order.set_frozen_price(market_price) if env.can_submit_order(order): env.broker.submit_order(order) return order
[ "def", "submit_order", "(", "id_or_ins", ",", "amount", ",", "side", ",", "price", "=", "None", ",", "position_effect", "=", "None", ")", ":", "order_book_id", "=", "assure_order_book_id", "(", "id_or_ins", ")", "env", "=", "Environment", ".", "get_instance", "(", ")", "if", "(", "env", ".", "config", ".", "base", ".", "run_type", "!=", "RUN_TYPE", ".", "BACKTEST", "and", "env", ".", "get_instrument", "(", "order_book_id", ")", ".", "type", "==", "\"Future\"", ")", ":", "if", "\"88\"", "in", "order_book_id", ":", "raise", "RQInvalidArgument", "(", "_", "(", "u\"Main Future contracts[88] are not supported in paper trading.\"", ")", ")", "if", "\"99\"", "in", "order_book_id", ":", "raise", "RQInvalidArgument", "(", "_", "(", "u\"Index Future contracts[99] are not supported in paper trading.\"", ")", ")", "style", "=", "cal_style", "(", "price", ",", "None", ")", "market_price", "=", "env", ".", "get_last_price", "(", "order_book_id", ")", "if", "not", "is_valid_price", "(", "market_price", ")", ":", "user_system_log", ".", "warn", "(", "_", "(", "u\"Order Creation Failed: [{order_book_id}] No market data\"", ")", ".", "format", "(", "order_book_id", "=", "order_book_id", ")", ")", "return", "amount", "=", "int", "(", "amount", ")", "order", "=", "Order", ".", "__from_create__", "(", "order_book_id", "=", "order_book_id", ",", "quantity", "=", "amount", ",", "side", "=", "side", ",", "style", "=", "style", ",", "position_effect", "=", "position_effect", ",", ")", "if", "order", ".", "type", "==", "ORDER_TYPE", ".", "MARKET", ":", "order", ".", "set_frozen_price", "(", "market_price", ")", "if", "env", ".", "can_submit_order", "(", "order", ")", ":", "env", ".", "broker", ".", "submit_order", "(", "order", ")", "return", "order" ]
通用下单函数,策略可以通过该函数自由选择参数下单。 :param id_or_ins: 下单标的物 :type id_or_ins: :class:`~Instrument` object | `str` :param float amount: 下单量,需为正数 :param side: 多空方向,多(SIDE.BUY)或空(SIDE.SELL) :type side: :class:`~SIDE` enum :param float price: 下单价格,默认为None,表示市价单 :param position_effect: 开平方向,开仓(POSITION_EFFECT.OPEN),平仓(POSITION.CLOSE)或平今(POSITION_EFFECT.CLOSE_TODAY),交易股票不需要该参数 :type position_effect: :class:`~POSITION_EFFECT` enum :return: :class:`~Order` object | None :example: .. code-block:: python # 购买 2000 股的平安银行股票,并以市价单发送: submit_order('000001.XSHE', 2000, SIDE.BUY) # 平 10 份 RB1812 多方向的今仓,并以 4000 的价格发送限价单 submit_order('RB1812', 10, SIDE.SELL, price=4000, position_effect=POSITION_EFFECT.CLOSE_TODAY)
[ "通用下单函数,策略可以通过该函数自由选择参数下单。" ]
ac40a62d4e7eca9494b4d0a14f46facf5616820c
https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/api/api_base.py#L224-L291
train
ricequant/rqalpha
rqalpha/api/api_base.py
cancel_order
def cancel_order(order): """ 撤单 :param order: 需要撤销的order对象 :type order: :class:`~Order` object """ env = Environment.get_instance() if env.can_cancel_order(order): env.broker.cancel_order(order) return order
python
def cancel_order(order): """ 撤单 :param order: 需要撤销的order对象 :type order: :class:`~Order` object """ env = Environment.get_instance() if env.can_cancel_order(order): env.broker.cancel_order(order) return order
[ "def", "cancel_order", "(", "order", ")", ":", "env", "=", "Environment", ".", "get_instance", "(", ")", "if", "env", ".", "can_cancel_order", "(", "order", ")", ":", "env", ".", "broker", ".", "cancel_order", "(", "order", ")", "return", "order" ]
撤单 :param order: 需要撤销的order对象 :type order: :class:`~Order` object
[ "撤单" ]
ac40a62d4e7eca9494b4d0a14f46facf5616820c
https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/api/api_base.py#L304-L314
train
ricequant/rqalpha
rqalpha/api/api_base.py
update_universe
def update_universe(id_or_symbols): """ 该方法用于更新现在关注的证券的集合(e.g.:股票池)。PS:会在下一个bar事件触发时候产生(新的关注的股票池更新)效果。并且update_universe会是覆盖(overwrite)的操作而不是在已有的股票池的基础上进行增量添加。比如已有的股票池为['000001.XSHE', '000024.XSHE']然后调用了update_universe(['000030.XSHE'])之后,股票池就会变成000030.XSHE一个股票了,随后的数据更新也只会跟踪000030.XSHE这一个股票了。 :param id_or_symbols: 标的物 :type id_or_symbols: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`] """ if isinstance(id_or_symbols, (six.string_types, Instrument)): id_or_symbols = [id_or_symbols] order_book_ids = set( assure_order_book_id(order_book_id) for order_book_id in id_or_symbols ) if order_book_ids != Environment.get_instance().get_universe(): Environment.get_instance().update_universe(order_book_ids)
python
def update_universe(id_or_symbols): """ 该方法用于更新现在关注的证券的集合(e.g.:股票池)。PS:会在下一个bar事件触发时候产生(新的关注的股票池更新)效果。并且update_universe会是覆盖(overwrite)的操作而不是在已有的股票池的基础上进行增量添加。比如已有的股票池为['000001.XSHE', '000024.XSHE']然后调用了update_universe(['000030.XSHE'])之后,股票池就会变成000030.XSHE一个股票了,随后的数据更新也只会跟踪000030.XSHE这一个股票了。 :param id_or_symbols: 标的物 :type id_or_symbols: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`] """ if isinstance(id_or_symbols, (six.string_types, Instrument)): id_or_symbols = [id_or_symbols] order_book_ids = set( assure_order_book_id(order_book_id) for order_book_id in id_or_symbols ) if order_book_ids != Environment.get_instance().get_universe(): Environment.get_instance().update_universe(order_book_ids)
[ "def", "update_universe", "(", "id_or_symbols", ")", ":", "if", "isinstance", "(", "id_or_symbols", ",", "(", "six", ".", "string_types", ",", "Instrument", ")", ")", ":", "id_or_symbols", "=", "[", "id_or_symbols", "]", "order_book_ids", "=", "set", "(", "assure_order_book_id", "(", "order_book_id", ")", "for", "order_book_id", "in", "id_or_symbols", ")", "if", "order_book_ids", "!=", "Environment", ".", "get_instance", "(", ")", ".", "get_universe", "(", ")", ":", "Environment", ".", "get_instance", "(", ")", ".", "update_universe", "(", "order_book_ids", ")" ]
该方法用于更新现在关注的证券的集合(e.g.:股票池)。PS:会在下一个bar事件触发时候产生(新的关注的股票池更新)效果。并且update_universe会是覆盖(overwrite)的操作而不是在已有的股票池的基础上进行增量添加。比如已有的股票池为['000001.XSHE', '000024.XSHE']然后调用了update_universe(['000030.XSHE'])之后,股票池就会变成000030.XSHE一个股票了,随后的数据更新也只会跟踪000030.XSHE这一个股票了。 :param id_or_symbols: 标的物 :type id_or_symbols: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`]
[ "该方法用于更新现在关注的证券的集合(e", ".", "g", ".", ":股票池)。PS:会在下一个bar事件触发时候产生(新的关注的股票池更新)效果。并且update_universe会是覆盖(overwrite)的操作而不是在已有的股票池的基础上进行增量添加。比如已有的股票池为", "[", "000001", ".", "XSHE", "000024", ".", "XSHE", "]", "然后调用了update_universe", "(", "[", "000030", ".", "XSHE", "]", ")", "之后,股票池就会变成000030", ".", "XSHE一个股票了,随后的数据更新也只会跟踪000030", ".", "XSHE这一个股票了。" ]
ac40a62d4e7eca9494b4d0a14f46facf5616820c
https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/api/api_base.py#L327-L340
train
ricequant/rqalpha
rqalpha/api/api_base.py
subscribe
def subscribe(id_or_symbols): """ 订阅合约行情。该操作会导致合约池内合约的增加,从而影响handle_bar中处理bar数据的数量。 需要注意,用户在初次编写策略时候需要首先订阅合约行情,否则handle_bar不会被触发。 :param id_or_symbols: 标的物 :type id_or_symbols: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`] """ current_universe = Environment.get_instance().get_universe() if isinstance(id_or_symbols, six.string_types): order_book_id = instruments(id_or_symbols).order_book_id current_universe.add(order_book_id) elif isinstance(id_or_symbols, Instrument): current_universe.add(id_or_symbols.order_book_id) elif isinstance(id_or_symbols, Iterable): for item in id_or_symbols: current_universe.add(assure_order_book_id(item)) else: raise RQInvalidArgument(_(u"unsupported order_book_id type")) verify_that("id_or_symbols")._are_valid_instruments("subscribe", id_or_symbols) Environment.get_instance().update_universe(current_universe)
python
def subscribe(id_or_symbols): """ 订阅合约行情。该操作会导致合约池内合约的增加,从而影响handle_bar中处理bar数据的数量。 需要注意,用户在初次编写策略时候需要首先订阅合约行情,否则handle_bar不会被触发。 :param id_or_symbols: 标的物 :type id_or_symbols: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`] """ current_universe = Environment.get_instance().get_universe() if isinstance(id_or_symbols, six.string_types): order_book_id = instruments(id_or_symbols).order_book_id current_universe.add(order_book_id) elif isinstance(id_or_symbols, Instrument): current_universe.add(id_or_symbols.order_book_id) elif isinstance(id_or_symbols, Iterable): for item in id_or_symbols: current_universe.add(assure_order_book_id(item)) else: raise RQInvalidArgument(_(u"unsupported order_book_id type")) verify_that("id_or_symbols")._are_valid_instruments("subscribe", id_or_symbols) Environment.get_instance().update_universe(current_universe)
[ "def", "subscribe", "(", "id_or_symbols", ")", ":", "current_universe", "=", "Environment", ".", "get_instance", "(", ")", ".", "get_universe", "(", ")", "if", "isinstance", "(", "id_or_symbols", ",", "six", ".", "string_types", ")", ":", "order_book_id", "=", "instruments", "(", "id_or_symbols", ")", ".", "order_book_id", "current_universe", ".", "add", "(", "order_book_id", ")", "elif", "isinstance", "(", "id_or_symbols", ",", "Instrument", ")", ":", "current_universe", ".", "add", "(", "id_or_symbols", ".", "order_book_id", ")", "elif", "isinstance", "(", "id_or_symbols", ",", "Iterable", ")", ":", "for", "item", "in", "id_or_symbols", ":", "current_universe", ".", "add", "(", "assure_order_book_id", "(", "item", ")", ")", "else", ":", "raise", "RQInvalidArgument", "(", "_", "(", "u\"unsupported order_book_id type\"", ")", ")", "verify_that", "(", "\"id_or_symbols\"", ")", ".", "_are_valid_instruments", "(", "\"subscribe\"", ",", "id_or_symbols", ")", "Environment", ".", "get_instance", "(", ")", ".", "update_universe", "(", "current_universe", ")" ]
订阅合约行情。该操作会导致合约池内合约的增加,从而影响handle_bar中处理bar数据的数量。 需要注意,用户在初次编写策略时候需要首先订阅合约行情,否则handle_bar不会被触发。 :param id_or_symbols: 标的物 :type id_or_symbols: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`]
[ "订阅合约行情。该操作会导致合约池内合约的增加,从而影响handle_bar中处理bar数据的数量。" ]
ac40a62d4e7eca9494b4d0a14f46facf5616820c
https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/api/api_base.py#L353-L374
train
ricequant/rqalpha
rqalpha/api/api_base.py
unsubscribe
def unsubscribe(id_or_symbols): """ 取消订阅合约行情。取消订阅会导致合约池内合约的减少,如果当前合约池中没有任何合约,则策略直接退出。 :param id_or_symbols: 标的物 :type id_or_symbols: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`] """ current_universe = Environment.get_instance().get_universe() if isinstance(id_or_symbols, six.string_types): order_book_id = instruments(id_or_symbols).order_book_id current_universe.discard(order_book_id) elif isinstance(id_or_symbols, Instrument): current_universe.discard(id_or_symbols.order_book_id) elif isinstance(id_or_symbols, Iterable): for item in id_or_symbols: i = assure_order_book_id(item) current_universe.discard(i) else: raise RQInvalidArgument(_(u"unsupported order_book_id type")) Environment.get_instance().update_universe(current_universe)
python
def unsubscribe(id_or_symbols): """ 取消订阅合约行情。取消订阅会导致合约池内合约的减少,如果当前合约池中没有任何合约,则策略直接退出。 :param id_or_symbols: 标的物 :type id_or_symbols: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`] """ current_universe = Environment.get_instance().get_universe() if isinstance(id_or_symbols, six.string_types): order_book_id = instruments(id_or_symbols).order_book_id current_universe.discard(order_book_id) elif isinstance(id_or_symbols, Instrument): current_universe.discard(id_or_symbols.order_book_id) elif isinstance(id_or_symbols, Iterable): for item in id_or_symbols: i = assure_order_book_id(item) current_universe.discard(i) else: raise RQInvalidArgument(_(u"unsupported order_book_id type")) Environment.get_instance().update_universe(current_universe)
[ "def", "unsubscribe", "(", "id_or_symbols", ")", ":", "current_universe", "=", "Environment", ".", "get_instance", "(", ")", ".", "get_universe", "(", ")", "if", "isinstance", "(", "id_or_symbols", ",", "six", ".", "string_types", ")", ":", "order_book_id", "=", "instruments", "(", "id_or_symbols", ")", ".", "order_book_id", "current_universe", ".", "discard", "(", "order_book_id", ")", "elif", "isinstance", "(", "id_or_symbols", ",", "Instrument", ")", ":", "current_universe", ".", "discard", "(", "id_or_symbols", ".", "order_book_id", ")", "elif", "isinstance", "(", "id_or_symbols", ",", "Iterable", ")", ":", "for", "item", "in", "id_or_symbols", ":", "i", "=", "assure_order_book_id", "(", "item", ")", "current_universe", ".", "discard", "(", "i", ")", "else", ":", "raise", "RQInvalidArgument", "(", "_", "(", "u\"unsupported order_book_id type\"", ")", ")", "Environment", ".", "get_instance", "(", ")", ".", "update_universe", "(", "current_universe", ")" ]
取消订阅合约行情。取消订阅会导致合约池内合约的减少,如果当前合约池中没有任何合约,则策略直接退出。 :param id_or_symbols: 标的物 :type id_or_symbols: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`]
[ "取消订阅合约行情。取消订阅会导致合约池内合约的减少,如果当前合约池中没有任何合约,则策略直接退出。" ]
ac40a62d4e7eca9494b4d0a14f46facf5616820c
https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/api/api_base.py#L387-L407
train
ricequant/rqalpha
rqalpha/api/api_base.py
get_yield_curve
def get_yield_curve(date=None, tenor=None): """ 获取某个国家市场指定日期的收益率曲线水平。 数据为2002年至今的中债国债收益率曲线,来源于中央国债登记结算有限责任公司。 :param date: 查询日期,默认为策略当前日期前一天 :type date: `str` | `date` | `datetime` | `pandas.Timestamp` :param str tenor: 标准期限,'0S' - 隔夜,'1M' - 1个月,'1Y' - 1年,默认为全部期限 :return: `pandas.DataFrame` - 查询时间段内无风险收益率曲线 :example: .. code-block:: python3 :linenos: [In] get_yield_curve('20130104') [Out] 0S 1M 2M 3M 6M 9M 1Y 2Y \ 2013-01-04 0.0196 0.0253 0.0288 0.0279 0.0280 0.0283 0.0292 0.0310 3Y 4Y ... 6Y 7Y 8Y 9Y 10Y \ 2013-01-04 0.0314 0.0318 ... 0.0342 0.0350 0.0353 0.0357 0.0361 ... """ env = Environment.get_instance() trading_date = env.trading_dt.date() yesterday = env.data_proxy.get_previous_trading_date(trading_date) if date is None: date = yesterday else: date = pd.Timestamp(date) if date > yesterday: raise RQInvalidArgument( "get_yield_curve: {} >= now({})".format(date, yesterday) ) return env.data_proxy.get_yield_curve(start_date=date, end_date=date, tenor=tenor)
python
def get_yield_curve(date=None, tenor=None): """ 获取某个国家市场指定日期的收益率曲线水平。 数据为2002年至今的中债国债收益率曲线,来源于中央国债登记结算有限责任公司。 :param date: 查询日期,默认为策略当前日期前一天 :type date: `str` | `date` | `datetime` | `pandas.Timestamp` :param str tenor: 标准期限,'0S' - 隔夜,'1M' - 1个月,'1Y' - 1年,默认为全部期限 :return: `pandas.DataFrame` - 查询时间段内无风险收益率曲线 :example: .. code-block:: python3 :linenos: [In] get_yield_curve('20130104') [Out] 0S 1M 2M 3M 6M 9M 1Y 2Y \ 2013-01-04 0.0196 0.0253 0.0288 0.0279 0.0280 0.0283 0.0292 0.0310 3Y 4Y ... 6Y 7Y 8Y 9Y 10Y \ 2013-01-04 0.0314 0.0318 ... 0.0342 0.0350 0.0353 0.0357 0.0361 ... """ env = Environment.get_instance() trading_date = env.trading_dt.date() yesterday = env.data_proxy.get_previous_trading_date(trading_date) if date is None: date = yesterday else: date = pd.Timestamp(date) if date > yesterday: raise RQInvalidArgument( "get_yield_curve: {} >= now({})".format(date, yesterday) ) return env.data_proxy.get_yield_curve(start_date=date, end_date=date, tenor=tenor)
[ "def", "get_yield_curve", "(", "date", "=", "None", ",", "tenor", "=", "None", ")", ":", "env", "=", "Environment", ".", "get_instance", "(", ")", "trading_date", "=", "env", ".", "trading_dt", ".", "date", "(", ")", "yesterday", "=", "env", ".", "data_proxy", ".", "get_previous_trading_date", "(", "trading_date", ")", "if", "date", "is", "None", ":", "date", "=", "yesterday", "else", ":", "date", "=", "pd", ".", "Timestamp", "(", "date", ")", "if", "date", ">", "yesterday", ":", "raise", "RQInvalidArgument", "(", "\"get_yield_curve: {} >= now({})\"", ".", "format", "(", "date", ",", "yesterday", ")", ")", "return", "env", ".", "data_proxy", ".", "get_yield_curve", "(", "start_date", "=", "date", ",", "end_date", "=", "date", ",", "tenor", "=", "tenor", ")" ]
获取某个国家市场指定日期的收益率曲线水平。 数据为2002年至今的中债国债收益率曲线,来源于中央国债登记结算有限责任公司。 :param date: 查询日期,默认为策略当前日期前一天 :type date: `str` | `date` | `datetime` | `pandas.Timestamp` :param str tenor: 标准期限,'0S' - 隔夜,'1M' - 1个月,'1Y' - 1年,默认为全部期限 :return: `pandas.DataFrame` - 查询时间段内无风险收益率曲线 :example: .. code-block:: python3 :linenos: [In] get_yield_curve('20130104') [Out] 0S 1M 2M 3M 6M 9M 1Y 2Y \ 2013-01-04 0.0196 0.0253 0.0288 0.0279 0.0280 0.0283 0.0292 0.0310 3Y 4Y ... 6Y 7Y 8Y 9Y 10Y \ 2013-01-04 0.0314 0.0318 ... 0.0342 0.0350 0.0353 0.0357 0.0361 ...
[ "获取某个国家市场指定日期的收益率曲线水平。" ]
ac40a62d4e7eca9494b4d0a14f46facf5616820c
https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/api/api_base.py#L423-L465
train
ricequant/rqalpha
rqalpha/api/api_base.py
history_bars
def history_bars( order_book_id, bar_count, frequency, fields=None, skip_suspended=True, include_now=False, adjust_type="pre", ): """ 获取指定合约的历史行情,同时支持日以及分钟历史数据。不能在init中调用。 注意,该API会自动跳过停牌数据。 日回测获取分钟历史数据:不支持 日回测获取日历史数据 ========================= =================================================== 调用时间 返回数据 ========================= =================================================== T日before_trading T-1日day bar T日handle_bar T日day bar ========================= =================================================== 分钟回测获取日历史数据 ========================= =================================================== 调用时间 返回数据 ========================= =================================================== T日before_trading T-1日day bar T日handle_bar T-1日day bar ========================= =================================================== 分钟回测获取分钟历史数据 ========================= =================================================== 调用时间 返回数据 ========================= =================================================== T日before_trading T-1日最后一个minute bar T日handle_bar T日当前minute bar ========================= =================================================== :param order_book_id: 合约代码 :type order_book_id: `str` :param int bar_count: 获取的历史数据数量,必填项 :param str frequency: 获取数据什么样的频率进行。'1d'或'1m'分别表示每日和每分钟,必填项 :param str fields: 返回数据字段。必填项。见下方列表。 ========================= =================================================== fields 字段名 ========================= =================================================== datetime 时间戳 open 开盘价 high 最高价 low 最低价 close 收盘价 volume 成交量 total_turnover 成交额 open_interest 持仓量(期货专用) basis_spread 期现差(股指期货专用) settlement 结算价(期货日线专用) prev_settlement 结算价(期货日线专用) ========================= =================================================== :param bool skip_suspended: 是否跳过停牌数据 :param bool include_now: 是否包含当前数据 :param str adjust_type: 复权类型,默认为前复权 pre;可选 pre, none, post :return: `ndarray`, 方便直接与talib等计算库对接,效率较history返回的DataFrame更高。 :example: 获取最近5天的日线收盘价序列(策略当前日期为20160706): .. code-block:: python3 :linenos: [In] logger.info(history_bars('000002.XSHE', 5, '1d', 'close')) [Out] [ 8.69 8.7 8.71 8.81 8.81] """ order_book_id = assure_order_book_id(order_book_id) env = Environment.get_instance() dt = env.calendar_dt if frequency[-1] not in {"m", "d"}: raise RQInvalidArgument("invalid frequency {}".format(frequency)) if frequency[-1] == "m" and env.config.base.frequency == "1d": raise RQInvalidArgument("can not get minute history in day back test") if frequency[-1] == "d" and frequency != "1d": raise RQInvalidArgument("invalid frequency") if adjust_type not in {"pre", "post", "none"}: raise RuntimeError("invalid adjust_type") if frequency == "1d": sys_frequency = Environment.get_instance().config.base.frequency if ( sys_frequency in ["1m", "tick"] and not include_now and ExecutionContext.phase() != EXECUTION_PHASE.AFTER_TRADING ) or (ExecutionContext.phase() == EXECUTION_PHASE.BEFORE_TRADING): dt = env.data_proxy.get_previous_trading_date(env.trading_dt.date()) # 当 EXECUTION_PHASE.BEFORE_TRADING 的时候,强制 include_now 为 False include_now = False if sys_frequency == "1d": # 日回测不支持 include_now include_now = False if fields is None: fields = ["datetime", "open", "high", "low", "close", "volume"] return env.data_proxy.history_bars( order_book_id, bar_count, frequency, fields, dt, skip_suspended=skip_suspended, include_now=include_now, adjust_type=adjust_type, adjust_orig=env.trading_dt, )
python
def history_bars( order_book_id, bar_count, frequency, fields=None, skip_suspended=True, include_now=False, adjust_type="pre", ): """ 获取指定合约的历史行情,同时支持日以及分钟历史数据。不能在init中调用。 注意,该API会自动跳过停牌数据。 日回测获取分钟历史数据:不支持 日回测获取日历史数据 ========================= =================================================== 调用时间 返回数据 ========================= =================================================== T日before_trading T-1日day bar T日handle_bar T日day bar ========================= =================================================== 分钟回测获取日历史数据 ========================= =================================================== 调用时间 返回数据 ========================= =================================================== T日before_trading T-1日day bar T日handle_bar T-1日day bar ========================= =================================================== 分钟回测获取分钟历史数据 ========================= =================================================== 调用时间 返回数据 ========================= =================================================== T日before_trading T-1日最后一个minute bar T日handle_bar T日当前minute bar ========================= =================================================== :param order_book_id: 合约代码 :type order_book_id: `str` :param int bar_count: 获取的历史数据数量,必填项 :param str frequency: 获取数据什么样的频率进行。'1d'或'1m'分别表示每日和每分钟,必填项 :param str fields: 返回数据字段。必填项。见下方列表。 ========================= =================================================== fields 字段名 ========================= =================================================== datetime 时间戳 open 开盘价 high 最高价 low 最低价 close 收盘价 volume 成交量 total_turnover 成交额 open_interest 持仓量(期货专用) basis_spread 期现差(股指期货专用) settlement 结算价(期货日线专用) prev_settlement 结算价(期货日线专用) ========================= =================================================== :param bool skip_suspended: 是否跳过停牌数据 :param bool include_now: 是否包含当前数据 :param str adjust_type: 复权类型,默认为前复权 pre;可选 pre, none, post :return: `ndarray`, 方便直接与talib等计算库对接,效率较history返回的DataFrame更高。 :example: 获取最近5天的日线收盘价序列(策略当前日期为20160706): .. code-block:: python3 :linenos: [In] logger.info(history_bars('000002.XSHE', 5, '1d', 'close')) [Out] [ 8.69 8.7 8.71 8.81 8.81] """ order_book_id = assure_order_book_id(order_book_id) env = Environment.get_instance() dt = env.calendar_dt if frequency[-1] not in {"m", "d"}: raise RQInvalidArgument("invalid frequency {}".format(frequency)) if frequency[-1] == "m" and env.config.base.frequency == "1d": raise RQInvalidArgument("can not get minute history in day back test") if frequency[-1] == "d" and frequency != "1d": raise RQInvalidArgument("invalid frequency") if adjust_type not in {"pre", "post", "none"}: raise RuntimeError("invalid adjust_type") if frequency == "1d": sys_frequency = Environment.get_instance().config.base.frequency if ( sys_frequency in ["1m", "tick"] and not include_now and ExecutionContext.phase() != EXECUTION_PHASE.AFTER_TRADING ) or (ExecutionContext.phase() == EXECUTION_PHASE.BEFORE_TRADING): dt = env.data_proxy.get_previous_trading_date(env.trading_dt.date()) # 当 EXECUTION_PHASE.BEFORE_TRADING 的时候,强制 include_now 为 False include_now = False if sys_frequency == "1d": # 日回测不支持 include_now include_now = False if fields is None: fields = ["datetime", "open", "high", "low", "close", "volume"] return env.data_proxy.history_bars( order_book_id, bar_count, frequency, fields, dt, skip_suspended=skip_suspended, include_now=include_now, adjust_type=adjust_type, adjust_orig=env.trading_dt, )
[ "def", "history_bars", "(", "order_book_id", ",", "bar_count", ",", "frequency", ",", "fields", "=", "None", ",", "skip_suspended", "=", "True", ",", "include_now", "=", "False", ",", "adjust_type", "=", "\"pre\"", ",", ")", ":", "order_book_id", "=", "assure_order_book_id", "(", "order_book_id", ")", "env", "=", "Environment", ".", "get_instance", "(", ")", "dt", "=", "env", ".", "calendar_dt", "if", "frequency", "[", "-", "1", "]", "not", "in", "{", "\"m\"", ",", "\"d\"", "}", ":", "raise", "RQInvalidArgument", "(", "\"invalid frequency {}\"", ".", "format", "(", "frequency", ")", ")", "if", "frequency", "[", "-", "1", "]", "==", "\"m\"", "and", "env", ".", "config", ".", "base", ".", "frequency", "==", "\"1d\"", ":", "raise", "RQInvalidArgument", "(", "\"can not get minute history in day back test\"", ")", "if", "frequency", "[", "-", "1", "]", "==", "\"d\"", "and", "frequency", "!=", "\"1d\"", ":", "raise", "RQInvalidArgument", "(", "\"invalid frequency\"", ")", "if", "adjust_type", "not", "in", "{", "\"pre\"", ",", "\"post\"", ",", "\"none\"", "}", ":", "raise", "RuntimeError", "(", "\"invalid adjust_type\"", ")", "if", "frequency", "==", "\"1d\"", ":", "sys_frequency", "=", "Environment", ".", "get_instance", "(", ")", ".", "config", ".", "base", ".", "frequency", "if", "(", "sys_frequency", "in", "[", "\"1m\"", ",", "\"tick\"", "]", "and", "not", "include_now", "and", "ExecutionContext", ".", "phase", "(", ")", "!=", "EXECUTION_PHASE", ".", "AFTER_TRADING", ")", "or", "(", "ExecutionContext", ".", "phase", "(", ")", "==", "EXECUTION_PHASE", ".", "BEFORE_TRADING", ")", ":", "dt", "=", "env", ".", "data_proxy", ".", "get_previous_trading_date", "(", "env", ".", "trading_dt", ".", "date", "(", ")", ")", "# 当 EXECUTION_PHASE.BEFORE_TRADING 的时候,强制 include_now 为 False", "include_now", "=", "False", "if", "sys_frequency", "==", "\"1d\"", ":", "# 日回测不支持 include_now", "include_now", "=", "False", "if", "fields", "is", "None", ":", "fields", "=", "[", "\"datetime\"", ",", "\"open\"", ",", "\"high\"", ",", "\"low\"", ",", "\"close\"", ",", "\"volume\"", "]", "return", "env", ".", "data_proxy", ".", "history_bars", "(", "order_book_id", ",", "bar_count", ",", "frequency", ",", "fields", ",", "dt", ",", "skip_suspended", "=", "skip_suspended", ",", "include_now", "=", "include_now", ",", "adjust_type", "=", "adjust_type", ",", "adjust_orig", "=", "env", ".", "trading_dt", ",", ")" ]
获取指定合约的历史行情,同时支持日以及分钟历史数据。不能在init中调用。 注意,该API会自动跳过停牌数据。 日回测获取分钟历史数据:不支持 日回测获取日历史数据 ========================= =================================================== 调用时间 返回数据 ========================= =================================================== T日before_trading T-1日day bar T日handle_bar T日day bar ========================= =================================================== 分钟回测获取日历史数据 ========================= =================================================== 调用时间 返回数据 ========================= =================================================== T日before_trading T-1日day bar T日handle_bar T-1日day bar ========================= =================================================== 分钟回测获取分钟历史数据 ========================= =================================================== 调用时间 返回数据 ========================= =================================================== T日before_trading T-1日最后一个minute bar T日handle_bar T日当前minute bar ========================= =================================================== :param order_book_id: 合约代码 :type order_book_id: `str` :param int bar_count: 获取的历史数据数量,必填项 :param str frequency: 获取数据什么样的频率进行。'1d'或'1m'分别表示每日和每分钟,必填项 :param str fields: 返回数据字段。必填项。见下方列表。 ========================= =================================================== fields 字段名 ========================= =================================================== datetime 时间戳 open 开盘价 high 最高价 low 最低价 close 收盘价 volume 成交量 total_turnover 成交额 open_interest 持仓量(期货专用) basis_spread 期现差(股指期货专用) settlement 结算价(期货日线专用) prev_settlement 结算价(期货日线专用) ========================= =================================================== :param bool skip_suspended: 是否跳过停牌数据 :param bool include_now: 是否包含当前数据 :param str adjust_type: 复权类型,默认为前复权 pre;可选 pre, none, post :return: `ndarray`, 方便直接与talib等计算库对接,效率较history返回的DataFrame更高。 :example: 获取最近5天的日线收盘价序列(策略当前日期为20160706): .. code-block:: python3 :linenos: [In] logger.info(history_bars('000002.XSHE', 5, '1d', 'close')) [Out] [ 8.69 8.7 8.71 8.81 8.81]
[ "获取指定合约的历史行情,同时支持日以及分钟历史数据。不能在init中调用。", "注意,该API会自动跳过停牌数据。" ]
ac40a62d4e7eca9494b4d0a14f46facf5616820c
https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/api/api_base.py#L487-L612
train
ricequant/rqalpha
rqalpha/api/api_base.py
all_instruments
def all_instruments(type=None, date=None): """ 获取某个国家市场的所有合约信息。使用者可以通过这一方法很快地对合约信息有一个快速了解,目前仅支持中国市场。 :param str type: 需要查询合约类型,例如:type='CS'代表股票。默认是所有类型 :param date: 查询时间点 :type date: `str` | `datetime` | `date` :return: `pandas DataFrame` 所有合约的基本信息。 其中type参数传入的合约类型和对应的解释如下: ========================= =================================================== 合约类型 说明 ========================= =================================================== CS Common Stock, 即股票 ETF Exchange Traded Fund, 即交易所交易基金 LOF Listed Open-Ended Fund,即上市型开放式基金 FenjiMu Fenji Mu Fund, 即分级母基金 FenjiA Fenji A Fund, 即分级A类基金 FenjiB Fenji B Funds, 即分级B类基金 INDX Index, 即指数 Future Futures,即期货,包含股指、国债和商品期货 ========================= =================================================== :example: 获取中国市场所有分级基金的基础信息: .. code-block:: python3 :linenos: [In]all_instruments('FenjiA') [Out] abbrev_symbol order_book_id product sector_code symbol 0 CYGA 150303.XSHE null null 华安创业板50A 1 JY500A 150088.XSHE null null 金鹰500A 2 TD500A 150053.XSHE null null 泰达稳健 3 HS500A 150110.XSHE null null 华商500A 4 QSAJ 150235.XSHE null null 鹏华证券A ... """ env = Environment.get_instance() if date is None: dt = env.trading_dt else: dt = pd.Timestamp(date).to_pydatetime() dt = min(dt, env.trading_dt) if type is not None: if isinstance(type, six.string_types): type = [type] types = set() for t in type: if t == "Stock": types.add("CS") elif t == "Fund": types.update(["ETF", "LOF", "SF", "FenjiA", "FenjiB", "FenjiMu"]) else: types.add(t) else: types = None result = env.data_proxy.all_instruments(types, dt) if types is not None and len(types) == 1: return pd.DataFrame([i.__dict__ for i in result]) return pd.DataFrame( [ [i.order_book_id, i.symbol, i.type, i.listed_date, i.de_listed_date] for i in result ], columns=["order_book_id", "symbol", "type", "listed_date", "de_listed_date"], )
python
def all_instruments(type=None, date=None): """ 获取某个国家市场的所有合约信息。使用者可以通过这一方法很快地对合约信息有一个快速了解,目前仅支持中国市场。 :param str type: 需要查询合约类型,例如:type='CS'代表股票。默认是所有类型 :param date: 查询时间点 :type date: `str` | `datetime` | `date` :return: `pandas DataFrame` 所有合约的基本信息。 其中type参数传入的合约类型和对应的解释如下: ========================= =================================================== 合约类型 说明 ========================= =================================================== CS Common Stock, 即股票 ETF Exchange Traded Fund, 即交易所交易基金 LOF Listed Open-Ended Fund,即上市型开放式基金 FenjiMu Fenji Mu Fund, 即分级母基金 FenjiA Fenji A Fund, 即分级A类基金 FenjiB Fenji B Funds, 即分级B类基金 INDX Index, 即指数 Future Futures,即期货,包含股指、国债和商品期货 ========================= =================================================== :example: 获取中国市场所有分级基金的基础信息: .. code-block:: python3 :linenos: [In]all_instruments('FenjiA') [Out] abbrev_symbol order_book_id product sector_code symbol 0 CYGA 150303.XSHE null null 华安创业板50A 1 JY500A 150088.XSHE null null 金鹰500A 2 TD500A 150053.XSHE null null 泰达稳健 3 HS500A 150110.XSHE null null 华商500A 4 QSAJ 150235.XSHE null null 鹏华证券A ... """ env = Environment.get_instance() if date is None: dt = env.trading_dt else: dt = pd.Timestamp(date).to_pydatetime() dt = min(dt, env.trading_dt) if type is not None: if isinstance(type, six.string_types): type = [type] types = set() for t in type: if t == "Stock": types.add("CS") elif t == "Fund": types.update(["ETF", "LOF", "SF", "FenjiA", "FenjiB", "FenjiMu"]) else: types.add(t) else: types = None result = env.data_proxy.all_instruments(types, dt) if types is not None and len(types) == 1: return pd.DataFrame([i.__dict__ for i in result]) return pd.DataFrame( [ [i.order_book_id, i.symbol, i.type, i.listed_date, i.de_listed_date] for i in result ], columns=["order_book_id", "symbol", "type", "listed_date", "de_listed_date"], )
[ "def", "all_instruments", "(", "type", "=", "None", ",", "date", "=", "None", ")", ":", "env", "=", "Environment", ".", "get_instance", "(", ")", "if", "date", "is", "None", ":", "dt", "=", "env", ".", "trading_dt", "else", ":", "dt", "=", "pd", ".", "Timestamp", "(", "date", ")", ".", "to_pydatetime", "(", ")", "dt", "=", "min", "(", "dt", ",", "env", ".", "trading_dt", ")", "if", "type", "is", "not", "None", ":", "if", "isinstance", "(", "type", ",", "six", ".", "string_types", ")", ":", "type", "=", "[", "type", "]", "types", "=", "set", "(", ")", "for", "t", "in", "type", ":", "if", "t", "==", "\"Stock\"", ":", "types", ".", "add", "(", "\"CS\"", ")", "elif", "t", "==", "\"Fund\"", ":", "types", ".", "update", "(", "[", "\"ETF\"", ",", "\"LOF\"", ",", "\"SF\"", ",", "\"FenjiA\"", ",", "\"FenjiB\"", ",", "\"FenjiMu\"", "]", ")", "else", ":", "types", ".", "add", "(", "t", ")", "else", ":", "types", "=", "None", "result", "=", "env", ".", "data_proxy", ".", "all_instruments", "(", "types", ",", "dt", ")", "if", "types", "is", "not", "None", "and", "len", "(", "types", ")", "==", "1", ":", "return", "pd", ".", "DataFrame", "(", "[", "i", ".", "__dict__", "for", "i", "in", "result", "]", ")", "return", "pd", ".", "DataFrame", "(", "[", "[", "i", ".", "order_book_id", ",", "i", ".", "symbol", ",", "i", ".", "type", ",", "i", ".", "listed_date", ",", "i", ".", "de_listed_date", "]", "for", "i", "in", "result", "]", ",", "columns", "=", "[", "\"order_book_id\"", ",", "\"symbol\"", ",", "\"type\"", ",", "\"listed_date\"", ",", "\"de_listed_date\"", "]", ",", ")" ]
获取某个国家市场的所有合约信息。使用者可以通过这一方法很快地对合约信息有一个快速了解,目前仅支持中国市场。 :param str type: 需要查询合约类型,例如:type='CS'代表股票。默认是所有类型 :param date: 查询时间点 :type date: `str` | `datetime` | `date` :return: `pandas DataFrame` 所有合约的基本信息。 其中type参数传入的合约类型和对应的解释如下: ========================= =================================================== 合约类型 说明 ========================= =================================================== CS Common Stock, 即股票 ETF Exchange Traded Fund, 即交易所交易基金 LOF Listed Open-Ended Fund,即上市型开放式基金 FenjiMu Fenji Mu Fund, 即分级母基金 FenjiA Fenji A Fund, 即分级A类基金 FenjiB Fenji B Funds, 即分级B类基金 INDX Index, 即指数 Future Futures,即期货,包含股指、国债和商品期货 ========================= =================================================== :example: 获取中国市场所有分级基金的基础信息: .. code-block:: python3 :linenos: [In]all_instruments('FenjiA') [Out] abbrev_symbol order_book_id product sector_code symbol 0 CYGA 150303.XSHE null null 华安创业板50A 1 JY500A 150088.XSHE null null 金鹰500A 2 TD500A 150053.XSHE null null 泰达稳健 3 HS500A 150110.XSHE null null 华商500A 4 QSAJ 150235.XSHE null null 鹏华证券A ...
[ "获取某个国家市场的所有合约信息。使用者可以通过这一方法很快地对合约信息有一个快速了解,目前仅支持中国市场。" ]
ac40a62d4e7eca9494b4d0a14f46facf5616820c
https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/api/api_base.py#L630-L707
train
ricequant/rqalpha
rqalpha/api/api_base.py
current_snapshot
def current_snapshot(id_or_symbol): """ 获得当前市场快照数据。只能在日内交易阶段调用,获取当日调用时点的市场快照数据。 市场快照数据记录了每日从开盘到当前的数据信息,可以理解为一个动态的day bar数据。 在目前分钟回测中,快照数据为当日所有分钟线累积而成,一般情况下,最后一个分钟线获取到的快照数据应当与当日的日线行情保持一致。 需要注意,在实盘模拟中,该函数返回的是调用当时的市场快照情况,所以在同一个handle_bar中不同时点调用可能返回的数据不同。 如果当日截止到调用时候对应股票没有任何成交,那么snapshot中的close, high, low, last几个价格水平都将以0表示。 :param str id_or_symbol: 合约代码或简称 :return: :class:`~Snapshot` :example: 在handle_bar中调用该函数,假设策略当前时间是20160104 09:33: .. code-block:: python3 :linenos: [In] logger.info(current_snapshot('000001.XSHE')) [Out] 2016-01-04 09:33:00.00 INFO Snapshot(order_book_id: '000001.XSHE', datetime: datetime.datetime(2016, 1, 4, 9, 33), open: 10.0, high: 10.025, low: 9.9667, last: 9.9917, volume: 2050320, total_turnover: 20485195, prev_close: 9.99) """ env = Environment.get_instance() frequency = env.config.base.frequency order_book_id = assure_order_book_id(id_or_symbol) dt = env.calendar_dt if env.config.base.run_type == RUN_TYPE.BACKTEST: if ExecutionContext.phase() == EXECUTION_PHASE.BEFORE_TRADING: dt = env.data_proxy.get_previous_trading_date(env.trading_dt.date()) return env.data_proxy.current_snapshot(order_book_id, "1d", dt) elif ExecutionContext.phase() == EXECUTION_PHASE.AFTER_TRADING: return env.data_proxy.current_snapshot(order_book_id, "1d", dt) # PT、实盘直接取最新快照,忽略 frequency, dt 参数 return env.data_proxy.current_snapshot(order_book_id, frequency, dt)
python
def current_snapshot(id_or_symbol): """ 获得当前市场快照数据。只能在日内交易阶段调用,获取当日调用时点的市场快照数据。 市场快照数据记录了每日从开盘到当前的数据信息,可以理解为一个动态的day bar数据。 在目前分钟回测中,快照数据为当日所有分钟线累积而成,一般情况下,最后一个分钟线获取到的快照数据应当与当日的日线行情保持一致。 需要注意,在实盘模拟中,该函数返回的是调用当时的市场快照情况,所以在同一个handle_bar中不同时点调用可能返回的数据不同。 如果当日截止到调用时候对应股票没有任何成交,那么snapshot中的close, high, low, last几个价格水平都将以0表示。 :param str id_or_symbol: 合约代码或简称 :return: :class:`~Snapshot` :example: 在handle_bar中调用该函数,假设策略当前时间是20160104 09:33: .. code-block:: python3 :linenos: [In] logger.info(current_snapshot('000001.XSHE')) [Out] 2016-01-04 09:33:00.00 INFO Snapshot(order_book_id: '000001.XSHE', datetime: datetime.datetime(2016, 1, 4, 9, 33), open: 10.0, high: 10.025, low: 9.9667, last: 9.9917, volume: 2050320, total_turnover: 20485195, prev_close: 9.99) """ env = Environment.get_instance() frequency = env.config.base.frequency order_book_id = assure_order_book_id(id_or_symbol) dt = env.calendar_dt if env.config.base.run_type == RUN_TYPE.BACKTEST: if ExecutionContext.phase() == EXECUTION_PHASE.BEFORE_TRADING: dt = env.data_proxy.get_previous_trading_date(env.trading_dt.date()) return env.data_proxy.current_snapshot(order_book_id, "1d", dt) elif ExecutionContext.phase() == EXECUTION_PHASE.AFTER_TRADING: return env.data_proxy.current_snapshot(order_book_id, "1d", dt) # PT、实盘直接取最新快照,忽略 frequency, dt 参数 return env.data_proxy.current_snapshot(order_book_id, frequency, dt)
[ "def", "current_snapshot", "(", "id_or_symbol", ")", ":", "env", "=", "Environment", ".", "get_instance", "(", ")", "frequency", "=", "env", ".", "config", ".", "base", ".", "frequency", "order_book_id", "=", "assure_order_book_id", "(", "id_or_symbol", ")", "dt", "=", "env", ".", "calendar_dt", "if", "env", ".", "config", ".", "base", ".", "run_type", "==", "RUN_TYPE", ".", "BACKTEST", ":", "if", "ExecutionContext", ".", "phase", "(", ")", "==", "EXECUTION_PHASE", ".", "BEFORE_TRADING", ":", "dt", "=", "env", ".", "data_proxy", ".", "get_previous_trading_date", "(", "env", ".", "trading_dt", ".", "date", "(", ")", ")", "return", "env", ".", "data_proxy", ".", "current_snapshot", "(", "order_book_id", ",", "\"1d\"", ",", "dt", ")", "elif", "ExecutionContext", ".", "phase", "(", ")", "==", "EXECUTION_PHASE", ".", "AFTER_TRADING", ":", "return", "env", ".", "data_proxy", ".", "current_snapshot", "(", "order_book_id", ",", "\"1d\"", ",", "dt", ")", "# PT、实盘直接取最新快照,忽略 frequency, dt 参数", "return", "env", ".", "data_proxy", ".", "current_snapshot", "(", "order_book_id", ",", "frequency", ",", "dt", ")" ]
获得当前市场快照数据。只能在日内交易阶段调用,获取当日调用时点的市场快照数据。 市场快照数据记录了每日从开盘到当前的数据信息,可以理解为一个动态的day bar数据。 在目前分钟回测中,快照数据为当日所有分钟线累积而成,一般情况下,最后一个分钟线获取到的快照数据应当与当日的日线行情保持一致。 需要注意,在实盘模拟中,该函数返回的是调用当时的市场快照情况,所以在同一个handle_bar中不同时点调用可能返回的数据不同。 如果当日截止到调用时候对应股票没有任何成交,那么snapshot中的close, high, low, last几个价格水平都将以0表示。 :param str id_or_symbol: 合约代码或简称 :return: :class:`~Snapshot` :example: 在handle_bar中调用该函数,假设策略当前时间是20160104 09:33: .. code-block:: python3 :linenos: [In] logger.info(current_snapshot('000001.XSHE')) [Out] 2016-01-04 09:33:00.00 INFO Snapshot(order_book_id: '000001.XSHE', datetime: datetime.datetime(2016, 1, 4, 9, 33), open: 10.0, high: 10.025, low: 9.9667, last: 9.9917, volume: 2050320, total_turnover: 20485195, prev_close: 9.99)
[ "获得当前市场快照数据。只能在日内交易阶段调用,获取当日调用时点的市场快照数据。", "市场快照数据记录了每日从开盘到当前的数据信息,可以理解为一个动态的day", "bar数据。", "在目前分钟回测中,快照数据为当日所有分钟线累积而成,一般情况下,最后一个分钟线获取到的快照数据应当与当日的日线行情保持一致。", "需要注意,在实盘模拟中,该函数返回的是调用当时的市场快照情况,所以在同一个handle_bar中不同时点调用可能返回的数据不同。", "如果当日截止到调用时候对应股票没有任何成交,那么snapshot中的close", "high", "low", "last几个价格水平都将以0表示。" ]
ac40a62d4e7eca9494b4d0a14f46facf5616820c
https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/api/api_base.py#L989-L1028
train
ricequant/rqalpha
rqalpha/mod/rqalpha_mod_sys_accounts/account_model/stock_account.py
StockAccount.dividend_receivable
def dividend_receivable(self): """ [float] 投资组合在分红现金收到账面之前的应收分红部分。具体细节在分红部分 """ return sum(d['quantity'] * d['dividend_per_share'] for d in six.itervalues(self._dividend_receivable))
python
def dividend_receivable(self): """ [float] 投资组合在分红现金收到账面之前的应收分红部分。具体细节在分红部分 """ return sum(d['quantity'] * d['dividend_per_share'] for d in six.itervalues(self._dividend_receivable))
[ "def", "dividend_receivable", "(", "self", ")", ":", "return", "sum", "(", "d", "[", "'quantity'", "]", "*", "d", "[", "'dividend_per_share'", "]", "for", "d", "in", "six", ".", "itervalues", "(", "self", ".", "_dividend_receivable", ")", ")" ]
[float] 投资组合在分红现金收到账面之前的应收分红部分。具体细节在分红部分
[ "[", "float", "]", "投资组合在分红现金收到账面之前的应收分红部分。具体细节在分红部分" ]
ac40a62d4e7eca9494b4d0a14f46facf5616820c
https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/mod/rqalpha_mod_sys_accounts/account_model/stock_account.py#L247-L251
train
ricequant/rqalpha
rqalpha/interface.py
AbstractDataSource.history_bars
def history_bars(self, instrument, bar_count, frequency, fields, dt, skip_suspended=True, include_now=False, adjust_type='pre', adjust_orig=None): """ 获取历史数据 :param instrument: 合约对象 :type instrument: :class:`~Instrument` :param int bar_count: 获取的历史数据数量 :param str frequency: 周期频率,`1d` 表示日周期, `1m` 表示分钟周期 :param str fields: 返回数据字段 ========================= =================================================== fields 字段名 ========================= =================================================== datetime 时间戳 open 开盘价 high 最高价 low 最低价 close 收盘价 volume 成交量 total_turnover 成交额 datetime int类型时间戳 open_interest 持仓量(期货专用) basis_spread 期现差(股指期货专用) settlement 结算价(期货日线专用) prev_settlement 结算价(期货日线专用) ========================= =================================================== :param datetime.datetime dt: 时间 :param bool skip_suspended: 是否跳过停牌日 :param bool include_now: 是否包含当天最新数据 :param str adjust_type: 复权类型,'pre', 'none', 'post' :param datetime.datetime adjust_orig: 复权起点; :return: `numpy.ndarray` """ raise NotImplementedError
python
def history_bars(self, instrument, bar_count, frequency, fields, dt, skip_suspended=True, include_now=False, adjust_type='pre', adjust_orig=None): """ 获取历史数据 :param instrument: 合约对象 :type instrument: :class:`~Instrument` :param int bar_count: 获取的历史数据数量 :param str frequency: 周期频率,`1d` 表示日周期, `1m` 表示分钟周期 :param str fields: 返回数据字段 ========================= =================================================== fields 字段名 ========================= =================================================== datetime 时间戳 open 开盘价 high 最高价 low 最低价 close 收盘价 volume 成交量 total_turnover 成交额 datetime int类型时间戳 open_interest 持仓量(期货专用) basis_spread 期现差(股指期货专用) settlement 结算价(期货日线专用) prev_settlement 结算价(期货日线专用) ========================= =================================================== :param datetime.datetime dt: 时间 :param bool skip_suspended: 是否跳过停牌日 :param bool include_now: 是否包含当天最新数据 :param str adjust_type: 复权类型,'pre', 'none', 'post' :param datetime.datetime adjust_orig: 复权起点; :return: `numpy.ndarray` """ raise NotImplementedError
[ "def", "history_bars", "(", "self", ",", "instrument", ",", "bar_count", ",", "frequency", ",", "fields", ",", "dt", ",", "skip_suspended", "=", "True", ",", "include_now", "=", "False", ",", "adjust_type", "=", "'pre'", ",", "adjust_orig", "=", "None", ")", ":", "raise", "NotImplementedError" ]
获取历史数据 :param instrument: 合约对象 :type instrument: :class:`~Instrument` :param int bar_count: 获取的历史数据数量 :param str frequency: 周期频率,`1d` 表示日周期, `1m` 表示分钟周期 :param str fields: 返回数据字段 ========================= =================================================== fields 字段名 ========================= =================================================== datetime 时间戳 open 开盘价 high 最高价 low 最低价 close 收盘价 volume 成交量 total_turnover 成交额 datetime int类型时间戳 open_interest 持仓量(期货专用) basis_spread 期现差(股指期货专用) settlement 结算价(期货日线专用) prev_settlement 结算价(期货日线专用) ========================= =================================================== :param datetime.datetime dt: 时间 :param bool skip_suspended: 是否跳过停牌日 :param bool include_now: 是否包含当天最新数据 :param str adjust_type: 复权类型,'pre', 'none', 'post' :param datetime.datetime adjust_orig: 复权起点; :return: `numpy.ndarray`
[ "获取历史数据" ]
ac40a62d4e7eca9494b4d0a14f46facf5616820c
https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/interface.py#L360-L398
train
ricequant/rqalpha
rqalpha/mod/rqalpha_mod_sys_accounts/api/api_stock.py
order_shares
def order_shares(id_or_ins, amount, price=None, style=None): """ 落指定股数的买/卖单,最常见的落单方式之一。如有需要落单类型当做一个参量传入,如果忽略掉落单类型,那么默认是市价单(market order)。 :param id_or_ins: 下单标的物 :type id_or_ins: :class:`~Instrument` object | `str` :param int amount: 下单量, 正数代表买入,负数代表卖出。将会根据一手xx股来向下调整到一手的倍数,比如中国A股就是调整成100股的倍数。 :param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要用于简化 `style` 参数。 :param style: 下单类型, 默认是市价单。目前支持的订单类型有 :class:`~LimitOrder` 和 :class:`~MarketOrder` :type style: `OrderStyle` object :return: :class:`~Order` object | None :example: .. code-block:: python #购买Buy 2000 股的平安银行股票,并以市价单发送: order_shares('000001.XSHE', 2000) #卖出2000股的平安银行股票,并以市价单发送: order_shares('000001.XSHE', -2000) #购买1000股的平安银行股票,并以限价单发送,价格为¥10: order_shares('000001.XSHG', 1000, style=LimitOrder(10)) """ if amount == 0: # 如果下单量为0,则认为其并没有发单,则直接返回None user_system_log.warn(_(u"Order Creation Failed: Order amount is 0.")) return None style = cal_style(price, style) if isinstance(style, LimitOrder): if style.get_limit_price() <= 0: raise RQInvalidArgument(_(u"Limit order price should be positive")) order_book_id = assure_stock_order_book_id(id_or_ins) env = Environment.get_instance() price = env.get_last_price(order_book_id) if not is_valid_price(price): user_system_log.warn( _(u"Order Creation Failed: [{order_book_id}] No market data").format(order_book_id=order_book_id)) return if amount > 0: side = SIDE.BUY position_effect = POSITION_EFFECT.OPEN else: amount = abs(amount) side = SIDE.SELL position_effect = POSITION_EFFECT.CLOSE if side == SIDE.BUY: # 卖出不再限制 round_lot, order_shares 不再依赖 portfolio round_lot = int(env.get_instrument(order_book_id).round_lot) try: amount = int(Decimal(amount) / Decimal(round_lot)) * round_lot except ValueError: amount = 0 r_order = Order.__from_create__(order_book_id, amount, side, style, position_effect) if amount == 0: # 如果计算出来的下单量为0, 则不生成Order, 直接返回None # 因为很多策略会直接在handle_bar里面执行order_target_percent之类的函数,经常会出现下一个量为0的订单,如果这些订单都生成是没有意义的。 user_system_log.warn(_(u"Order Creation Failed: 0 order quantity")) return if r_order.type == ORDER_TYPE.MARKET: r_order.set_frozen_price(price) if env.can_submit_order(r_order): env.broker.submit_order(r_order) return r_order
python
def order_shares(id_or_ins, amount, price=None, style=None): """ 落指定股数的买/卖单,最常见的落单方式之一。如有需要落单类型当做一个参量传入,如果忽略掉落单类型,那么默认是市价单(market order)。 :param id_or_ins: 下单标的物 :type id_or_ins: :class:`~Instrument` object | `str` :param int amount: 下单量, 正数代表买入,负数代表卖出。将会根据一手xx股来向下调整到一手的倍数,比如中国A股就是调整成100股的倍数。 :param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要用于简化 `style` 参数。 :param style: 下单类型, 默认是市价单。目前支持的订单类型有 :class:`~LimitOrder` 和 :class:`~MarketOrder` :type style: `OrderStyle` object :return: :class:`~Order` object | None :example: .. code-block:: python #购买Buy 2000 股的平安银行股票,并以市价单发送: order_shares('000001.XSHE', 2000) #卖出2000股的平安银行股票,并以市价单发送: order_shares('000001.XSHE', -2000) #购买1000股的平安银行股票,并以限价单发送,价格为¥10: order_shares('000001.XSHG', 1000, style=LimitOrder(10)) """ if amount == 0: # 如果下单量为0,则认为其并没有发单,则直接返回None user_system_log.warn(_(u"Order Creation Failed: Order amount is 0.")) return None style = cal_style(price, style) if isinstance(style, LimitOrder): if style.get_limit_price() <= 0: raise RQInvalidArgument(_(u"Limit order price should be positive")) order_book_id = assure_stock_order_book_id(id_or_ins) env = Environment.get_instance() price = env.get_last_price(order_book_id) if not is_valid_price(price): user_system_log.warn( _(u"Order Creation Failed: [{order_book_id}] No market data").format(order_book_id=order_book_id)) return if amount > 0: side = SIDE.BUY position_effect = POSITION_EFFECT.OPEN else: amount = abs(amount) side = SIDE.SELL position_effect = POSITION_EFFECT.CLOSE if side == SIDE.BUY: # 卖出不再限制 round_lot, order_shares 不再依赖 portfolio round_lot = int(env.get_instrument(order_book_id).round_lot) try: amount = int(Decimal(amount) / Decimal(round_lot)) * round_lot except ValueError: amount = 0 r_order = Order.__from_create__(order_book_id, amount, side, style, position_effect) if amount == 0: # 如果计算出来的下单量为0, 则不生成Order, 直接返回None # 因为很多策略会直接在handle_bar里面执行order_target_percent之类的函数,经常会出现下一个量为0的订单,如果这些订单都生成是没有意义的。 user_system_log.warn(_(u"Order Creation Failed: 0 order quantity")) return if r_order.type == ORDER_TYPE.MARKET: r_order.set_frozen_price(price) if env.can_submit_order(r_order): env.broker.submit_order(r_order) return r_order
[ "def", "order_shares", "(", "id_or_ins", ",", "amount", ",", "price", "=", "None", ",", "style", "=", "None", ")", ":", "if", "amount", "==", "0", ":", "# 如果下单量为0,则认为其并没有发单,则直接返回None", "user_system_log", ".", "warn", "(", "_", "(", "u\"Order Creation Failed: Order amount is 0.\"", ")", ")", "return", "None", "style", "=", "cal_style", "(", "price", ",", "style", ")", "if", "isinstance", "(", "style", ",", "LimitOrder", ")", ":", "if", "style", ".", "get_limit_price", "(", ")", "<=", "0", ":", "raise", "RQInvalidArgument", "(", "_", "(", "u\"Limit order price should be positive\"", ")", ")", "order_book_id", "=", "assure_stock_order_book_id", "(", "id_or_ins", ")", "env", "=", "Environment", ".", "get_instance", "(", ")", "price", "=", "env", ".", "get_last_price", "(", "order_book_id", ")", "if", "not", "is_valid_price", "(", "price", ")", ":", "user_system_log", ".", "warn", "(", "_", "(", "u\"Order Creation Failed: [{order_book_id}] No market data\"", ")", ".", "format", "(", "order_book_id", "=", "order_book_id", ")", ")", "return", "if", "amount", ">", "0", ":", "side", "=", "SIDE", ".", "BUY", "position_effect", "=", "POSITION_EFFECT", ".", "OPEN", "else", ":", "amount", "=", "abs", "(", "amount", ")", "side", "=", "SIDE", ".", "SELL", "position_effect", "=", "POSITION_EFFECT", ".", "CLOSE", "if", "side", "==", "SIDE", ".", "BUY", ":", "# 卖出不再限制 round_lot, order_shares 不再依赖 portfolio", "round_lot", "=", "int", "(", "env", ".", "get_instrument", "(", "order_book_id", ")", ".", "round_lot", ")", "try", ":", "amount", "=", "int", "(", "Decimal", "(", "amount", ")", "/", "Decimal", "(", "round_lot", ")", ")", "*", "round_lot", "except", "ValueError", ":", "amount", "=", "0", "r_order", "=", "Order", ".", "__from_create__", "(", "order_book_id", ",", "amount", ",", "side", ",", "style", ",", "position_effect", ")", "if", "amount", "==", "0", ":", "# 如果计算出来的下单量为0, 则不生成Order, 直接返回None", "# 因为很多策略会直接在handle_bar里面执行order_target_percent之类的函数,经常会出现下一个量为0的订单,如果这些订单都生成是没有意义的。", "user_system_log", ".", "warn", "(", "_", "(", "u\"Order Creation Failed: 0 order quantity\"", ")", ")", "return", "if", "r_order", ".", "type", "==", "ORDER_TYPE", ".", "MARKET", ":", "r_order", ".", "set_frozen_price", "(", "price", ")", "if", "env", ".", "can_submit_order", "(", "r_order", ")", ":", "env", ".", "broker", ".", "submit_order", "(", "r_order", ")", "return", "r_order" ]
落指定股数的买/卖单,最常见的落单方式之一。如有需要落单类型当做一个参量传入,如果忽略掉落单类型,那么默认是市价单(market order)。 :param id_or_ins: 下单标的物 :type id_or_ins: :class:`~Instrument` object | `str` :param int amount: 下单量, 正数代表买入,负数代表卖出。将会根据一手xx股来向下调整到一手的倍数,比如中国A股就是调整成100股的倍数。 :param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要用于简化 `style` 参数。 :param style: 下单类型, 默认是市价单。目前支持的订单类型有 :class:`~LimitOrder` 和 :class:`~MarketOrder` :type style: `OrderStyle` object :return: :class:`~Order` object | None :example: .. code-block:: python #购买Buy 2000 股的平安银行股票,并以市价单发送: order_shares('000001.XSHE', 2000) #卖出2000股的平安银行股票,并以市价单发送: order_shares('000001.XSHE', -2000) #购买1000股的平安银行股票,并以限价单发送,价格为¥10: order_shares('000001.XSHG', 1000, style=LimitOrder(10))
[ "落指定股数的买", "/", "卖单,最常见的落单方式之一。如有需要落单类型当做一个参量传入,如果忽略掉落单类型,那么默认是市价单(market", "order)。" ]
ac40a62d4e7eca9494b4d0a14f46facf5616820c
https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/mod/rqalpha_mod_sys_accounts/api/api_stock.py#L68-L139
train
ricequant/rqalpha
rqalpha/mod/rqalpha_mod_sys_accounts/api/api_stock.py
order_lots
def order_lots(id_or_ins, amount, price=None, style=None): """ 指定手数发送买/卖单。如有需要落单类型当做一个参量传入,如果忽略掉落单类型,那么默认是市价单(market order)。 :param id_or_ins: 下单标的物 :type id_or_ins: :class:`~Instrument` object | `str` :param int amount: 下单量, 正数代表买入,负数代表卖出。将会根据一手xx股来向下调整到一手的倍数,比如中国A股就是调整成100股的倍数。 :param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要用于简化 `style` 参数。 :param style: 下单类型, 默认是市价单。目前支持的订单类型有 :class:`~LimitOrder` 和 :class:`~MarketOrder` :type style: `OrderStyle` object :return: :class:`~Order` object | None :example: .. code-block:: python #买入20手的平安银行股票,并且发送市价单: order_lots('000001.XSHE', 20) #买入10手平安银行股票,并且发送限价单,价格为¥10: order_lots('000001.XSHE', 10, style=LimitOrder(10)) """ order_book_id = assure_stock_order_book_id(id_or_ins) round_lot = int(Environment.get_instance().get_instrument(order_book_id).round_lot) style = cal_style(price, style) return order_shares(id_or_ins, amount * round_lot, style=style)
python
def order_lots(id_or_ins, amount, price=None, style=None): """ 指定手数发送买/卖单。如有需要落单类型当做一个参量传入,如果忽略掉落单类型,那么默认是市价单(market order)。 :param id_or_ins: 下单标的物 :type id_or_ins: :class:`~Instrument` object | `str` :param int amount: 下单量, 正数代表买入,负数代表卖出。将会根据一手xx股来向下调整到一手的倍数,比如中国A股就是调整成100股的倍数。 :param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要用于简化 `style` 参数。 :param style: 下单类型, 默认是市价单。目前支持的订单类型有 :class:`~LimitOrder` 和 :class:`~MarketOrder` :type style: `OrderStyle` object :return: :class:`~Order` object | None :example: .. code-block:: python #买入20手的平安银行股票,并且发送市价单: order_lots('000001.XSHE', 20) #买入10手平安银行股票,并且发送限价单,价格为¥10: order_lots('000001.XSHE', 10, style=LimitOrder(10)) """ order_book_id = assure_stock_order_book_id(id_or_ins) round_lot = int(Environment.get_instance().get_instrument(order_book_id).round_lot) style = cal_style(price, style) return order_shares(id_or_ins, amount * round_lot, style=style)
[ "def", "order_lots", "(", "id_or_ins", ",", "amount", ",", "price", "=", "None", ",", "style", "=", "None", ")", ":", "order_book_id", "=", "assure_stock_order_book_id", "(", "id_or_ins", ")", "round_lot", "=", "int", "(", "Environment", ".", "get_instance", "(", ")", ".", "get_instrument", "(", "order_book_id", ")", ".", "round_lot", ")", "style", "=", "cal_style", "(", "price", ",", "style", ")", "return", "order_shares", "(", "id_or_ins", ",", "amount", "*", "round_lot", ",", "style", "=", "style", ")" ]
指定手数发送买/卖单。如有需要落单类型当做一个参量传入,如果忽略掉落单类型,那么默认是市价单(market order)。 :param id_or_ins: 下单标的物 :type id_or_ins: :class:`~Instrument` object | `str` :param int amount: 下单量, 正数代表买入,负数代表卖出。将会根据一手xx股来向下调整到一手的倍数,比如中国A股就是调整成100股的倍数。 :param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要用于简化 `style` 参数。 :param style: 下单类型, 默认是市价单。目前支持的订单类型有 :class:`~LimitOrder` 和 :class:`~MarketOrder` :type style: `OrderStyle` object :return: :class:`~Order` object | None :example: .. code-block:: python #买入20手的平安银行股票,并且发送市价单: order_lots('000001.XSHE', 20) #买入10手平安银行股票,并且发送限价单,价格为¥10: order_lots('000001.XSHE', 10, style=LimitOrder(10))
[ "指定手数发送买", "/", "卖单。如有需要落单类型当做一个参量传入,如果忽略掉落单类型,那么默认是市价单(market", "order)。" ]
ac40a62d4e7eca9494b4d0a14f46facf5616820c
https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/mod/rqalpha_mod_sys_accounts/api/api_stock.py#L162-L194
train
ricequant/rqalpha
rqalpha/mod/rqalpha_mod_sys_accounts/api/api_stock.py
order_value
def order_value(id_or_ins, cash_amount, price=None, style=None): """ 使用想要花费的金钱买入/卖出股票,而不是买入/卖出想要的股数,正数代表买入,负数代表卖出。股票的股数总是会被调整成对应的100的倍数(在A中国A股市场1手是100股)。如果资金不足,该API将不会创建发送订单。 需要注意: 当您提交一个买单时,cash_amount 代表的含义是您希望买入股票消耗的金额(包含税费),最终买入的股数不仅和发单的价格有关,还和税费相关的参数设置有关。 当您提交一个卖单时,cash_amount 代表的意义是您希望卖出股票的总价值。如果金额超出了您所持有股票的价值,那么您将卖出所有股票。 :param id_or_ins: 下单标的物 :type id_or_ins: :class:`~Instrument` object | `str` :param float cash_amount: 需要花费现金购买/卖出证券的数目。正数代表买入,负数代表卖出。 :param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要用于简化 `style` 参数。 :param style: 下单类型, 默认是市价单。目前支持的订单类型有 :class:`~LimitOrder` 和 :class:`~MarketOrder` :type style: `OrderStyle` object :return: :class:`~Order` object | None :example: .. code-block:: python #花费最多¥10000买入平安银行股票,并以市价单发送。具体下单的数量与您策略税费相关的配置有关。 order_value('000001.XSHE', 10000) #卖出价值¥10000的现在持有的平安银行: order_value('000001.XSHE', -10000) """ style = cal_style(price, style) if isinstance(style, LimitOrder): if style.get_limit_price() <= 0: raise RQInvalidArgument(_(u"Limit order price should be positive")) order_book_id = assure_stock_order_book_id(id_or_ins) env = Environment.get_instance() price = env.get_last_price(order_book_id) if not is_valid_price(price): user_system_log.warn( _(u"Order Creation Failed: [{order_book_id}] No market data").format(order_book_id=order_book_id)) return account = env.portfolio.accounts[DEFAULT_ACCOUNT_TYPE.STOCK.name] if cash_amount > 0: cash_amount = min(cash_amount, account.cash) price = price if isinstance(style, MarketOrder) else style.get_limit_price() amount = int(Decimal(cash_amount) / Decimal(price)) if cash_amount > 0: round_lot = int(env.get_instrument(order_book_id).round_lot) # FIXME: logic duplicate with order_shares amount = int(Decimal(amount) / Decimal(round_lot)) * round_lot while amount > 0: dummy_order = Order.__from_create__(order_book_id, amount, SIDE.BUY, style, POSITION_EFFECT.OPEN) expected_transaction_cost = env.get_order_transaction_cost(DEFAULT_ACCOUNT_TYPE.STOCK, dummy_order) if amount * price + expected_transaction_cost <= cash_amount: break amount -= round_lot else: user_system_log.warn(_(u"Order Creation Failed: 0 order quantity")) return # if the cash_amount is larger than you current security’s position, # then it will sell all shares of this security. position = account.positions[order_book_id] amount = downsize_amount(amount, position) return order_shares(order_book_id, amount, style=style)
python
def order_value(id_or_ins, cash_amount, price=None, style=None): """ 使用想要花费的金钱买入/卖出股票,而不是买入/卖出想要的股数,正数代表买入,负数代表卖出。股票的股数总是会被调整成对应的100的倍数(在A中国A股市场1手是100股)。如果资金不足,该API将不会创建发送订单。 需要注意: 当您提交一个买单时,cash_amount 代表的含义是您希望买入股票消耗的金额(包含税费),最终买入的股数不仅和发单的价格有关,还和税费相关的参数设置有关。 当您提交一个卖单时,cash_amount 代表的意义是您希望卖出股票的总价值。如果金额超出了您所持有股票的价值,那么您将卖出所有股票。 :param id_or_ins: 下单标的物 :type id_or_ins: :class:`~Instrument` object | `str` :param float cash_amount: 需要花费现金购买/卖出证券的数目。正数代表买入,负数代表卖出。 :param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要用于简化 `style` 参数。 :param style: 下单类型, 默认是市价单。目前支持的订单类型有 :class:`~LimitOrder` 和 :class:`~MarketOrder` :type style: `OrderStyle` object :return: :class:`~Order` object | None :example: .. code-block:: python #花费最多¥10000买入平安银行股票,并以市价单发送。具体下单的数量与您策略税费相关的配置有关。 order_value('000001.XSHE', 10000) #卖出价值¥10000的现在持有的平安银行: order_value('000001.XSHE', -10000) """ style = cal_style(price, style) if isinstance(style, LimitOrder): if style.get_limit_price() <= 0: raise RQInvalidArgument(_(u"Limit order price should be positive")) order_book_id = assure_stock_order_book_id(id_or_ins) env = Environment.get_instance() price = env.get_last_price(order_book_id) if not is_valid_price(price): user_system_log.warn( _(u"Order Creation Failed: [{order_book_id}] No market data").format(order_book_id=order_book_id)) return account = env.portfolio.accounts[DEFAULT_ACCOUNT_TYPE.STOCK.name] if cash_amount > 0: cash_amount = min(cash_amount, account.cash) price = price if isinstance(style, MarketOrder) else style.get_limit_price() amount = int(Decimal(cash_amount) / Decimal(price)) if cash_amount > 0: round_lot = int(env.get_instrument(order_book_id).round_lot) # FIXME: logic duplicate with order_shares amount = int(Decimal(amount) / Decimal(round_lot)) * round_lot while amount > 0: dummy_order = Order.__from_create__(order_book_id, amount, SIDE.BUY, style, POSITION_EFFECT.OPEN) expected_transaction_cost = env.get_order_transaction_cost(DEFAULT_ACCOUNT_TYPE.STOCK, dummy_order) if amount * price + expected_transaction_cost <= cash_amount: break amount -= round_lot else: user_system_log.warn(_(u"Order Creation Failed: 0 order quantity")) return # if the cash_amount is larger than you current security’s position, # then it will sell all shares of this security. position = account.positions[order_book_id] amount = downsize_amount(amount, position) return order_shares(order_book_id, amount, style=style)
[ "def", "order_value", "(", "id_or_ins", ",", "cash_amount", ",", "price", "=", "None", ",", "style", "=", "None", ")", ":", "style", "=", "cal_style", "(", "price", ",", "style", ")", "if", "isinstance", "(", "style", ",", "LimitOrder", ")", ":", "if", "style", ".", "get_limit_price", "(", ")", "<=", "0", ":", "raise", "RQInvalidArgument", "(", "_", "(", "u\"Limit order price should be positive\"", ")", ")", "order_book_id", "=", "assure_stock_order_book_id", "(", "id_or_ins", ")", "env", "=", "Environment", ".", "get_instance", "(", ")", "price", "=", "env", ".", "get_last_price", "(", "order_book_id", ")", "if", "not", "is_valid_price", "(", "price", ")", ":", "user_system_log", ".", "warn", "(", "_", "(", "u\"Order Creation Failed: [{order_book_id}] No market data\"", ")", ".", "format", "(", "order_book_id", "=", "order_book_id", ")", ")", "return", "account", "=", "env", ".", "portfolio", ".", "accounts", "[", "DEFAULT_ACCOUNT_TYPE", ".", "STOCK", ".", "name", "]", "if", "cash_amount", ">", "0", ":", "cash_amount", "=", "min", "(", "cash_amount", ",", "account", ".", "cash", ")", "price", "=", "price", "if", "isinstance", "(", "style", ",", "MarketOrder", ")", "else", "style", ".", "get_limit_price", "(", ")", "amount", "=", "int", "(", "Decimal", "(", "cash_amount", ")", "/", "Decimal", "(", "price", ")", ")", "if", "cash_amount", ">", "0", ":", "round_lot", "=", "int", "(", "env", ".", "get_instrument", "(", "order_book_id", ")", ".", "round_lot", ")", "# FIXME: logic duplicate with order_shares", "amount", "=", "int", "(", "Decimal", "(", "amount", ")", "/", "Decimal", "(", "round_lot", ")", ")", "*", "round_lot", "while", "amount", ">", "0", ":", "dummy_order", "=", "Order", ".", "__from_create__", "(", "order_book_id", ",", "amount", ",", "SIDE", ".", "BUY", ",", "style", ",", "POSITION_EFFECT", ".", "OPEN", ")", "expected_transaction_cost", "=", "env", ".", "get_order_transaction_cost", "(", "DEFAULT_ACCOUNT_TYPE", ".", "STOCK", ",", "dummy_order", ")", "if", "amount", "*", "price", "+", "expected_transaction_cost", "<=", "cash_amount", ":", "break", "amount", "-=", "round_lot", "else", ":", "user_system_log", ".", "warn", "(", "_", "(", "u\"Order Creation Failed: 0 order quantity\"", ")", ")", "return", "# if the cash_amount is larger than you current security’s position,", "# then it will sell all shares of this security.", "position", "=", "account", ".", "positions", "[", "order_book_id", "]", "amount", "=", "downsize_amount", "(", "amount", ",", "position", ")", "return", "order_shares", "(", "order_book_id", ",", "amount", ",", "style", "=", "style", ")" ]
使用想要花费的金钱买入/卖出股票,而不是买入/卖出想要的股数,正数代表买入,负数代表卖出。股票的股数总是会被调整成对应的100的倍数(在A中国A股市场1手是100股)。如果资金不足,该API将不会创建发送订单。 需要注意: 当您提交一个买单时,cash_amount 代表的含义是您希望买入股票消耗的金额(包含税费),最终买入的股数不仅和发单的价格有关,还和税费相关的参数设置有关。 当您提交一个卖单时,cash_amount 代表的意义是您希望卖出股票的总价值。如果金额超出了您所持有股票的价值,那么您将卖出所有股票。 :param id_or_ins: 下单标的物 :type id_or_ins: :class:`~Instrument` object | `str` :param float cash_amount: 需要花费现金购买/卖出证券的数目。正数代表买入,负数代表卖出。 :param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要用于简化 `style` 参数。 :param style: 下单类型, 默认是市价单。目前支持的订单类型有 :class:`~LimitOrder` 和 :class:`~MarketOrder` :type style: `OrderStyle` object :return: :class:`~Order` object | None :example: .. code-block:: python #花费最多¥10000买入平安银行股票,并以市价单发送。具体下单的数量与您策略税费相关的配置有关。 order_value('000001.XSHE', 10000) #卖出价值¥10000的现在持有的平安银行: order_value('000001.XSHE', -10000)
[ "使用想要花费的金钱买入", "/", "卖出股票,而不是买入", "/", "卖出想要的股数,正数代表买入,负数代表卖出。股票的股数总是会被调整成对应的100的倍数(在A中国A股市场1手是100股)。如果资金不足,该API将不会创建发送订单。" ]
ac40a62d4e7eca9494b4d0a14f46facf5616820c
https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/mod/rqalpha_mod_sys_accounts/api/api_stock.py#L206-L282
train
ricequant/rqalpha
rqalpha/mod/rqalpha_mod_sys_accounts/api/api_stock.py
order_percent
def order_percent(id_or_ins, percent, price=None, style=None): """ 发送一个花费价值等于目前投资组合(市场价值和目前现金的总和)一定百分比现金的买/卖单,正数代表买,负数代表卖。股票的股数总是会被调整成对应的一手的股票数的倍数(1手是100股)。百分比是一个小数,并且小于或等于1(<=100%),0.5表示的是50%.需要注意,如果资金不足,该API将不会创建发送订单。 需要注意: 发送买单时,percent 代表的是期望买入股票消耗的金额(包含税费)占投资组合总权益的比例。 发送卖单时,percent 代表的是期望卖出的股票总价值占投资组合总权益的比例。 :param id_or_ins: 下单标的物 :type id_or_ins: :class:`~Instrument` object | `str` :param float percent: 占有现有的投资组合价值的百分比。正数表示买入,负数表示卖出。 :param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要用于简化 `style` 参数。 :param style: 下单类型, 默认是市价单。目前支持的订单类型有 :class:`~LimitOrder` 和 :class:`~MarketOrder` :type style: `OrderStyle` object :return: :class:`~Order` object | None :example: .. code-block:: python #花费等于现有投资组合50%价值的现金买入平安银行股票: order_percent('000001.XSHG', 0.5) """ if percent < -1 or percent > 1: raise RQInvalidArgument(_(u"percent should between -1 and 1")) style = cal_style(price, style) account = Environment.get_instance().portfolio.accounts[DEFAULT_ACCOUNT_TYPE.STOCK.name] return order_value(id_or_ins, account.total_value * percent, style=style)
python
def order_percent(id_or_ins, percent, price=None, style=None): """ 发送一个花费价值等于目前投资组合(市场价值和目前现金的总和)一定百分比现金的买/卖单,正数代表买,负数代表卖。股票的股数总是会被调整成对应的一手的股票数的倍数(1手是100股)。百分比是一个小数,并且小于或等于1(<=100%),0.5表示的是50%.需要注意,如果资金不足,该API将不会创建发送订单。 需要注意: 发送买单时,percent 代表的是期望买入股票消耗的金额(包含税费)占投资组合总权益的比例。 发送卖单时,percent 代表的是期望卖出的股票总价值占投资组合总权益的比例。 :param id_or_ins: 下单标的物 :type id_or_ins: :class:`~Instrument` object | `str` :param float percent: 占有现有的投资组合价值的百分比。正数表示买入,负数表示卖出。 :param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要用于简化 `style` 参数。 :param style: 下单类型, 默认是市价单。目前支持的订单类型有 :class:`~LimitOrder` 和 :class:`~MarketOrder` :type style: `OrderStyle` object :return: :class:`~Order` object | None :example: .. code-block:: python #花费等于现有投资组合50%价值的现金买入平安银行股票: order_percent('000001.XSHG', 0.5) """ if percent < -1 or percent > 1: raise RQInvalidArgument(_(u"percent should between -1 and 1")) style = cal_style(price, style) account = Environment.get_instance().portfolio.accounts[DEFAULT_ACCOUNT_TYPE.STOCK.name] return order_value(id_or_ins, account.total_value * percent, style=style)
[ "def", "order_percent", "(", "id_or_ins", ",", "percent", ",", "price", "=", "None", ",", "style", "=", "None", ")", ":", "if", "percent", "<", "-", "1", "or", "percent", ">", "1", ":", "raise", "RQInvalidArgument", "(", "_", "(", "u\"percent should between -1 and 1\"", ")", ")", "style", "=", "cal_style", "(", "price", ",", "style", ")", "account", "=", "Environment", ".", "get_instance", "(", ")", ".", "portfolio", ".", "accounts", "[", "DEFAULT_ACCOUNT_TYPE", ".", "STOCK", ".", "name", "]", "return", "order_value", "(", "id_or_ins", ",", "account", ".", "total_value", "*", "percent", ",", "style", "=", "style", ")" ]
发送一个花费价值等于目前投资组合(市场价值和目前现金的总和)一定百分比现金的买/卖单,正数代表买,负数代表卖。股票的股数总是会被调整成对应的一手的股票数的倍数(1手是100股)。百分比是一个小数,并且小于或等于1(<=100%),0.5表示的是50%.需要注意,如果资金不足,该API将不会创建发送订单。 需要注意: 发送买单时,percent 代表的是期望买入股票消耗的金额(包含税费)占投资组合总权益的比例。 发送卖单时,percent 代表的是期望卖出的股票总价值占投资组合总权益的比例。 :param id_or_ins: 下单标的物 :type id_or_ins: :class:`~Instrument` object | `str` :param float percent: 占有现有的投资组合价值的百分比。正数表示买入,负数表示卖出。 :param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要用于简化 `style` 参数。 :param style: 下单类型, 默认是市价单。目前支持的订单类型有 :class:`~LimitOrder` 和 :class:`~MarketOrder` :type style: `OrderStyle` object :return: :class:`~Order` object | None :example: .. code-block:: python #花费等于现有投资组合50%价值的现金买入平安银行股票: order_percent('000001.XSHG', 0.5)
[ "发送一个花费价值等于目前投资组合(市场价值和目前现金的总和)一定百分比现金的买", "/", "卖单,正数代表买,负数代表卖。股票的股数总是会被调整成对应的一手的股票数的倍数(1手是100股)。百分比是一个小数,并且小于或等于1(<", "=", "100%),0", ".", "5表示的是50%", ".", "需要注意,如果资金不足,该API将不会创建发送订单。" ]
ac40a62d4e7eca9494b4d0a14f46facf5616820c
https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/mod/rqalpha_mod_sys_accounts/api/api_stock.py#L294-L326
train
ricequant/rqalpha
rqalpha/mod/rqalpha_mod_sys_accounts/api/api_stock.py
order_target_value
def order_target_value(id_or_ins, cash_amount, price=None, style=None): """ 买入/卖出并且自动调整该证券的仓位到一个目标价值。 加仓时,cash_amount 代表现有持仓的价值加上即将花费(包含税费)的现金的总价值。 减仓时,cash_amount 代表调整仓位的目标价至。 需要注意,如果资金不足,该API将不会创建发送订单。 :param id_or_ins: 下单标的物 :type id_or_ins: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`] :param float cash_amount: 最终的该证券的仓位目标价值。 :param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要用于简化 `style` 参数。 :param style: 下单类型, 默认是市价单。目前支持的订单类型有 :class:`~LimitOrder` 和 :class:`~MarketOrder` :type style: `OrderStyle` object :return: :class:`~Order` object | None :example: .. code-block:: python #如果现在的投资组合中持有价值¥3000的平安银行股票的仓位,以下代码范例会发送花费 ¥7000 现金的平安银行买单到市场。(向下调整到最接近每手股数即100的倍数的股数): order_target_value('000001.XSHE', 10000) """ order_book_id = assure_stock_order_book_id(id_or_ins) account = Environment.get_instance().portfolio.accounts[DEFAULT_ACCOUNT_TYPE.STOCK.name] position = account.positions[order_book_id] style = cal_style(price, style) if cash_amount == 0: return _sell_all_stock(order_book_id, position.sellable, style) try: market_value = position.market_value except RuntimeError: order_result = order_value(order_book_id, np.nan, style=style) if order_result: raise else: return order_value(order_book_id, cash_amount - market_value, style=style)
python
def order_target_value(id_or_ins, cash_amount, price=None, style=None): """ 买入/卖出并且自动调整该证券的仓位到一个目标价值。 加仓时,cash_amount 代表现有持仓的价值加上即将花费(包含税费)的现金的总价值。 减仓时,cash_amount 代表调整仓位的目标价至。 需要注意,如果资金不足,该API将不会创建发送订单。 :param id_or_ins: 下单标的物 :type id_or_ins: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`] :param float cash_amount: 最终的该证券的仓位目标价值。 :param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要用于简化 `style` 参数。 :param style: 下单类型, 默认是市价单。目前支持的订单类型有 :class:`~LimitOrder` 和 :class:`~MarketOrder` :type style: `OrderStyle` object :return: :class:`~Order` object | None :example: .. code-block:: python #如果现在的投资组合中持有价值¥3000的平安银行股票的仓位,以下代码范例会发送花费 ¥7000 现金的平安银行买单到市场。(向下调整到最接近每手股数即100的倍数的股数): order_target_value('000001.XSHE', 10000) """ order_book_id = assure_stock_order_book_id(id_or_ins) account = Environment.get_instance().portfolio.accounts[DEFAULT_ACCOUNT_TYPE.STOCK.name] position = account.positions[order_book_id] style = cal_style(price, style) if cash_amount == 0: return _sell_all_stock(order_book_id, position.sellable, style) try: market_value = position.market_value except RuntimeError: order_result = order_value(order_book_id, np.nan, style=style) if order_result: raise else: return order_value(order_book_id, cash_amount - market_value, style=style)
[ "def", "order_target_value", "(", "id_or_ins", ",", "cash_amount", ",", "price", "=", "None", ",", "style", "=", "None", ")", ":", "order_book_id", "=", "assure_stock_order_book_id", "(", "id_or_ins", ")", "account", "=", "Environment", ".", "get_instance", "(", ")", ".", "portfolio", ".", "accounts", "[", "DEFAULT_ACCOUNT_TYPE", ".", "STOCK", ".", "name", "]", "position", "=", "account", ".", "positions", "[", "order_book_id", "]", "style", "=", "cal_style", "(", "price", ",", "style", ")", "if", "cash_amount", "==", "0", ":", "return", "_sell_all_stock", "(", "order_book_id", ",", "position", ".", "sellable", ",", "style", ")", "try", ":", "market_value", "=", "position", ".", "market_value", "except", "RuntimeError", ":", "order_result", "=", "order_value", "(", "order_book_id", ",", "np", ".", "nan", ",", "style", "=", "style", ")", "if", "order_result", ":", "raise", "else", ":", "return", "order_value", "(", "order_book_id", ",", "cash_amount", "-", "market_value", ",", "style", "=", "style", ")" ]
买入/卖出并且自动调整该证券的仓位到一个目标价值。 加仓时,cash_amount 代表现有持仓的价值加上即将花费(包含税费)的现金的总价值。 减仓时,cash_amount 代表调整仓位的目标价至。 需要注意,如果资金不足,该API将不会创建发送订单。 :param id_or_ins: 下单标的物 :type id_or_ins: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`] :param float cash_amount: 最终的该证券的仓位目标价值。 :param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要用于简化 `style` 参数。 :param style: 下单类型, 默认是市价单。目前支持的订单类型有 :class:`~LimitOrder` 和 :class:`~MarketOrder` :type style: `OrderStyle` object :return: :class:`~Order` object | None :example: .. code-block:: python #如果现在的投资组合中持有价值¥3000的平安银行股票的仓位,以下代码范例会发送花费 ¥7000 现金的平安银行买单到市场。(向下调整到最接近每手股数即100的倍数的股数): order_target_value('000001.XSHE', 10000)
[ "买入", "/", "卖出并且自动调整该证券的仓位到一个目标价值。", "加仓时,cash_amount", "代表现有持仓的价值加上即将花费(包含税费)的现金的总价值。", "减仓时,cash_amount", "代表调整仓位的目标价至。" ]
ac40a62d4e7eca9494b4d0a14f46facf5616820c
https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/mod/rqalpha_mod_sys_accounts/api/api_stock.py#L338-L380
train
ricequant/rqalpha
rqalpha/mod/rqalpha_mod_sys_accounts/api/api_stock.py
order_target_percent
def order_target_percent(id_or_ins, percent, price=None, style=None): """ 买入/卖出证券以自动调整该证券的仓位到占有一个目标价值。 加仓时,percent 代表证券已有持仓的价值加上即将花费的现金(包含税费)的总值占当前投资组合总价值的比例。 减仓时,percent 代表证券将被调整到的目标价至占当前投资组合总价值的比例。 其实我们需要计算一个position_to_adjust (即应该调整的仓位) `position_to_adjust = target_position - current_position` 投资组合价值等于所有已有仓位的价值和剩余现金的总和。买/卖单会被下舍入一手股数(A股是100的倍数)的倍数。目标百分比应该是一个小数,并且最大值应该<=1,比如0.5表示50%。 如果position_to_adjust 计算之后是正的,那么会买入该证券,否则会卖出该证券。 需要注意,如果资金不足,该API将不会创建发送订单。 :param id_or_ins: 下单标的物 :type id_or_ins: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`] :param float percent: 仓位最终所占投资组合总价值的目标百分比。 :param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要用于简化 `style` 参数。 :param style: 下单类型, 默认是市价单。目前支持的订单类型有 :class:`~LimitOrder` 和 :class:`~MarketOrder` :type style: `OrderStyle` object :return: :class:`~Order` object | None :example: .. code-block:: python #如果投资组合中已经有了平安银行股票的仓位,并且占据目前投资组合的10%的价值,那么以下代码会消耗相当于当前投资组合价值5%的现金买入平安银行股票: order_target_percent('000001.XSHE', 0.15) """ if percent < 0 or percent > 1: raise RQInvalidArgument(_(u"percent should between 0 and 1")) order_book_id = assure_stock_order_book_id(id_or_ins) style = cal_style(price, style) account = Environment.get_instance().portfolio.accounts[DEFAULT_ACCOUNT_TYPE.STOCK.name] position = account.positions[order_book_id] if percent == 0: return _sell_all_stock(order_book_id, position.sellable, style) try: market_value = position.market_value except RuntimeError: order_result = order_value(order_book_id, np.nan, style=style) if order_result: raise else: return order_value(order_book_id, account.total_value * percent - market_value, style=style)
python
def order_target_percent(id_or_ins, percent, price=None, style=None): """ 买入/卖出证券以自动调整该证券的仓位到占有一个目标价值。 加仓时,percent 代表证券已有持仓的价值加上即将花费的现金(包含税费)的总值占当前投资组合总价值的比例。 减仓时,percent 代表证券将被调整到的目标价至占当前投资组合总价值的比例。 其实我们需要计算一个position_to_adjust (即应该调整的仓位) `position_to_adjust = target_position - current_position` 投资组合价值等于所有已有仓位的价值和剩余现金的总和。买/卖单会被下舍入一手股数(A股是100的倍数)的倍数。目标百分比应该是一个小数,并且最大值应该<=1,比如0.5表示50%。 如果position_to_adjust 计算之后是正的,那么会买入该证券,否则会卖出该证券。 需要注意,如果资金不足,该API将不会创建发送订单。 :param id_or_ins: 下单标的物 :type id_or_ins: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`] :param float percent: 仓位最终所占投资组合总价值的目标百分比。 :param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要用于简化 `style` 参数。 :param style: 下单类型, 默认是市价单。目前支持的订单类型有 :class:`~LimitOrder` 和 :class:`~MarketOrder` :type style: `OrderStyle` object :return: :class:`~Order` object | None :example: .. code-block:: python #如果投资组合中已经有了平安银行股票的仓位,并且占据目前投资组合的10%的价值,那么以下代码会消耗相当于当前投资组合价值5%的现金买入平安银行股票: order_target_percent('000001.XSHE', 0.15) """ if percent < 0 or percent > 1: raise RQInvalidArgument(_(u"percent should between 0 and 1")) order_book_id = assure_stock_order_book_id(id_or_ins) style = cal_style(price, style) account = Environment.get_instance().portfolio.accounts[DEFAULT_ACCOUNT_TYPE.STOCK.name] position = account.positions[order_book_id] if percent == 0: return _sell_all_stock(order_book_id, position.sellable, style) try: market_value = position.market_value except RuntimeError: order_result = order_value(order_book_id, np.nan, style=style) if order_result: raise else: return order_value(order_book_id, account.total_value * percent - market_value, style=style)
[ "def", "order_target_percent", "(", "id_or_ins", ",", "percent", ",", "price", "=", "None", ",", "style", "=", "None", ")", ":", "if", "percent", "<", "0", "or", "percent", ">", "1", ":", "raise", "RQInvalidArgument", "(", "_", "(", "u\"percent should between 0 and 1\"", ")", ")", "order_book_id", "=", "assure_stock_order_book_id", "(", "id_or_ins", ")", "style", "=", "cal_style", "(", "price", ",", "style", ")", "account", "=", "Environment", ".", "get_instance", "(", ")", ".", "portfolio", ".", "accounts", "[", "DEFAULT_ACCOUNT_TYPE", ".", "STOCK", ".", "name", "]", "position", "=", "account", ".", "positions", "[", "order_book_id", "]", "if", "percent", "==", "0", ":", "return", "_sell_all_stock", "(", "order_book_id", ",", "position", ".", "sellable", ",", "style", ")", "try", ":", "market_value", "=", "position", ".", "market_value", "except", "RuntimeError", ":", "order_result", "=", "order_value", "(", "order_book_id", ",", "np", ".", "nan", ",", "style", "=", "style", ")", "if", "order_result", ":", "raise", "else", ":", "return", "order_value", "(", "order_book_id", ",", "account", ".", "total_value", "*", "percent", "-", "market_value", ",", "style", "=", "style", ")" ]
买入/卖出证券以自动调整该证券的仓位到占有一个目标价值。 加仓时,percent 代表证券已有持仓的价值加上即将花费的现金(包含税费)的总值占当前投资组合总价值的比例。 减仓时,percent 代表证券将被调整到的目标价至占当前投资组合总价值的比例。 其实我们需要计算一个position_to_adjust (即应该调整的仓位) `position_to_adjust = target_position - current_position` 投资组合价值等于所有已有仓位的价值和剩余现金的总和。买/卖单会被下舍入一手股数(A股是100的倍数)的倍数。目标百分比应该是一个小数,并且最大值应该<=1,比如0.5表示50%。 如果position_to_adjust 计算之后是正的,那么会买入该证券,否则会卖出该证券。 需要注意,如果资金不足,该API将不会创建发送订单。 :param id_or_ins: 下单标的物 :type id_or_ins: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`] :param float percent: 仓位最终所占投资组合总价值的目标百分比。 :param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要用于简化 `style` 参数。 :param style: 下单类型, 默认是市价单。目前支持的订单类型有 :class:`~LimitOrder` 和 :class:`~MarketOrder` :type style: `OrderStyle` object :return: :class:`~Order` object | None :example: .. code-block:: python #如果投资组合中已经有了平安银行股票的仓位,并且占据目前投资组合的10%的价值,那么以下代码会消耗相当于当前投资组合价值5%的现金买入平安银行股票: order_target_percent('000001.XSHE', 0.15)
[ "买入", "/", "卖出证券以自动调整该证券的仓位到占有一个目标价值。" ]
ac40a62d4e7eca9494b4d0a14f46facf5616820c
https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/mod/rqalpha_mod_sys_accounts/api/api_stock.py#L392-L445
train
ricequant/rqalpha
rqalpha/mod/rqalpha_mod_sys_accounts/api/api_stock.py
is_suspended
def is_suspended(order_book_id, count=1): """ 判断某只股票是否全天停牌。 :param str order_book_id: 某只股票的代码或股票代码,可传入单只股票的order_book_id, symbol :param int count: 回溯获取的数据个数。默认为当前能够获取到的最近的数据 :return: count为1时 `bool`; count>1时 `pandas.DataFrame` """ dt = Environment.get_instance().calendar_dt.date() order_book_id = assure_stock_order_book_id(order_book_id) return Environment.get_instance().data_proxy.is_suspended(order_book_id, dt, count)
python
def is_suspended(order_book_id, count=1): """ 判断某只股票是否全天停牌。 :param str order_book_id: 某只股票的代码或股票代码,可传入单只股票的order_book_id, symbol :param int count: 回溯获取的数据个数。默认为当前能够获取到的最近的数据 :return: count为1时 `bool`; count>1时 `pandas.DataFrame` """ dt = Environment.get_instance().calendar_dt.date() order_book_id = assure_stock_order_book_id(order_book_id) return Environment.get_instance().data_proxy.is_suspended(order_book_id, dt, count)
[ "def", "is_suspended", "(", "order_book_id", ",", "count", "=", "1", ")", ":", "dt", "=", "Environment", ".", "get_instance", "(", ")", ".", "calendar_dt", ".", "date", "(", ")", "order_book_id", "=", "assure_stock_order_book_id", "(", "order_book_id", ")", "return", "Environment", ".", "get_instance", "(", ")", ".", "data_proxy", ".", "is_suspended", "(", "order_book_id", ",", "dt", ",", "count", ")" ]
判断某只股票是否全天停牌。 :param str order_book_id: 某只股票的代码或股票代码,可传入单只股票的order_book_id, symbol :param int count: 回溯获取的数据个数。默认为当前能够获取到的最近的数据 :return: count为1时 `bool`; count>1时 `pandas.DataFrame`
[ "判断某只股票是否全天停牌。" ]
ac40a62d4e7eca9494b4d0a14f46facf5616820c
https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/mod/rqalpha_mod_sys_accounts/api/api_stock.py#L457-L469
train
ricequant/rqalpha
rqalpha/__main__.py
update_bundle
def update_bundle(data_bundle_path, locale): """ Sync Data Bundle """ import rqalpha.utils.bundle_helper rqalpha.utils.bundle_helper.update_bundle(data_bundle_path, locale)
python
def update_bundle(data_bundle_path, locale): """ Sync Data Bundle """ import rqalpha.utils.bundle_helper rqalpha.utils.bundle_helper.update_bundle(data_bundle_path, locale)
[ "def", "update_bundle", "(", "data_bundle_path", ",", "locale", ")", ":", "import", "rqalpha", ".", "utils", ".", "bundle_helper", "rqalpha", ".", "utils", ".", "bundle_helper", ".", "update_bundle", "(", "data_bundle_path", ",", "locale", ")" ]
Sync Data Bundle
[ "Sync", "Data", "Bundle" ]
ac40a62d4e7eca9494b4d0a14f46facf5616820c
https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/__main__.py#L77-L82
train
ricequant/rqalpha
rqalpha/__main__.py
run
def run(**kwargs): """ Start to run a strategy """ config_path = kwargs.get('config_path', None) if config_path is not None: config_path = os.path.abspath(config_path) kwargs.pop('config_path') if not kwargs.get('base__securities', None): kwargs.pop('base__securities', None) from rqalpha import main source_code = kwargs.get("base__source_code") cfg = parse_config(kwargs, config_path=config_path, click_type=True, source_code=source_code) source_code = cfg.base.source_code results = main.run(cfg, source_code=source_code) # store results into ipython when running in ipython from rqalpha.utils import is_run_from_ipython if results is not None and is_run_from_ipython(): import IPython from rqalpha.utils import RqAttrDict ipy = IPython.get_ipython() report = results.get("sys_analyser", {}) ipy.user_global_ns["results"] = results ipy.user_global_ns["report"] = RqAttrDict(report) if results is None: sys.exit(1)
python
def run(**kwargs): """ Start to run a strategy """ config_path = kwargs.get('config_path', None) if config_path is not None: config_path = os.path.abspath(config_path) kwargs.pop('config_path') if not kwargs.get('base__securities', None): kwargs.pop('base__securities', None) from rqalpha import main source_code = kwargs.get("base__source_code") cfg = parse_config(kwargs, config_path=config_path, click_type=True, source_code=source_code) source_code = cfg.base.source_code results = main.run(cfg, source_code=source_code) # store results into ipython when running in ipython from rqalpha.utils import is_run_from_ipython if results is not None and is_run_from_ipython(): import IPython from rqalpha.utils import RqAttrDict ipy = IPython.get_ipython() report = results.get("sys_analyser", {}) ipy.user_global_ns["results"] = results ipy.user_global_ns["report"] = RqAttrDict(report) if results is None: sys.exit(1)
[ "def", "run", "(", "*", "*", "kwargs", ")", ":", "config_path", "=", "kwargs", ".", "get", "(", "'config_path'", ",", "None", ")", "if", "config_path", "is", "not", "None", ":", "config_path", "=", "os", ".", "path", ".", "abspath", "(", "config_path", ")", "kwargs", ".", "pop", "(", "'config_path'", ")", "if", "not", "kwargs", ".", "get", "(", "'base__securities'", ",", "None", ")", ":", "kwargs", ".", "pop", "(", "'base__securities'", ",", "None", ")", "from", "rqalpha", "import", "main", "source_code", "=", "kwargs", ".", "get", "(", "\"base__source_code\"", ")", "cfg", "=", "parse_config", "(", "kwargs", ",", "config_path", "=", "config_path", ",", "click_type", "=", "True", ",", "source_code", "=", "source_code", ")", "source_code", "=", "cfg", ".", "base", ".", "source_code", "results", "=", "main", ".", "run", "(", "cfg", ",", "source_code", "=", "source_code", ")", "# store results into ipython when running in ipython", "from", "rqalpha", ".", "utils", "import", "is_run_from_ipython", "if", "results", "is", "not", "None", "and", "is_run_from_ipython", "(", ")", ":", "import", "IPython", "from", "rqalpha", ".", "utils", "import", "RqAttrDict", "ipy", "=", "IPython", ".", "get_ipython", "(", ")", "report", "=", "results", ".", "get", "(", "\"sys_analyser\"", ",", "{", "}", ")", "ipy", ".", "user_global_ns", "[", "\"results\"", "]", "=", "results", "ipy", ".", "user_global_ns", "[", "\"report\"", "]", "=", "RqAttrDict", "(", "report", ")", "if", "results", "is", "None", ":", "sys", ".", "exit", "(", "1", ")" ]
Start to run a strategy
[ "Start", "to", "run", "a", "strategy" ]
ac40a62d4e7eca9494b4d0a14f46facf5616820c
https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/__main__.py#L112-L140
train
ricequant/rqalpha
rqalpha/__main__.py
examples
def examples(directory): """ Generate example strategies to target folder """ source_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "examples") try: shutil.copytree(source_dir, os.path.join(directory, "examples")) except OSError as e: if e.errno == errno.EEXIST: six.print_("Folder examples is exists.")
python
def examples(directory): """ Generate example strategies to target folder """ source_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "examples") try: shutil.copytree(source_dir, os.path.join(directory, "examples")) except OSError as e: if e.errno == errno.EEXIST: six.print_("Folder examples is exists.")
[ "def", "examples", "(", "directory", ")", ":", "source_dir", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "realpath", "(", "__file__", ")", ")", ",", "\"examples\"", ")", "try", ":", "shutil", ".", "copytree", "(", "source_dir", ",", "os", ".", "path", ".", "join", "(", "directory", ",", "\"examples\"", ")", ")", "except", "OSError", "as", "e", ":", "if", "e", ".", "errno", "==", "errno", ".", "EEXIST", ":", "six", ".", "print_", "(", "\"Folder examples is exists.\"", ")" ]
Generate example strategies to target folder
[ "Generate", "example", "strategies", "to", "target", "folder" ]
ac40a62d4e7eca9494b4d0a14f46facf5616820c
https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/__main__.py#L145-L155
train
ricequant/rqalpha
rqalpha/__main__.py
generate_config
def generate_config(directory): """ Generate default config file """ default_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "config.yml") target_config_path = os.path.abspath(os.path.join(directory, 'config.yml')) shutil.copy(default_config, target_config_path) six.print_("Config file has been generated in", target_config_path)
python
def generate_config(directory): """ Generate default config file """ default_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "config.yml") target_config_path = os.path.abspath(os.path.join(directory, 'config.yml')) shutil.copy(default_config, target_config_path) six.print_("Config file has been generated in", target_config_path)
[ "def", "generate_config", "(", "directory", ")", ":", "default_config", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "realpath", "(", "__file__", ")", ")", ",", "\"config.yml\"", ")", "target_config_path", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "directory", ",", "'config.yml'", ")", ")", "shutil", ".", "copy", "(", "default_config", ",", "target_config_path", ")", "six", ".", "print_", "(", "\"Config file has been generated in\"", ",", "target_config_path", ")" ]
Generate default config file
[ "Generate", "default", "config", "file" ]
ac40a62d4e7eca9494b4d0a14f46facf5616820c
https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/__main__.py#L170-L177
train
ricequant/rqalpha
rqalpha/__main__.py
mod
def mod(cmd, params): """ Mod management command rqalpha mod list \n rqalpha mod install xxx \n rqalpha mod uninstall xxx \n rqalpha mod enable xxx \n rqalpha mod disable xxx \n """ def list(params): """ List all mod configuration """ from tabulate import tabulate from rqalpha.utils.config import get_mod_conf mod_config = get_mod_conf() table = [] for mod_name, mod in six.iteritems(mod_config['mod']): table.append([ mod_name, ("enabled" if mod['enabled'] else "disabled") ]) headers = [ "name", "status" ] six.print_(tabulate(table, headers=headers, tablefmt="psql")) six.print_("You can use `rqalpha mod list/install/uninstall/enable/disable` to manage your mods") def install(params): """ Install third-party Mod """ try: from pip._internal import main as pip_main from pip._internal.commands.install import InstallCommand except ImportError: from pip import main as pip_main from pip.commands.install import InstallCommand params = [param for param in params] options, mod_list = InstallCommand().parse_args(params) mod_list = [mod_name for mod_name in mod_list if mod_name != "."] params = ["install"] + params for mod_name in mod_list: mod_name_index = params.index(mod_name) if mod_name.startswith("rqalpha_mod_sys_"): six.print_('System Mod can not be installed or uninstalled') return if "rqalpha_mod_" in mod_name: lib_name = mod_name else: lib_name = "rqalpha_mod_" + mod_name params[mod_name_index] = lib_name # Install Mod installed_result = pip_main(params) # Export config from rqalpha.utils.config import load_yaml, user_mod_conf_path user_conf = load_yaml(user_mod_conf_path()) if os.path.exists(user_mod_conf_path()) else {'mod': {}} if installed_result == 0: # 如果为0,则说明安装成功 if len(mod_list) == 0: """ 主要是方便 `pip install -e .` 这种方式 本地调试 Mod 使用,需要满足以下条件: 1. `rqalpha mod install -e .` 命令是在对应 自定义 Mod 的根目录下 2. 该 Mod 必须包含 `setup.py` 文件(否则也不能正常的 `pip install -e .` 来安装) 3. 该 Mod 包名必须按照 RQAlpha 的规范来命名,具体规则如下 * 必须以 `rqalpha-mod-` 来开头,比如 `rqalpha-mod-xxx-yyy` * 对应import的库名必须要 `rqalpha_mod_` 来开头,并且需要和包名后半部分一致,但是 `-` 需要替换为 `_`, 比如 `rqalpha_mod_xxx_yyy` """ mod_name = _detect_package_name_from_dir(params) mod_name = mod_name.replace("-", "_").replace("rqalpha_mod_", "") mod_list.append(mod_name) for mod_name in mod_list: if "rqalpha_mod_" in mod_name: mod_name = mod_name.replace("rqalpha_mod_", "") if "==" in mod_name: mod_name = mod_name.split('==')[0] user_conf['mod'][mod_name] = {} user_conf['mod'][mod_name]['enabled'] = False dump_config(user_mod_conf_path(), user_conf) return installed_result def uninstall(params): """ Uninstall third-party Mod """ try: from pip._internal import main as pip_main from pip._internal.commands.uninstall import UninstallCommand except ImportError: # be compatible with pip < 10.0 from pip import main as pip_main from pip.commands.uninstall import UninstallCommand params = [param for param in params] options, mod_list = UninstallCommand().parse_args(params) params = ["uninstall"] + params for mod_name in mod_list: mod_name_index = params.index(mod_name) if mod_name.startswith("rqalpha_mod_sys_"): six.print_('System Mod can not be installed or uninstalled') return if "rqalpha_mod_" in mod_name: lib_name = mod_name else: lib_name = "rqalpha_mod_" + mod_name params[mod_name_index] = lib_name # Uninstall Mod uninstalled_result = pip_main(params) # Remove Mod Config from rqalpha.utils.config import user_mod_conf_path, load_yaml user_conf = load_yaml(user_mod_conf_path()) if os.path.exists(user_mod_conf_path()) else {'mod': {}} for mod_name in mod_list: if "rqalpha_mod_" in mod_name: mod_name = mod_name.replace("rqalpha_mod_", "") del user_conf['mod'][mod_name] dump_config(user_mod_conf_path(), user_conf) return uninstalled_result def enable(params): """ enable mod """ mod_name = params[0] if "rqalpha_mod_" in mod_name: mod_name = mod_name.replace("rqalpha_mod_", "") # check whether is installed module_name = "rqalpha_mod_" + mod_name if module_name.startswith("rqalpha_mod_sys_"): module_name = "rqalpha.mod." + module_name try: import_module(module_name) except ImportError: installed_result = install([module_name]) if installed_result != 0: return from rqalpha.utils.config import user_mod_conf_path, load_yaml user_conf = load_yaml(user_mod_conf_path()) if os.path.exists(user_mod_conf_path()) else {'mod': {}} try: user_conf['mod'][mod_name]['enabled'] = True except KeyError: user_conf['mod'][mod_name] = {'enabled': True} dump_config(user_mod_conf_path(), user_conf) def disable(params): """ disable mod """ mod_name = params[0] if "rqalpha_mod_" in mod_name: mod_name = mod_name.replace("rqalpha_mod_", "") from rqalpha.utils.config import user_mod_conf_path, load_yaml user_conf = load_yaml(user_mod_conf_path()) if os.path.exists(user_mod_conf_path()) else {'mod': {}} try: user_conf['mod'][mod_name]['enabled'] = False except KeyError: user_conf['mod'][mod_name] = {'enabled': False} dump_config(user_mod_conf_path(), user_conf) locals()[cmd](params)
python
def mod(cmd, params): """ Mod management command rqalpha mod list \n rqalpha mod install xxx \n rqalpha mod uninstall xxx \n rqalpha mod enable xxx \n rqalpha mod disable xxx \n """ def list(params): """ List all mod configuration """ from tabulate import tabulate from rqalpha.utils.config import get_mod_conf mod_config = get_mod_conf() table = [] for mod_name, mod in six.iteritems(mod_config['mod']): table.append([ mod_name, ("enabled" if mod['enabled'] else "disabled") ]) headers = [ "name", "status" ] six.print_(tabulate(table, headers=headers, tablefmt="psql")) six.print_("You can use `rqalpha mod list/install/uninstall/enable/disable` to manage your mods") def install(params): """ Install third-party Mod """ try: from pip._internal import main as pip_main from pip._internal.commands.install import InstallCommand except ImportError: from pip import main as pip_main from pip.commands.install import InstallCommand params = [param for param in params] options, mod_list = InstallCommand().parse_args(params) mod_list = [mod_name for mod_name in mod_list if mod_name != "."] params = ["install"] + params for mod_name in mod_list: mod_name_index = params.index(mod_name) if mod_name.startswith("rqalpha_mod_sys_"): six.print_('System Mod can not be installed or uninstalled') return if "rqalpha_mod_" in mod_name: lib_name = mod_name else: lib_name = "rqalpha_mod_" + mod_name params[mod_name_index] = lib_name # Install Mod installed_result = pip_main(params) # Export config from rqalpha.utils.config import load_yaml, user_mod_conf_path user_conf = load_yaml(user_mod_conf_path()) if os.path.exists(user_mod_conf_path()) else {'mod': {}} if installed_result == 0: # 如果为0,则说明安装成功 if len(mod_list) == 0: """ 主要是方便 `pip install -e .` 这种方式 本地调试 Mod 使用,需要满足以下条件: 1. `rqalpha mod install -e .` 命令是在对应 自定义 Mod 的根目录下 2. 该 Mod 必须包含 `setup.py` 文件(否则也不能正常的 `pip install -e .` 来安装) 3. 该 Mod 包名必须按照 RQAlpha 的规范来命名,具体规则如下 * 必须以 `rqalpha-mod-` 来开头,比如 `rqalpha-mod-xxx-yyy` * 对应import的库名必须要 `rqalpha_mod_` 来开头,并且需要和包名后半部分一致,但是 `-` 需要替换为 `_`, 比如 `rqalpha_mod_xxx_yyy` """ mod_name = _detect_package_name_from_dir(params) mod_name = mod_name.replace("-", "_").replace("rqalpha_mod_", "") mod_list.append(mod_name) for mod_name in mod_list: if "rqalpha_mod_" in mod_name: mod_name = mod_name.replace("rqalpha_mod_", "") if "==" in mod_name: mod_name = mod_name.split('==')[0] user_conf['mod'][mod_name] = {} user_conf['mod'][mod_name]['enabled'] = False dump_config(user_mod_conf_path(), user_conf) return installed_result def uninstall(params): """ Uninstall third-party Mod """ try: from pip._internal import main as pip_main from pip._internal.commands.uninstall import UninstallCommand except ImportError: # be compatible with pip < 10.0 from pip import main as pip_main from pip.commands.uninstall import UninstallCommand params = [param for param in params] options, mod_list = UninstallCommand().parse_args(params) params = ["uninstall"] + params for mod_name in mod_list: mod_name_index = params.index(mod_name) if mod_name.startswith("rqalpha_mod_sys_"): six.print_('System Mod can not be installed or uninstalled') return if "rqalpha_mod_" in mod_name: lib_name = mod_name else: lib_name = "rqalpha_mod_" + mod_name params[mod_name_index] = lib_name # Uninstall Mod uninstalled_result = pip_main(params) # Remove Mod Config from rqalpha.utils.config import user_mod_conf_path, load_yaml user_conf = load_yaml(user_mod_conf_path()) if os.path.exists(user_mod_conf_path()) else {'mod': {}} for mod_name in mod_list: if "rqalpha_mod_" in mod_name: mod_name = mod_name.replace("rqalpha_mod_", "") del user_conf['mod'][mod_name] dump_config(user_mod_conf_path(), user_conf) return uninstalled_result def enable(params): """ enable mod """ mod_name = params[0] if "rqalpha_mod_" in mod_name: mod_name = mod_name.replace("rqalpha_mod_", "") # check whether is installed module_name = "rqalpha_mod_" + mod_name if module_name.startswith("rqalpha_mod_sys_"): module_name = "rqalpha.mod." + module_name try: import_module(module_name) except ImportError: installed_result = install([module_name]) if installed_result != 0: return from rqalpha.utils.config import user_mod_conf_path, load_yaml user_conf = load_yaml(user_mod_conf_path()) if os.path.exists(user_mod_conf_path()) else {'mod': {}} try: user_conf['mod'][mod_name]['enabled'] = True except KeyError: user_conf['mod'][mod_name] = {'enabled': True} dump_config(user_mod_conf_path(), user_conf) def disable(params): """ disable mod """ mod_name = params[0] if "rqalpha_mod_" in mod_name: mod_name = mod_name.replace("rqalpha_mod_", "") from rqalpha.utils.config import user_mod_conf_path, load_yaml user_conf = load_yaml(user_mod_conf_path()) if os.path.exists(user_mod_conf_path()) else {'mod': {}} try: user_conf['mod'][mod_name]['enabled'] = False except KeyError: user_conf['mod'][mod_name] = {'enabled': False} dump_config(user_mod_conf_path(), user_conf) locals()[cmd](params)
[ "def", "mod", "(", "cmd", ",", "params", ")", ":", "def", "list", "(", "params", ")", ":", "\"\"\"\n List all mod configuration\n \"\"\"", "from", "tabulate", "import", "tabulate", "from", "rqalpha", ".", "utils", ".", "config", "import", "get_mod_conf", "mod_config", "=", "get_mod_conf", "(", ")", "table", "=", "[", "]", "for", "mod_name", ",", "mod", "in", "six", ".", "iteritems", "(", "mod_config", "[", "'mod'", "]", ")", ":", "table", ".", "append", "(", "[", "mod_name", ",", "(", "\"enabled\"", "if", "mod", "[", "'enabled'", "]", "else", "\"disabled\"", ")", "]", ")", "headers", "=", "[", "\"name\"", ",", "\"status\"", "]", "six", ".", "print_", "(", "tabulate", "(", "table", ",", "headers", "=", "headers", ",", "tablefmt", "=", "\"psql\"", ")", ")", "six", ".", "print_", "(", "\"You can use `rqalpha mod list/install/uninstall/enable/disable` to manage your mods\"", ")", "def", "install", "(", "params", ")", ":", "\"\"\"\n Install third-party Mod\n \"\"\"", "try", ":", "from", "pip", ".", "_internal", "import", "main", "as", "pip_main", "from", "pip", ".", "_internal", ".", "commands", ".", "install", "import", "InstallCommand", "except", "ImportError", ":", "from", "pip", "import", "main", "as", "pip_main", "from", "pip", ".", "commands", ".", "install", "import", "InstallCommand", "params", "=", "[", "param", "for", "param", "in", "params", "]", "options", ",", "mod_list", "=", "InstallCommand", "(", ")", ".", "parse_args", "(", "params", ")", "mod_list", "=", "[", "mod_name", "for", "mod_name", "in", "mod_list", "if", "mod_name", "!=", "\".\"", "]", "params", "=", "[", "\"install\"", "]", "+", "params", "for", "mod_name", "in", "mod_list", ":", "mod_name_index", "=", "params", ".", "index", "(", "mod_name", ")", "if", "mod_name", ".", "startswith", "(", "\"rqalpha_mod_sys_\"", ")", ":", "six", ".", "print_", "(", "'System Mod can not be installed or uninstalled'", ")", "return", "if", "\"rqalpha_mod_\"", "in", "mod_name", ":", "lib_name", "=", "mod_name", "else", ":", "lib_name", "=", "\"rqalpha_mod_\"", "+", "mod_name", "params", "[", "mod_name_index", "]", "=", "lib_name", "# Install Mod", "installed_result", "=", "pip_main", "(", "params", ")", "# Export config", "from", "rqalpha", ".", "utils", ".", "config", "import", "load_yaml", ",", "user_mod_conf_path", "user_conf", "=", "load_yaml", "(", "user_mod_conf_path", "(", ")", ")", "if", "os", ".", "path", ".", "exists", "(", "user_mod_conf_path", "(", ")", ")", "else", "{", "'mod'", ":", "{", "}", "}", "if", "installed_result", "==", "0", ":", "# 如果为0,则说明安装成功", "if", "len", "(", "mod_list", ")", "==", "0", ":", "\"\"\"\n 主要是方便 `pip install -e .` 这种方式 本地调试 Mod 使用,需要满足以下条件:\n 1. `rqalpha mod install -e .` 命令是在对应 自定义 Mod 的根目录下\n 2. 该 Mod 必须包含 `setup.py` 文件(否则也不能正常的 `pip install -e .` 来安装)\n 3. 该 Mod 包名必须按照 RQAlpha 的规范来命名,具体规则如下\n * 必须以 `rqalpha-mod-` 来开头,比如 `rqalpha-mod-xxx-yyy`\n * 对应import的库名必须要 `rqalpha_mod_` 来开头,并且需要和包名后半部分一致,但是 `-` 需要替换为 `_`, 比如 `rqalpha_mod_xxx_yyy`\n \"\"\"", "mod_name", "=", "_detect_package_name_from_dir", "(", "params", ")", "mod_name", "=", "mod_name", ".", "replace", "(", "\"-\"", ",", "\"_\"", ")", ".", "replace", "(", "\"rqalpha_mod_\"", ",", "\"\"", ")", "mod_list", ".", "append", "(", "mod_name", ")", "for", "mod_name", "in", "mod_list", ":", "if", "\"rqalpha_mod_\"", "in", "mod_name", ":", "mod_name", "=", "mod_name", ".", "replace", "(", "\"rqalpha_mod_\"", ",", "\"\"", ")", "if", "\"==\"", "in", "mod_name", ":", "mod_name", "=", "mod_name", ".", "split", "(", "'=='", ")", "[", "0", "]", "user_conf", "[", "'mod'", "]", "[", "mod_name", "]", "=", "{", "}", "user_conf", "[", "'mod'", "]", "[", "mod_name", "]", "[", "'enabled'", "]", "=", "False", "dump_config", "(", "user_mod_conf_path", "(", ")", ",", "user_conf", ")", "return", "installed_result", "def", "uninstall", "(", "params", ")", ":", "\"\"\"\n Uninstall third-party Mod\n \"\"\"", "try", ":", "from", "pip", ".", "_internal", "import", "main", "as", "pip_main", "from", "pip", ".", "_internal", ".", "commands", ".", "uninstall", "import", "UninstallCommand", "except", "ImportError", ":", "# be compatible with pip < 10.0", "from", "pip", "import", "main", "as", "pip_main", "from", "pip", ".", "commands", ".", "uninstall", "import", "UninstallCommand", "params", "=", "[", "param", "for", "param", "in", "params", "]", "options", ",", "mod_list", "=", "UninstallCommand", "(", ")", ".", "parse_args", "(", "params", ")", "params", "=", "[", "\"uninstall\"", "]", "+", "params", "for", "mod_name", "in", "mod_list", ":", "mod_name_index", "=", "params", ".", "index", "(", "mod_name", ")", "if", "mod_name", ".", "startswith", "(", "\"rqalpha_mod_sys_\"", ")", ":", "six", ".", "print_", "(", "'System Mod can not be installed or uninstalled'", ")", "return", "if", "\"rqalpha_mod_\"", "in", "mod_name", ":", "lib_name", "=", "mod_name", "else", ":", "lib_name", "=", "\"rqalpha_mod_\"", "+", "mod_name", "params", "[", "mod_name_index", "]", "=", "lib_name", "# Uninstall Mod", "uninstalled_result", "=", "pip_main", "(", "params", ")", "# Remove Mod Config", "from", "rqalpha", ".", "utils", ".", "config", "import", "user_mod_conf_path", ",", "load_yaml", "user_conf", "=", "load_yaml", "(", "user_mod_conf_path", "(", ")", ")", "if", "os", ".", "path", ".", "exists", "(", "user_mod_conf_path", "(", ")", ")", "else", "{", "'mod'", ":", "{", "}", "}", "for", "mod_name", "in", "mod_list", ":", "if", "\"rqalpha_mod_\"", "in", "mod_name", ":", "mod_name", "=", "mod_name", ".", "replace", "(", "\"rqalpha_mod_\"", ",", "\"\"", ")", "del", "user_conf", "[", "'mod'", "]", "[", "mod_name", "]", "dump_config", "(", "user_mod_conf_path", "(", ")", ",", "user_conf", ")", "return", "uninstalled_result", "def", "enable", "(", "params", ")", ":", "\"\"\"\n enable mod\n \"\"\"", "mod_name", "=", "params", "[", "0", "]", "if", "\"rqalpha_mod_\"", "in", "mod_name", ":", "mod_name", "=", "mod_name", ".", "replace", "(", "\"rqalpha_mod_\"", ",", "\"\"", ")", "# check whether is installed", "module_name", "=", "\"rqalpha_mod_\"", "+", "mod_name", "if", "module_name", ".", "startswith", "(", "\"rqalpha_mod_sys_\"", ")", ":", "module_name", "=", "\"rqalpha.mod.\"", "+", "module_name", "try", ":", "import_module", "(", "module_name", ")", "except", "ImportError", ":", "installed_result", "=", "install", "(", "[", "module_name", "]", ")", "if", "installed_result", "!=", "0", ":", "return", "from", "rqalpha", ".", "utils", ".", "config", "import", "user_mod_conf_path", ",", "load_yaml", "user_conf", "=", "load_yaml", "(", "user_mod_conf_path", "(", ")", ")", "if", "os", ".", "path", ".", "exists", "(", "user_mod_conf_path", "(", ")", ")", "else", "{", "'mod'", ":", "{", "}", "}", "try", ":", "user_conf", "[", "'mod'", "]", "[", "mod_name", "]", "[", "'enabled'", "]", "=", "True", "except", "KeyError", ":", "user_conf", "[", "'mod'", "]", "[", "mod_name", "]", "=", "{", "'enabled'", ":", "True", "}", "dump_config", "(", "user_mod_conf_path", "(", ")", ",", "user_conf", ")", "def", "disable", "(", "params", ")", ":", "\"\"\"\n disable mod\n \"\"\"", "mod_name", "=", "params", "[", "0", "]", "if", "\"rqalpha_mod_\"", "in", "mod_name", ":", "mod_name", "=", "mod_name", ".", "replace", "(", "\"rqalpha_mod_\"", ",", "\"\"", ")", "from", "rqalpha", ".", "utils", ".", "config", "import", "user_mod_conf_path", ",", "load_yaml", "user_conf", "=", "load_yaml", "(", "user_mod_conf_path", "(", ")", ")", "if", "os", ".", "path", ".", "exists", "(", "user_mod_conf_path", "(", ")", ")", "else", "{", "'mod'", ":", "{", "}", "}", "try", ":", "user_conf", "[", "'mod'", "]", "[", "mod_name", "]", "[", "'enabled'", "]", "=", "False", "except", "KeyError", ":", "user_conf", "[", "'mod'", "]", "[", "mod_name", "]", "=", "{", "'enabled'", ":", "False", "}", "dump_config", "(", "user_mod_conf_path", "(", ")", ",", "user_conf", ")", "locals", "(", ")", "[", "cmd", "]", "(", "params", ")" ]
Mod management command rqalpha mod list \n rqalpha mod install xxx \n rqalpha mod uninstall xxx \n rqalpha mod enable xxx \n rqalpha mod disable xxx \n
[ "Mod", "management", "command" ]
ac40a62d4e7eca9494b4d0a14f46facf5616820c
https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/__main__.py#L188-L379
train
ricequant/rqalpha
rqalpha/mod/rqalpha_mod_sys_analyser/__init__.py
plot
def plot(result_pickle_file_path, show, plot_save_file): """ [sys_analyser] draw result DataFrame """ import pandas as pd from .plot import plot_result result_dict = pd.read_pickle(result_pickle_file_path) plot_result(result_dict, show, plot_save_file)
python
def plot(result_pickle_file_path, show, plot_save_file): """ [sys_analyser] draw result DataFrame """ import pandas as pd from .plot import plot_result result_dict = pd.read_pickle(result_pickle_file_path) plot_result(result_dict, show, plot_save_file)
[ "def", "plot", "(", "result_pickle_file_path", ",", "show", ",", "plot_save_file", ")", ":", "import", "pandas", "as", "pd", "from", ".", "plot", "import", "plot_result", "result_dict", "=", "pd", ".", "read_pickle", "(", "result_pickle_file_path", ")", "plot_result", "(", "result_dict", ",", "show", ",", "plot_save_file", ")" ]
[sys_analyser] draw result DataFrame
[ "[", "sys_analyser", "]", "draw", "result", "DataFrame" ]
ac40a62d4e7eca9494b4d0a14f46facf5616820c
https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/mod/rqalpha_mod_sys_analyser/__init__.py#L78-L86
train
ricequant/rqalpha
rqalpha/mod/rqalpha_mod_sys_analyser/__init__.py
report
def report(result_pickle_file_path, target_report_csv_path): """ [sys_analyser] Generate report from backtest output file """ import pandas as pd result_dict = pd.read_pickle(result_pickle_file_path) from .report import generate_report generate_report(result_dict, target_report_csv_path)
python
def report(result_pickle_file_path, target_report_csv_path): """ [sys_analyser] Generate report from backtest output file """ import pandas as pd result_dict = pd.read_pickle(result_pickle_file_path) from .report import generate_report generate_report(result_dict, target_report_csv_path)
[ "def", "report", "(", "result_pickle_file_path", ",", "target_report_csv_path", ")", ":", "import", "pandas", "as", "pd", "result_dict", "=", "pd", ".", "read_pickle", "(", "result_pickle_file_path", ")", "from", ".", "report", "import", "generate_report", "generate_report", "(", "result_dict", ",", "target_report_csv_path", ")" ]
[sys_analyser] Generate report from backtest output file
[ "[", "sys_analyser", "]", "Generate", "report", "from", "backtest", "output", "file" ]
ac40a62d4e7eca9494b4d0a14f46facf5616820c
https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/mod/rqalpha_mod_sys_analyser/__init__.py#L92-L100
train
ricequant/rqalpha
rqalpha/mod/rqalpha_mod_sys_accounts/account_model/future_account.py
FutureAccount.margin
def margin(self): """ [float] 总保证金 """ return sum(position.margin for position in six.itervalues(self._positions))
python
def margin(self): """ [float] 总保证金 """ return sum(position.margin for position in six.itervalues(self._positions))
[ "def", "margin", "(", "self", ")", ":", "return", "sum", "(", "position", ".", "margin", "for", "position", "in", "six", ".", "itervalues", "(", "self", ".", "_positions", ")", ")" ]
[float] 总保证金
[ "[", "float", "]", "总保证金" ]
ac40a62d4e7eca9494b4d0a14f46facf5616820c
https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/mod/rqalpha_mod_sys_accounts/account_model/future_account.py#L177-L181
train
ricequant/rqalpha
rqalpha/mod/rqalpha_mod_sys_accounts/account_model/future_account.py
FutureAccount.buy_margin
def buy_margin(self): """ [float] 买方向保证金 """ return sum(position.buy_margin for position in six.itervalues(self._positions))
python
def buy_margin(self): """ [float] 买方向保证金 """ return sum(position.buy_margin for position in six.itervalues(self._positions))
[ "def", "buy_margin", "(", "self", ")", ":", "return", "sum", "(", "position", ".", "buy_margin", "for", "position", "in", "six", ".", "itervalues", "(", "self", ".", "_positions", ")", ")" ]
[float] 买方向保证金
[ "[", "float", "]", "买方向保证金" ]
ac40a62d4e7eca9494b4d0a14f46facf5616820c
https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/mod/rqalpha_mod_sys_accounts/account_model/future_account.py#L184-L188
train
ricequant/rqalpha
rqalpha/mod/rqalpha_mod_sys_accounts/account_model/future_account.py
FutureAccount.sell_margin
def sell_margin(self): """ [float] 卖方向保证金 """ return sum(position.sell_margin for position in six.itervalues(self._positions))
python
def sell_margin(self): """ [float] 卖方向保证金 """ return sum(position.sell_margin for position in six.itervalues(self._positions))
[ "def", "sell_margin", "(", "self", ")", ":", "return", "sum", "(", "position", ".", "sell_margin", "for", "position", "in", "six", ".", "itervalues", "(", "self", ".", "_positions", ")", ")" ]
[float] 卖方向保证金
[ "[", "float", "]", "卖方向保证金" ]
ac40a62d4e7eca9494b4d0a14f46facf5616820c
https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/mod/rqalpha_mod_sys_accounts/account_model/future_account.py#L191-L195
train
ricequant/rqalpha
rqalpha/mod/rqalpha_mod_sys_accounts/account_model/future_account.py
FutureAccount.holding_pnl
def holding_pnl(self): """ [float] 浮动盈亏 """ return sum(position.holding_pnl for position in six.itervalues(self._positions))
python
def holding_pnl(self): """ [float] 浮动盈亏 """ return sum(position.holding_pnl for position in six.itervalues(self._positions))
[ "def", "holding_pnl", "(", "self", ")", ":", "return", "sum", "(", "position", ".", "holding_pnl", "for", "position", "in", "six", ".", "itervalues", "(", "self", ".", "_positions", ")", ")" ]
[float] 浮动盈亏
[ "[", "float", "]", "浮动盈亏" ]
ac40a62d4e7eca9494b4d0a14f46facf5616820c
https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/mod/rqalpha_mod_sys_accounts/account_model/future_account.py#L206-L210
train
ricequant/rqalpha
rqalpha/mod/rqalpha_mod_sys_accounts/account_model/future_account.py
FutureAccount.realized_pnl
def realized_pnl(self): """ [float] 平仓盈亏 """ return sum(position.realized_pnl for position in six.itervalues(self._positions))
python
def realized_pnl(self): """ [float] 平仓盈亏 """ return sum(position.realized_pnl for position in six.itervalues(self._positions))
[ "def", "realized_pnl", "(", "self", ")", ":", "return", "sum", "(", "position", ".", "realized_pnl", "for", "position", "in", "six", ".", "itervalues", "(", "self", ".", "_positions", ")", ")" ]
[float] 平仓盈亏
[ "[", "float", "]", "平仓盈亏" ]
ac40a62d4e7eca9494b4d0a14f46facf5616820c
https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/mod/rqalpha_mod_sys_accounts/account_model/future_account.py#L213-L217
train
ricequant/rqalpha
rqalpha/api/api_extension.py
order
def order(order_book_id, quantity, price=None, style=None): """ 全品种通用智能调仓函数 如果不指定 price, 则相当于下 MarketOrder 如果 order_book_id 是股票,等同于调用 order_shares 如果 order_book_id 是期货,则进行智能下单: * quantity 表示调仓量 * 如果 quantity 为正数,则先平 Sell 方向仓位,再开 Buy 方向仓位 * 如果 quantity 为负数,则先平 Buy 反向仓位,再开 Sell 方向仓位 :param order_book_id: 下单标的物 :type order_book_id: :class:`~Instrument` object | `str` :param int quantity: 调仓量 :param float price: 下单价格 :param style: 下单类型, 默认是市价单。目前支持的订单类型有 :class:`~LimitOrder` 和 :class:`~MarketOrder` :type style: `OrderStyle` object :return: list[:class:`~Order`] :example: .. code-block:: python3 :linenos: # 当前仓位为0 # RB1710 多方向调仓2手:调整后变为 BUY 2手 order('RB1710', 2) # RB1710 空方向调仓3手:先平多方向2手 在开空方向1手,调整后变为 SELL 1手 order('RB1710', -3) """ style = cal_style(price, style) orders = Environment.get_instance().portfolio.order(order_book_id, quantity, style) if isinstance(orders, Order): return [orders] return orders
python
def order(order_book_id, quantity, price=None, style=None): """ 全品种通用智能调仓函数 如果不指定 price, 则相当于下 MarketOrder 如果 order_book_id 是股票,等同于调用 order_shares 如果 order_book_id 是期货,则进行智能下单: * quantity 表示调仓量 * 如果 quantity 为正数,则先平 Sell 方向仓位,再开 Buy 方向仓位 * 如果 quantity 为负数,则先平 Buy 反向仓位,再开 Sell 方向仓位 :param order_book_id: 下单标的物 :type order_book_id: :class:`~Instrument` object | `str` :param int quantity: 调仓量 :param float price: 下单价格 :param style: 下单类型, 默认是市价单。目前支持的订单类型有 :class:`~LimitOrder` 和 :class:`~MarketOrder` :type style: `OrderStyle` object :return: list[:class:`~Order`] :example: .. code-block:: python3 :linenos: # 当前仓位为0 # RB1710 多方向调仓2手:调整后变为 BUY 2手 order('RB1710', 2) # RB1710 空方向调仓3手:先平多方向2手 在开空方向1手,调整后变为 SELL 1手 order('RB1710', -3) """ style = cal_style(price, style) orders = Environment.get_instance().portfolio.order(order_book_id, quantity, style) if isinstance(orders, Order): return [orders] return orders
[ "def", "order", "(", "order_book_id", ",", "quantity", ",", "price", "=", "None", ",", "style", "=", "None", ")", ":", "style", "=", "cal_style", "(", "price", ",", "style", ")", "orders", "=", "Environment", ".", "get_instance", "(", ")", ".", "portfolio", ".", "order", "(", "order_book_id", ",", "quantity", ",", "style", ")", "if", "isinstance", "(", "orders", ",", "Order", ")", ":", "return", "[", "orders", "]", "return", "orders" ]
全品种通用智能调仓函数 如果不指定 price, 则相当于下 MarketOrder 如果 order_book_id 是股票,等同于调用 order_shares 如果 order_book_id 是期货,则进行智能下单: * quantity 表示调仓量 * 如果 quantity 为正数,则先平 Sell 方向仓位,再开 Buy 方向仓位 * 如果 quantity 为负数,则先平 Buy 反向仓位,再开 Sell 方向仓位 :param order_book_id: 下单标的物 :type order_book_id: :class:`~Instrument` object | `str` :param int quantity: 调仓量 :param float price: 下单价格 :param style: 下单类型, 默认是市价单。目前支持的订单类型有 :class:`~LimitOrder` 和 :class:`~MarketOrder` :type style: `OrderStyle` object :return: list[:class:`~Order`] :example: .. code-block:: python3 :linenos: # 当前仓位为0 # RB1710 多方向调仓2手:调整后变为 BUY 2手 order('RB1710', 2) # RB1710 空方向调仓3手:先平多方向2手 在开空方向1手,调整后变为 SELL 1手 order('RB1710', -3)
[ "全品种通用智能调仓函数" ]
ac40a62d4e7eca9494b4d0a14f46facf5616820c
https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/api/api_extension.py#L52-L96
train
elastic/elasticsearch-py
elasticsearch/client/xpack/sql.py
SqlClient.clear_cursor
def clear_cursor(self, body, params=None): """ `<Clear SQL cursor>`_ :arg body: Specify the cursor value in the `cursor` element to clean the cursor. """ if body in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'body'.") return self.transport.perform_request( "POST", "/_sql/close", params=params, body=body )
python
def clear_cursor(self, body, params=None): """ `<Clear SQL cursor>`_ :arg body: Specify the cursor value in the `cursor` element to clean the cursor. """ if body in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'body'.") return self.transport.perform_request( "POST", "/_sql/close", params=params, body=body )
[ "def", "clear_cursor", "(", "self", ",", "body", ",", "params", "=", "None", ")", ":", "if", "body", "in", "SKIP_IN_PATH", ":", "raise", "ValueError", "(", "\"Empty value passed for a required argument 'body'.\"", ")", "return", "self", ".", "transport", ".", "perform_request", "(", "\"POST\"", ",", "\"/_sql/close\"", ",", "params", "=", "params", ",", "body", "=", "body", ")" ]
`<Clear SQL cursor>`_ :arg body: Specify the cursor value in the `cursor` element to clean the cursor.
[ "<Clear", "SQL", "cursor", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/xpack/sql.py#L6-L17
train
elastic/elasticsearch-py
elasticsearch/client/xpack/sql.py
SqlClient.query
def query(self, body, params=None): """ `<Execute SQL>`_ :arg body: Use the `query` element to start a query. Use the `cursor` element to continue a query. :arg format: a short version of the Accept header, e.g. json, yaml """ if body in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'body'.") return self.transport.perform_request("POST", "/_sql", params=params, body=body)
python
def query(self, body, params=None): """ `<Execute SQL>`_ :arg body: Use the `query` element to start a query. Use the `cursor` element to continue a query. :arg format: a short version of the Accept header, e.g. json, yaml """ if body in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'body'.") return self.transport.perform_request("POST", "/_sql", params=params, body=body)
[ "def", "query", "(", "self", ",", "body", ",", "params", "=", "None", ")", ":", "if", "body", "in", "SKIP_IN_PATH", ":", "raise", "ValueError", "(", "\"Empty value passed for a required argument 'body'.\"", ")", "return", "self", ".", "transport", ".", "perform_request", "(", "\"POST\"", ",", "\"/_sql\"", ",", "params", "=", "params", ",", "body", "=", "body", ")" ]
`<Execute SQL>`_ :arg body: Use the `query` element to start a query. Use the `cursor` element to continue a query. :arg format: a short version of the Accept header, e.g. json, yaml
[ "<Execute", "SQL", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/xpack/sql.py#L20-L30
train
elastic/elasticsearch-py
elasticsearch/client/xpack/sql.py
SqlClient.translate
def translate(self, body, params=None): """ `<Translate SQL into Elasticsearch queries>`_ :arg body: Specify the query in the `query` element. """ if body in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'body'.") return self.transport.perform_request( "POST", "/_sql/translate", params=params, body=body )
python
def translate(self, body, params=None): """ `<Translate SQL into Elasticsearch queries>`_ :arg body: Specify the query in the `query` element. """ if body in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'body'.") return self.transport.perform_request( "POST", "/_sql/translate", params=params, body=body )
[ "def", "translate", "(", "self", ",", "body", ",", "params", "=", "None", ")", ":", "if", "body", "in", "SKIP_IN_PATH", ":", "raise", "ValueError", "(", "\"Empty value passed for a required argument 'body'.\"", ")", "return", "self", ".", "transport", ".", "perform_request", "(", "\"POST\"", ",", "\"/_sql/translate\"", ",", "params", "=", "params", ",", "body", "=", "body", ")" ]
`<Translate SQL into Elasticsearch queries>`_ :arg body: Specify the query in the `query` element.
[ "<Translate", "SQL", "into", "Elasticsearch", "queries", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/xpack/sql.py#L33-L43
train
elastic/elasticsearch-py
elasticsearch/connection/base.py
Connection.log_request_success
def log_request_success(self, method, full_url, path, body, status_code, response, duration): """ Log a successful API call. """ # TODO: optionally pass in params instead of full_url and do urlencode only when needed # body has already been serialized to utf-8, deserialize it for logging # TODO: find a better way to avoid (de)encoding the body back and forth if body: try: body = body.decode('utf-8', 'ignore') except AttributeError: pass logger.info( '%s %s [status:%s request:%.3fs]', method, full_url, status_code, duration ) logger.debug('> %s', body) logger.debug('< %s', response) self._log_trace(method, path, body, status_code, response, duration)
python
def log_request_success(self, method, full_url, path, body, status_code, response, duration): """ Log a successful API call. """ # TODO: optionally pass in params instead of full_url and do urlencode only when needed # body has already been serialized to utf-8, deserialize it for logging # TODO: find a better way to avoid (de)encoding the body back and forth if body: try: body = body.decode('utf-8', 'ignore') except AttributeError: pass logger.info( '%s %s [status:%s request:%.3fs]', method, full_url, status_code, duration ) logger.debug('> %s', body) logger.debug('< %s', response) self._log_trace(method, path, body, status_code, response, duration)
[ "def", "log_request_success", "(", "self", ",", "method", ",", "full_url", ",", "path", ",", "body", ",", "status_code", ",", "response", ",", "duration", ")", ":", "# TODO: optionally pass in params instead of full_url and do urlencode only when needed", "# body has already been serialized to utf-8, deserialize it for logging", "# TODO: find a better way to avoid (de)encoding the body back and forth", "if", "body", ":", "try", ":", "body", "=", "body", ".", "decode", "(", "'utf-8'", ",", "'ignore'", ")", "except", "AttributeError", ":", "pass", "logger", ".", "info", "(", "'%s %s [status:%s request:%.3fs]'", ",", "method", ",", "full_url", ",", "status_code", ",", "duration", ")", "logger", ".", "debug", "(", "'> %s'", ",", "body", ")", "logger", ".", "debug", "(", "'< %s'", ",", "response", ")", "self", ".", "_log_trace", "(", "method", ",", "path", ",", "body", ",", "status_code", ",", "response", ",", "duration", ")" ]
Log a successful API call.
[ "Log", "a", "successful", "API", "call", "." ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/connection/base.py#L72-L91
train
elastic/elasticsearch-py
elasticsearch/connection/base.py
Connection.log_request_fail
def log_request_fail(self, method, full_url, path, body, duration, status_code=None, response=None, exception=None): """ Log an unsuccessful API call. """ # do not log 404s on HEAD requests if method == 'HEAD' and status_code == 404: return logger.warning( '%s %s [status:%s request:%.3fs]', method, full_url, status_code or 'N/A', duration, exc_info=exception is not None ) # body has already been serialized to utf-8, deserialize it for logging # TODO: find a better way to avoid (de)encoding the body back and forth if body: try: body = body.decode('utf-8', 'ignore') except AttributeError: pass logger.debug('> %s', body) self._log_trace(method, path, body, status_code, response, duration) if response is not None: logger.debug('< %s', response)
python
def log_request_fail(self, method, full_url, path, body, duration, status_code=None, response=None, exception=None): """ Log an unsuccessful API call. """ # do not log 404s on HEAD requests if method == 'HEAD' and status_code == 404: return logger.warning( '%s %s [status:%s request:%.3fs]', method, full_url, status_code or 'N/A', duration, exc_info=exception is not None ) # body has already been serialized to utf-8, deserialize it for logging # TODO: find a better way to avoid (de)encoding the body back and forth if body: try: body = body.decode('utf-8', 'ignore') except AttributeError: pass logger.debug('> %s', body) self._log_trace(method, path, body, status_code, response, duration) if response is not None: logger.debug('< %s', response)
[ "def", "log_request_fail", "(", "self", ",", "method", ",", "full_url", ",", "path", ",", "body", ",", "duration", ",", "status_code", "=", "None", ",", "response", "=", "None", ",", "exception", "=", "None", ")", ":", "# do not log 404s on HEAD requests", "if", "method", "==", "'HEAD'", "and", "status_code", "==", "404", ":", "return", "logger", ".", "warning", "(", "'%s %s [status:%s request:%.3fs]'", ",", "method", ",", "full_url", ",", "status_code", "or", "'N/A'", ",", "duration", ",", "exc_info", "=", "exception", "is", "not", "None", ")", "# body has already been serialized to utf-8, deserialize it for logging", "# TODO: find a better way to avoid (de)encoding the body back and forth", "if", "body", ":", "try", ":", "body", "=", "body", ".", "decode", "(", "'utf-8'", ",", "'ignore'", ")", "except", "AttributeError", ":", "pass", "logger", ".", "debug", "(", "'> %s'", ",", "body", ")", "self", ".", "_log_trace", "(", "method", ",", "path", ",", "body", ",", "status_code", ",", "response", ",", "duration", ")", "if", "response", "is", "not", "None", ":", "logger", ".", "debug", "(", "'< %s'", ",", "response", ")" ]
Log an unsuccessful API call.
[ "Log", "an", "unsuccessful", "API", "call", "." ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/connection/base.py#L93-L116
train
elastic/elasticsearch-py
elasticsearch/connection/base.py
Connection._raise_error
def _raise_error(self, status_code, raw_data): """ Locate appropriate exception and raise it. """ error_message = raw_data additional_info = None try: if raw_data: additional_info = json.loads(raw_data) error_message = additional_info.get('error', error_message) if isinstance(error_message, dict) and 'type' in error_message: error_message = error_message['type'] except (ValueError, TypeError) as err: logger.warning('Undecodable raw error response from server: %s', err) raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info)
python
def _raise_error(self, status_code, raw_data): """ Locate appropriate exception and raise it. """ error_message = raw_data additional_info = None try: if raw_data: additional_info = json.loads(raw_data) error_message = additional_info.get('error', error_message) if isinstance(error_message, dict) and 'type' in error_message: error_message = error_message['type'] except (ValueError, TypeError) as err: logger.warning('Undecodable raw error response from server: %s', err) raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info)
[ "def", "_raise_error", "(", "self", ",", "status_code", ",", "raw_data", ")", ":", "error_message", "=", "raw_data", "additional_info", "=", "None", "try", ":", "if", "raw_data", ":", "additional_info", "=", "json", ".", "loads", "(", "raw_data", ")", "error_message", "=", "additional_info", ".", "get", "(", "'error'", ",", "error_message", ")", "if", "isinstance", "(", "error_message", ",", "dict", ")", "and", "'type'", "in", "error_message", ":", "error_message", "=", "error_message", "[", "'type'", "]", "except", "(", "ValueError", ",", "TypeError", ")", "as", "err", ":", "logger", ".", "warning", "(", "'Undecodable raw error response from server: %s'", ",", "err", ")", "raise", "HTTP_EXCEPTIONS", ".", "get", "(", "status_code", ",", "TransportError", ")", "(", "status_code", ",", "error_message", ",", "additional_info", ")" ]
Locate appropriate exception and raise it.
[ "Locate", "appropriate", "exception", "and", "raise", "it", "." ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/connection/base.py#L118-L131
train
elastic/elasticsearch-py
elasticsearch/client/__init__.py
_normalize_hosts
def _normalize_hosts(hosts): """ Helper function to transform hosts argument to :class:`~elasticsearch.Elasticsearch` to a list of dicts. """ # if hosts are empty, just defer to defaults down the line if hosts is None: return [{}] # passed in just one string if isinstance(hosts, string_types): hosts = [hosts] out = [] # normalize hosts to dicts for host in hosts: if isinstance(host, string_types): if "://" not in host: host = "//%s" % host parsed_url = urlparse(host) h = {"host": parsed_url.hostname} if parsed_url.port: h["port"] = parsed_url.port if parsed_url.scheme == "https": h["port"] = parsed_url.port or 443 h["use_ssl"] = True if parsed_url.username or parsed_url.password: h["http_auth"] = "%s:%s" % ( unquote(parsed_url.username), unquote(parsed_url.password), ) if parsed_url.path and parsed_url.path != "/": h["url_prefix"] = parsed_url.path out.append(h) else: out.append(host) return out
python
def _normalize_hosts(hosts): """ Helper function to transform hosts argument to :class:`~elasticsearch.Elasticsearch` to a list of dicts. """ # if hosts are empty, just defer to defaults down the line if hosts is None: return [{}] # passed in just one string if isinstance(hosts, string_types): hosts = [hosts] out = [] # normalize hosts to dicts for host in hosts: if isinstance(host, string_types): if "://" not in host: host = "//%s" % host parsed_url = urlparse(host) h = {"host": parsed_url.hostname} if parsed_url.port: h["port"] = parsed_url.port if parsed_url.scheme == "https": h["port"] = parsed_url.port or 443 h["use_ssl"] = True if parsed_url.username or parsed_url.password: h["http_auth"] = "%s:%s" % ( unquote(parsed_url.username), unquote(parsed_url.password), ) if parsed_url.path and parsed_url.path != "/": h["url_prefix"] = parsed_url.path out.append(h) else: out.append(host) return out
[ "def", "_normalize_hosts", "(", "hosts", ")", ":", "# if hosts are empty, just defer to defaults down the line", "if", "hosts", "is", "None", ":", "return", "[", "{", "}", "]", "# passed in just one string", "if", "isinstance", "(", "hosts", ",", "string_types", ")", ":", "hosts", "=", "[", "hosts", "]", "out", "=", "[", "]", "# normalize hosts to dicts", "for", "host", "in", "hosts", ":", "if", "isinstance", "(", "host", ",", "string_types", ")", ":", "if", "\"://\"", "not", "in", "host", ":", "host", "=", "\"//%s\"", "%", "host", "parsed_url", "=", "urlparse", "(", "host", ")", "h", "=", "{", "\"host\"", ":", "parsed_url", ".", "hostname", "}", "if", "parsed_url", ".", "port", ":", "h", "[", "\"port\"", "]", "=", "parsed_url", ".", "port", "if", "parsed_url", ".", "scheme", "==", "\"https\"", ":", "h", "[", "\"port\"", "]", "=", "parsed_url", ".", "port", "or", "443", "h", "[", "\"use_ssl\"", "]", "=", "True", "if", "parsed_url", ".", "username", "or", "parsed_url", ".", "password", ":", "h", "[", "\"http_auth\"", "]", "=", "\"%s:%s\"", "%", "(", "unquote", "(", "parsed_url", ".", "username", ")", ",", "unquote", "(", "parsed_url", ".", "password", ")", ",", ")", "if", "parsed_url", ".", "path", "and", "parsed_url", ".", "path", "!=", "\"/\"", ":", "h", "[", "\"url_prefix\"", "]", "=", "parsed_url", ".", "path", "out", ".", "append", "(", "h", ")", "else", ":", "out", ".", "append", "(", "host", ")", "return", "out" ]
Helper function to transform hosts argument to :class:`~elasticsearch.Elasticsearch` to a list of dicts.
[ "Helper", "function", "to", "transform", "hosts", "argument", "to", ":", "class", ":", "~elasticsearch", ".", "Elasticsearch", "to", "a", "list", "of", "dicts", "." ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/__init__.py#L21-L63
train
elastic/elasticsearch-py
elasticsearch/client/__init__.py
Elasticsearch.ping
def ping(self, params=None): """ Returns True if the cluster is up, False otherwise. `<http://www.elastic.co/guide/>`_ """ try: return self.transport.perform_request("HEAD", "/", params=params) except TransportError: return False
python
def ping(self, params=None): """ Returns True if the cluster is up, False otherwise. `<http://www.elastic.co/guide/>`_ """ try: return self.transport.perform_request("HEAD", "/", params=params) except TransportError: return False
[ "def", "ping", "(", "self", ",", "params", "=", "None", ")", ":", "try", ":", "return", "self", ".", "transport", ".", "perform_request", "(", "\"HEAD\"", ",", "\"/\"", ",", "params", "=", "params", ")", "except", "TransportError", ":", "return", "False" ]
Returns True if the cluster is up, False otherwise. `<http://www.elastic.co/guide/>`_
[ "Returns", "True", "if", "the", "cluster", "is", "up", "False", "otherwise", ".", "<http", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/__init__.py#L243-L251
train
elastic/elasticsearch-py
elasticsearch/client/__init__.py
Elasticsearch.mget
def mget(self, body, doc_type=None, index=None, params=None): """ Get multiple documents based on an index, type (optional) and ids. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-multi-get.html>`_ :arg body: Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL. :arg index: The name of the index :arg _source: True or false to return the _source field or not, or a list of fields to return :arg _source_exclude: A list of fields to exclude from the returned _source field :arg _source_include: A list of fields to extract and return from the _source field :arg preference: Specify the node or shard the operation should be performed on (default: random) :arg realtime: Specify whether to perform the operation in realtime or search mode :arg refresh: Refresh the shard containing the document before performing the operation :arg routing: Specific routing value :arg stored_fields: A comma-separated list of stored fields to return in the response """ if body in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'body'.") return self.transport.perform_request( "GET", _make_path(index, doc_type, "_mget"), params=params, body=body )
python
def mget(self, body, doc_type=None, index=None, params=None): """ Get multiple documents based on an index, type (optional) and ids. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-multi-get.html>`_ :arg body: Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL. :arg index: The name of the index :arg _source: True or false to return the _source field or not, or a list of fields to return :arg _source_exclude: A list of fields to exclude from the returned _source field :arg _source_include: A list of fields to extract and return from the _source field :arg preference: Specify the node or shard the operation should be performed on (default: random) :arg realtime: Specify whether to perform the operation in realtime or search mode :arg refresh: Refresh the shard containing the document before performing the operation :arg routing: Specific routing value :arg stored_fields: A comma-separated list of stored fields to return in the response """ if body in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'body'.") return self.transport.perform_request( "GET", _make_path(index, doc_type, "_mget"), params=params, body=body )
[ "def", "mget", "(", "self", ",", "body", ",", "doc_type", "=", "None", ",", "index", "=", "None", ",", "params", "=", "None", ")", ":", "if", "body", "in", "SKIP_IN_PATH", ":", "raise", "ValueError", "(", "\"Empty value passed for a required argument 'body'.\"", ")", "return", "self", ".", "transport", ".", "perform_request", "(", "\"GET\"", ",", "_make_path", "(", "index", ",", "doc_type", ",", "\"_mget\"", ")", ",", "params", "=", "params", ",", "body", "=", "body", ")" ]
Get multiple documents based on an index, type (optional) and ids. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-multi-get.html>`_ :arg body: Document identifiers; can be either `docs` (containing full document information) or `ids` (when index and type is provided in the URL. :arg index: The name of the index :arg _source: True or false to return the _source field or not, or a list of fields to return :arg _source_exclude: A list of fields to exclude from the returned _source field :arg _source_include: A list of fields to extract and return from the _source field :arg preference: Specify the node or shard the operation should be performed on (default: random) :arg realtime: Specify whether to perform the operation in realtime or search mode :arg refresh: Refresh the shard containing the document before performing the operation :arg routing: Specific routing value :arg stored_fields: A comma-separated list of stored fields to return in the response
[ "Get", "multiple", "documents", "based", "on", "an", "index", "type", "(", "optional", ")", "and", "ids", ".", "<http", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "docs", "-", "multi", "-", "get", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/__init__.py#L566-L595
train
elastic/elasticsearch-py
elasticsearch/client/__init__.py
Elasticsearch.update
def update(self, index, id, doc_type="_doc", body=None, params=None): """ Update a document based on a script or partial data provided. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update.html>`_ :arg index: The name of the index :arg id: Document ID :arg body: The request definition using either `script` or partial `doc` :arg _source: True or false to return the _source field or not, or a list of fields to return :arg _source_exclude: A list of fields to exclude from the returned _source field :arg _source_include: A list of fields to extract and return from the _source field :arg fields: A comma-separated list of fields to return in the response :arg if_seq_no: :arg if_primary_term: :arg lang: The script language (default: painless) :arg parent: ID of the parent document. Is is only used for routing and when for the upsert request :arg refresh: If `true` then refresh the effected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` (the default) then do nothing with refreshes., valid choices are: 'true', 'false', 'wait_forarg retry_on_conflict: Specify how many times should the operation be retried when a conflict occurs (default: 0) :arg routing: Specific routing value :arg timeout: Explicit operation timeout :arg timestamp: Explicit timestamp for the document :arg ttl: Expiration time for the document :arg version: Explicit version number for concurrency control :arg version_type: Specific version type, valid choices are: 'internal', 'force' :arg wait_for_active_shards: Sets the number of shard copies that must be active before proceeding with the update operation. Defaults to 1, meaning the primary shard only. Set to `all` for all shard copies, otherwise set to any non-negative value less than or equal to the total number of copies for the shard (number of replicas + 1) """ for param in (index, id): if param in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument.") return self.transport.perform_request( "POST", _make_path(index, doc_type, id, "_update"), params=params, body=body )
python
def update(self, index, id, doc_type="_doc", body=None, params=None): """ Update a document based on a script or partial data provided. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update.html>`_ :arg index: The name of the index :arg id: Document ID :arg body: The request definition using either `script` or partial `doc` :arg _source: True or false to return the _source field or not, or a list of fields to return :arg _source_exclude: A list of fields to exclude from the returned _source field :arg _source_include: A list of fields to extract and return from the _source field :arg fields: A comma-separated list of fields to return in the response :arg if_seq_no: :arg if_primary_term: :arg lang: The script language (default: painless) :arg parent: ID of the parent document. Is is only used for routing and when for the upsert request :arg refresh: If `true` then refresh the effected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` (the default) then do nothing with refreshes., valid choices are: 'true', 'false', 'wait_forarg retry_on_conflict: Specify how many times should the operation be retried when a conflict occurs (default: 0) :arg routing: Specific routing value :arg timeout: Explicit operation timeout :arg timestamp: Explicit timestamp for the document :arg ttl: Expiration time for the document :arg version: Explicit version number for concurrency control :arg version_type: Specific version type, valid choices are: 'internal', 'force' :arg wait_for_active_shards: Sets the number of shard copies that must be active before proceeding with the update operation. Defaults to 1, meaning the primary shard only. Set to `all` for all shard copies, otherwise set to any non-negative value less than or equal to the total number of copies for the shard (number of replicas + 1) """ for param in (index, id): if param in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument.") return self.transport.perform_request( "POST", _make_path(index, doc_type, id, "_update"), params=params, body=body )
[ "def", "update", "(", "self", ",", "index", ",", "id", ",", "doc_type", "=", "\"_doc\"", ",", "body", "=", "None", ",", "params", "=", "None", ")", ":", "for", "param", "in", "(", "index", ",", "id", ")", ":", "if", "param", "in", "SKIP_IN_PATH", ":", "raise", "ValueError", "(", "\"Empty value passed for a required argument.\"", ")", "return", "self", ".", "transport", ".", "perform_request", "(", "\"POST\"", ",", "_make_path", "(", "index", ",", "doc_type", ",", "id", ",", "\"_update\"", ")", ",", "params", "=", "params", ",", "body", "=", "body", ")" ]
Update a document based on a script or partial data provided. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update.html>`_ :arg index: The name of the index :arg id: Document ID :arg body: The request definition using either `script` or partial `doc` :arg _source: True or false to return the _source field or not, or a list of fields to return :arg _source_exclude: A list of fields to exclude from the returned _source field :arg _source_include: A list of fields to extract and return from the _source field :arg fields: A comma-separated list of fields to return in the response :arg if_seq_no: :arg if_primary_term: :arg lang: The script language (default: painless) :arg parent: ID of the parent document. Is is only used for routing and when for the upsert request :arg refresh: If `true` then refresh the effected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` (the default) then do nothing with refreshes., valid choices are: 'true', 'false', 'wait_forarg retry_on_conflict: Specify how many times should the operation be retried when a conflict occurs (default: 0) :arg routing: Specific routing value :arg timeout: Explicit operation timeout :arg timestamp: Explicit timestamp for the document :arg ttl: Expiration time for the document :arg version: Explicit version number for concurrency control :arg version_type: Specific version type, valid choices are: 'internal', 'force' :arg wait_for_active_shards: Sets the number of shard copies that must be active before proceeding with the update operation. Defaults to 1, meaning the primary shard only. Set to `all` for all shard copies, otherwise set to any non-negative value less than or equal to the total number of copies for the shard (number of replicas + 1)
[ "Update", "a", "document", "based", "on", "a", "script", "or", "partial", "data", "provided", ".", "<http", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "docs", "-", "update", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/__init__.py#L618-L662
train
elastic/elasticsearch-py
elasticsearch/client/__init__.py
Elasticsearch.search
def search(self, index=None, body=None, params=None): """ Execute a search query and get back search hits that match the query. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/search-search.html>`_ :arg index: A list of index names to search, or a string containing a comma-separated list of index names to search; use `_all` or empty string to perform the operation on all indices :arg body: The search definition using the Query DSL :arg _source: True or false to return the _source field or not, or a list of fields to return :arg _source_exclude: A list of fields to exclude from the returned _source field :arg _source_include: A list of fields to extract and return from the _source field :arg allow_no_indices: Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) :arg allow_partial_search_results: Set to false to return an overall failure if the request would produce partial results. Defaults to True, which will allow partial results in the case of timeouts or partial failures :arg analyze_wildcard: Specify whether wildcard and prefix queries should be analyzed (default: false) :arg analyzer: The analyzer to use for the query string :arg batched_reduce_size: The number of shard results that should be reduced at once on the coordinating node. This value should be used as a protection mechanism to reduce the memory overhead per search request if the potential number of shards in the request can be large., default 512 :arg default_operator: The default operator for query string query (AND or OR), default 'OR', valid choices are: 'AND', 'OR' :arg df: The field to use as default where no field prefix is given in the query string :arg docvalue_fields: A comma-separated list of fields to return as the docvalue representation of a field for each hit :arg expand_wildcards: Whether to expand wildcard expression to concrete indices that are open, closed or both., default 'open', valid choices are: 'open', 'closed', 'none', 'all' :arg explain: Specify whether to return detailed information about score computation as part of a hit :arg from\\_: Starting offset (default: 0) :arg ignore_unavailable: Whether specified concrete indices should be ignored when unavailable (missing or closed) :arg lenient: Specify whether format-based query failures (such as providing text to a numeric field) should be ignored :arg max_concurrent_shard_requests: The number of concurrent shard requests this search executes concurrently. This value should be used to limit the impact of the search on the cluster in order to limit the number of concurrent shard requests, default 'The default grows with the number of nodes in the cluster but is at most 256.' :arg pre_filter_shard_size: A threshold that enforces a pre-filter roundtrip to prefilter search shards based on query rewriting if the number of shards the search request expands to exceeds the threshold. This filter roundtrip can limit the number of shards significantly if for instance a shard can not match any documents based on it's rewrite method ie. if date filters are mandatory to match but the shard bounds and the query are disjoint., default 128 :arg preference: Specify the node or shard the operation should be performed on (default: random) :arg q: Query in the Lucene query string syntax :arg rest_total_hits_as_int: This parameter is used to restore the total hits as a number in the response. This param is added version 6.x to handle mixed cluster queries where nodes are in multiple versions (7.0 and 6.latest) :arg request_cache: Specify if request cache should be used for this request or not, defaults to index level setting :arg routing: A comma-separated list of specific routing values :arg scroll: Specify how long a consistent view of the index should be maintained for scrolled search :arg search_type: Search operation type, valid choices are: 'query_then_fetch', 'dfs_query_then_fetch' :arg size: Number of hits to return (default: 10) :arg sort: A comma-separated list of <field>:<direction> pairs :arg stats: Specific 'tag' of the request for logging and statistical purposes :arg stored_fields: A comma-separated list of stored fields to return as part of a hit :arg suggest_field: Specify which field to use for suggestions :arg suggest_mode: Specify suggest mode, default 'missing', valid choices are: 'missing', 'popular', 'always' :arg suggest_size: How many suggestions to return in response :arg suggest_text: The source text for which the suggestions should be returned :arg terminate_after: The maximum number of documents to collect for each shard, upon reaching which the query execution will terminate early. :arg timeout: Explicit operation timeout :arg track_scores: Whether to calculate and return scores even if they are not used for sorting :arg track_total_hits: Indicate if the number of documents that match the query should be tracked :arg typed_keys: Specify whether aggregation and suggester names should be prefixed by their respective types in the response :arg version: Specify whether to return document version as part of a hit """ # from is a reserved word so it cannot be used, use from_ instead if "from_" in params: params["from"] = params.pop("from_") if not index: index = "_all" return self.transport.perform_request( "GET", _make_path(index, "_search"), params=params, body=body )
python
def search(self, index=None, body=None, params=None): """ Execute a search query and get back search hits that match the query. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/search-search.html>`_ :arg index: A list of index names to search, or a string containing a comma-separated list of index names to search; use `_all` or empty string to perform the operation on all indices :arg body: The search definition using the Query DSL :arg _source: True or false to return the _source field or not, or a list of fields to return :arg _source_exclude: A list of fields to exclude from the returned _source field :arg _source_include: A list of fields to extract and return from the _source field :arg allow_no_indices: Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) :arg allow_partial_search_results: Set to false to return an overall failure if the request would produce partial results. Defaults to True, which will allow partial results in the case of timeouts or partial failures :arg analyze_wildcard: Specify whether wildcard and prefix queries should be analyzed (default: false) :arg analyzer: The analyzer to use for the query string :arg batched_reduce_size: The number of shard results that should be reduced at once on the coordinating node. This value should be used as a protection mechanism to reduce the memory overhead per search request if the potential number of shards in the request can be large., default 512 :arg default_operator: The default operator for query string query (AND or OR), default 'OR', valid choices are: 'AND', 'OR' :arg df: The field to use as default where no field prefix is given in the query string :arg docvalue_fields: A comma-separated list of fields to return as the docvalue representation of a field for each hit :arg expand_wildcards: Whether to expand wildcard expression to concrete indices that are open, closed or both., default 'open', valid choices are: 'open', 'closed', 'none', 'all' :arg explain: Specify whether to return detailed information about score computation as part of a hit :arg from\\_: Starting offset (default: 0) :arg ignore_unavailable: Whether specified concrete indices should be ignored when unavailable (missing or closed) :arg lenient: Specify whether format-based query failures (such as providing text to a numeric field) should be ignored :arg max_concurrent_shard_requests: The number of concurrent shard requests this search executes concurrently. This value should be used to limit the impact of the search on the cluster in order to limit the number of concurrent shard requests, default 'The default grows with the number of nodes in the cluster but is at most 256.' :arg pre_filter_shard_size: A threshold that enforces a pre-filter roundtrip to prefilter search shards based on query rewriting if the number of shards the search request expands to exceeds the threshold. This filter roundtrip can limit the number of shards significantly if for instance a shard can not match any documents based on it's rewrite method ie. if date filters are mandatory to match but the shard bounds and the query are disjoint., default 128 :arg preference: Specify the node or shard the operation should be performed on (default: random) :arg q: Query in the Lucene query string syntax :arg rest_total_hits_as_int: This parameter is used to restore the total hits as a number in the response. This param is added version 6.x to handle mixed cluster queries where nodes are in multiple versions (7.0 and 6.latest) :arg request_cache: Specify if request cache should be used for this request or not, defaults to index level setting :arg routing: A comma-separated list of specific routing values :arg scroll: Specify how long a consistent view of the index should be maintained for scrolled search :arg search_type: Search operation type, valid choices are: 'query_then_fetch', 'dfs_query_then_fetch' :arg size: Number of hits to return (default: 10) :arg sort: A comma-separated list of <field>:<direction> pairs :arg stats: Specific 'tag' of the request for logging and statistical purposes :arg stored_fields: A comma-separated list of stored fields to return as part of a hit :arg suggest_field: Specify which field to use for suggestions :arg suggest_mode: Specify suggest mode, default 'missing', valid choices are: 'missing', 'popular', 'always' :arg suggest_size: How many suggestions to return in response :arg suggest_text: The source text for which the suggestions should be returned :arg terminate_after: The maximum number of documents to collect for each shard, upon reaching which the query execution will terminate early. :arg timeout: Explicit operation timeout :arg track_scores: Whether to calculate and return scores even if they are not used for sorting :arg track_total_hits: Indicate if the number of documents that match the query should be tracked :arg typed_keys: Specify whether aggregation and suggester names should be prefixed by their respective types in the response :arg version: Specify whether to return document version as part of a hit """ # from is a reserved word so it cannot be used, use from_ instead if "from_" in params: params["from"] = params.pop("from_") if not index: index = "_all" return self.transport.perform_request( "GET", _make_path(index, "_search"), params=params, body=body )
[ "def", "search", "(", "self", ",", "index", "=", "None", ",", "body", "=", "None", ",", "params", "=", "None", ")", ":", "# from is a reserved word so it cannot be used, use from_ instead", "if", "\"from_\"", "in", "params", ":", "params", "[", "\"from\"", "]", "=", "params", ".", "pop", "(", "\"from_\"", ")", "if", "not", "index", ":", "index", "=", "\"_all\"", "return", "self", ".", "transport", ".", "perform_request", "(", "\"GET\"", ",", "_make_path", "(", "index", ",", "\"_search\"", ")", ",", "params", "=", "params", ",", "body", "=", "body", ")" ]
Execute a search query and get back search hits that match the query. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/search-search.html>`_ :arg index: A list of index names to search, or a string containing a comma-separated list of index names to search; use `_all` or empty string to perform the operation on all indices :arg body: The search definition using the Query DSL :arg _source: True or false to return the _source field or not, or a list of fields to return :arg _source_exclude: A list of fields to exclude from the returned _source field :arg _source_include: A list of fields to extract and return from the _source field :arg allow_no_indices: Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) :arg allow_partial_search_results: Set to false to return an overall failure if the request would produce partial results. Defaults to True, which will allow partial results in the case of timeouts or partial failures :arg analyze_wildcard: Specify whether wildcard and prefix queries should be analyzed (default: false) :arg analyzer: The analyzer to use for the query string :arg batched_reduce_size: The number of shard results that should be reduced at once on the coordinating node. This value should be used as a protection mechanism to reduce the memory overhead per search request if the potential number of shards in the request can be large., default 512 :arg default_operator: The default operator for query string query (AND or OR), default 'OR', valid choices are: 'AND', 'OR' :arg df: The field to use as default where no field prefix is given in the query string :arg docvalue_fields: A comma-separated list of fields to return as the docvalue representation of a field for each hit :arg expand_wildcards: Whether to expand wildcard expression to concrete indices that are open, closed or both., default 'open', valid choices are: 'open', 'closed', 'none', 'all' :arg explain: Specify whether to return detailed information about score computation as part of a hit :arg from\\_: Starting offset (default: 0) :arg ignore_unavailable: Whether specified concrete indices should be ignored when unavailable (missing or closed) :arg lenient: Specify whether format-based query failures (such as providing text to a numeric field) should be ignored :arg max_concurrent_shard_requests: The number of concurrent shard requests this search executes concurrently. This value should be used to limit the impact of the search on the cluster in order to limit the number of concurrent shard requests, default 'The default grows with the number of nodes in the cluster but is at most 256.' :arg pre_filter_shard_size: A threshold that enforces a pre-filter roundtrip to prefilter search shards based on query rewriting if the number of shards the search request expands to exceeds the threshold. This filter roundtrip can limit the number of shards significantly if for instance a shard can not match any documents based on it's rewrite method ie. if date filters are mandatory to match but the shard bounds and the query are disjoint., default 128 :arg preference: Specify the node or shard the operation should be performed on (default: random) :arg q: Query in the Lucene query string syntax :arg rest_total_hits_as_int: This parameter is used to restore the total hits as a number in the response. This param is added version 6.x to handle mixed cluster queries where nodes are in multiple versions (7.0 and 6.latest) :arg request_cache: Specify if request cache should be used for this request or not, defaults to index level setting :arg routing: A comma-separated list of specific routing values :arg scroll: Specify how long a consistent view of the index should be maintained for scrolled search :arg search_type: Search operation type, valid choices are: 'query_then_fetch', 'dfs_query_then_fetch' :arg size: Number of hits to return (default: 10) :arg sort: A comma-separated list of <field>:<direction> pairs :arg stats: Specific 'tag' of the request for logging and statistical purposes :arg stored_fields: A comma-separated list of stored fields to return as part of a hit :arg suggest_field: Specify which field to use for suggestions :arg suggest_mode: Specify suggest mode, default 'missing', valid choices are: 'missing', 'popular', 'always' :arg suggest_size: How many suggestions to return in response :arg suggest_text: The source text for which the suggestions should be returned :arg terminate_after: The maximum number of documents to collect for each shard, upon reaching which the query execution will terminate early. :arg timeout: Explicit operation timeout :arg track_scores: Whether to calculate and return scores even if they are not used for sorting :arg track_total_hits: Indicate if the number of documents that match the query should be tracked :arg typed_keys: Specify whether aggregation and suggester names should be prefixed by their respective types in the response :arg version: Specify whether to return document version as part of a hit
[ "Execute", "a", "search", "query", "and", "get", "back", "search", "hits", "that", "match", "the", "query", ".", "<http", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "search", "-", "search", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/__init__.py#L709-L813
train
elastic/elasticsearch-py
elasticsearch/client/__init__.py
Elasticsearch.reindex
def reindex(self, body, params=None): """ Reindex all documents from one index to another. `<https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-reindex.html>`_ :arg body: The search definition using the Query DSL and the prototype for the index request. :arg refresh: Should the effected indexes be refreshed? :arg requests_per_second: The throttle to set on this request in sub- requests per second. -1 means no throttle., default 0 :arg slices: The number of slices this task should be divided into. Defaults to 1 meaning the task isn't sliced into subtasks., default 1 :arg timeout: Time each individual bulk request should wait for shards that are unavailable., default '1m' :arg wait_for_active_shards: Sets the number of shard copies that must be active before proceeding with the reindex operation. Defaults to 1, meaning the primary shard only. Set to `all` for all shard copies, otherwise set to any non-negative value less than or equal to the total number of copies for the shard (number of replicas + 1) :arg wait_for_completion: Should the request should block until the reindex is complete., default True """ if body in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'body'.") return self.transport.perform_request( "POST", "/_reindex", params=params, body=body )
python
def reindex(self, body, params=None): """ Reindex all documents from one index to another. `<https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-reindex.html>`_ :arg body: The search definition using the Query DSL and the prototype for the index request. :arg refresh: Should the effected indexes be refreshed? :arg requests_per_second: The throttle to set on this request in sub- requests per second. -1 means no throttle., default 0 :arg slices: The number of slices this task should be divided into. Defaults to 1 meaning the task isn't sliced into subtasks., default 1 :arg timeout: Time each individual bulk request should wait for shards that are unavailable., default '1m' :arg wait_for_active_shards: Sets the number of shard copies that must be active before proceeding with the reindex operation. Defaults to 1, meaning the primary shard only. Set to `all` for all shard copies, otherwise set to any non-negative value less than or equal to the total number of copies for the shard (number of replicas + 1) :arg wait_for_completion: Should the request should block until the reindex is complete., default True """ if body in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'body'.") return self.transport.perform_request( "POST", "/_reindex", params=params, body=body )
[ "def", "reindex", "(", "self", ",", "body", ",", "params", "=", "None", ")", ":", "if", "body", "in", "SKIP_IN_PATH", ":", "raise", "ValueError", "(", "\"Empty value passed for a required argument 'body'.\"", ")", "return", "self", ".", "transport", ".", "perform_request", "(", "\"POST\"", ",", "\"/_reindex\"", ",", "params", "=", "params", ",", "body", "=", "body", ")" ]
Reindex all documents from one index to another. `<https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-reindex.html>`_ :arg body: The search definition using the Query DSL and the prototype for the index request. :arg refresh: Should the effected indexes be refreshed? :arg requests_per_second: The throttle to set on this request in sub- requests per second. -1 means no throttle., default 0 :arg slices: The number of slices this task should be divided into. Defaults to 1 meaning the task isn't sliced into subtasks., default 1 :arg timeout: Time each individual bulk request should wait for shards that are unavailable., default '1m' :arg wait_for_active_shards: Sets the number of shard copies that must be active before proceeding with the reindex operation. Defaults to 1, meaning the primary shard only. Set to `all` for all shard copies, otherwise set to any non-negative value less than or equal to the total number of copies for the shard (number of replicas + 1) :arg wait_for_completion: Should the request should block until the reindex is complete., default True
[ "Reindex", "all", "documents", "from", "one", "index", "to", "another", ".", "<https", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "docs", "-", "reindex", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/__init__.py#L946-L973
train
elastic/elasticsearch-py
elasticsearch/client/__init__.py
Elasticsearch.reindex_rethrottle
def reindex_rethrottle(self, task_id=None, params=None): """ Change the value of ``requests_per_second`` of a running ``reindex`` task. `<https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-reindex.html>`_ :arg task_id: The task id to rethrottle :arg requests_per_second: The throttle to set on this request in floating sub-requests per second. -1 means set no throttle. """ return self.transport.perform_request( "POST", _make_path("_reindex", task_id, "_rethrottle"), params=params )
python
def reindex_rethrottle(self, task_id=None, params=None): """ Change the value of ``requests_per_second`` of a running ``reindex`` task. `<https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-reindex.html>`_ :arg task_id: The task id to rethrottle :arg requests_per_second: The throttle to set on this request in floating sub-requests per second. -1 means set no throttle. """ return self.transport.perform_request( "POST", _make_path("_reindex", task_id, "_rethrottle"), params=params )
[ "def", "reindex_rethrottle", "(", "self", ",", "task_id", "=", "None", ",", "params", "=", "None", ")", ":", "return", "self", ".", "transport", ".", "perform_request", "(", "\"POST\"", ",", "_make_path", "(", "\"_reindex\"", ",", "task_id", ",", "\"_rethrottle\"", ")", ",", "params", "=", "params", ")" ]
Change the value of ``requests_per_second`` of a running ``reindex`` task. `<https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-reindex.html>`_ :arg task_id: The task id to rethrottle :arg requests_per_second: The throttle to set on this request in floating sub-requests per second. -1 means set no throttle.
[ "Change", "the", "value", "of", "requests_per_second", "of", "a", "running", "reindex", "task", ".", "<https", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "docs", "-", "reindex", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/__init__.py#L976-L987
train
elastic/elasticsearch-py
elasticsearch/client/__init__.py
Elasticsearch.search_shards
def search_shards(self, index=None, params=None): """ The search shards api returns the indices and shards that a search request would be executed against. This can give useful feedback for working out issues or planning optimizations with routing and shard preferences. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/search-shards.html>`_ :arg index: A list of index names to search, or a string containing a comma-separated list of index names to search; use `_all` or the empty string to perform the operation on all indices :arg allow_no_indices: Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) :arg expand_wildcards: Whether to expand wildcard expression to concrete indices that are open, closed or both., default 'open', valid choices are: 'open', 'closed', 'none', 'all' :arg ignore_unavailable: Whether specified concrete indices should be ignored when unavailable (missing or closed) :arg local: Return local information, do not retrieve the state from master node (default: false) :arg preference: Specify the node or shard the operation should be performed on (default: random) :arg routing: Specific routing value """ return self.transport.perform_request( "GET", _make_path(index, "_search_shards"), params=params )
python
def search_shards(self, index=None, params=None): """ The search shards api returns the indices and shards that a search request would be executed against. This can give useful feedback for working out issues or planning optimizations with routing and shard preferences. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/search-shards.html>`_ :arg index: A list of index names to search, or a string containing a comma-separated list of index names to search; use `_all` or the empty string to perform the operation on all indices :arg allow_no_indices: Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) :arg expand_wildcards: Whether to expand wildcard expression to concrete indices that are open, closed or both., default 'open', valid choices are: 'open', 'closed', 'none', 'all' :arg ignore_unavailable: Whether specified concrete indices should be ignored when unavailable (missing or closed) :arg local: Return local information, do not retrieve the state from master node (default: false) :arg preference: Specify the node or shard the operation should be performed on (default: random) :arg routing: Specific routing value """ return self.transport.perform_request( "GET", _make_path(index, "_search_shards"), params=params )
[ "def", "search_shards", "(", "self", ",", "index", "=", "None", ",", "params", "=", "None", ")", ":", "return", "self", ".", "transport", ".", "perform_request", "(", "\"GET\"", ",", "_make_path", "(", "index", ",", "\"_search_shards\"", ")", ",", "params", "=", "params", ")" ]
The search shards api returns the indices and shards that a search request would be executed against. This can give useful feedback for working out issues or planning optimizations with routing and shard preferences. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/search-shards.html>`_ :arg index: A list of index names to search, or a string containing a comma-separated list of index names to search; use `_all` or the empty string to perform the operation on all indices :arg allow_no_indices: Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) :arg expand_wildcards: Whether to expand wildcard expression to concrete indices that are open, closed or both., default 'open', valid choices are: 'open', 'closed', 'none', 'all' :arg ignore_unavailable: Whether specified concrete indices should be ignored when unavailable (missing or closed) :arg local: Return local information, do not retrieve the state from master node (default: false) :arg preference: Specify the node or shard the operation should be performed on (default: random) :arg routing: Specific routing value
[ "The", "search", "shards", "api", "returns", "the", "indices", "and", "shards", "that", "a", "search", "request", "would", "be", "executed", "against", ".", "This", "can", "give", "useful", "feedback", "for", "working", "out", "issues", "or", "planning", "optimizations", "with", "routing", "and", "shard", "preferences", ".", "<http", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "search", "-", "shards", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/__init__.py#L1115-L1141
train
elastic/elasticsearch-py
elasticsearch/client/__init__.py
Elasticsearch.search_template
def search_template(self, index=None, body=None, params=None): """ A query that accepts a query template and a map of key/value pairs to fill in template parameters. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/search-template.html>`_ :arg index: A list of index names to search, or a string containing a comma-separated list of index names to search; use `_all` or the empty string to perform the operation on all indices :arg body: The search definition template and its params :arg allow_no_indices: Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) :arg expand_wildcards: Whether to expand wildcard expression to concrete indices that are open, closed or both., default 'open', valid choices are: 'open', 'closed', 'none', 'all' :arg explain: Specify whether to return detailed information about score computation as part of a hit :arg ignore_unavailable: Whether specified concrete indices should be ignored when unavailable (missing or closed) :arg preference: Specify the node or shard the operation should be performed on (default: random) :arg profile: Specify whether to profile the query execution :arg routing: A comma-separated list of specific routing values :arg scroll: Specify how long a consistent view of the index should be maintained for scrolled search :arg search_type: Search operation type, valid choices are: 'query_then_fetch', 'query_and_fetch', 'dfs_query_then_fetch', 'dfs_query_and_fetch' :arg typed_keys: Specify whether aggregation and suggester names should be prefixed by their respective types in the response """ return self.transport.perform_request( "GET", _make_path(index, "_search", "template"), params=params, body=body )
python
def search_template(self, index=None, body=None, params=None): """ A query that accepts a query template and a map of key/value pairs to fill in template parameters. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/search-template.html>`_ :arg index: A list of index names to search, or a string containing a comma-separated list of index names to search; use `_all` or the empty string to perform the operation on all indices :arg body: The search definition template and its params :arg allow_no_indices: Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) :arg expand_wildcards: Whether to expand wildcard expression to concrete indices that are open, closed or both., default 'open', valid choices are: 'open', 'closed', 'none', 'all' :arg explain: Specify whether to return detailed information about score computation as part of a hit :arg ignore_unavailable: Whether specified concrete indices should be ignored when unavailable (missing or closed) :arg preference: Specify the node or shard the operation should be performed on (default: random) :arg profile: Specify whether to profile the query execution :arg routing: A comma-separated list of specific routing values :arg scroll: Specify how long a consistent view of the index should be maintained for scrolled search :arg search_type: Search operation type, valid choices are: 'query_then_fetch', 'query_and_fetch', 'dfs_query_then_fetch', 'dfs_query_and_fetch' :arg typed_keys: Specify whether aggregation and suggester names should be prefixed by their respective types in the response """ return self.transport.perform_request( "GET", _make_path(index, "_search", "template"), params=params, body=body )
[ "def", "search_template", "(", "self", ",", "index", "=", "None", ",", "body", "=", "None", ",", "params", "=", "None", ")", ":", "return", "self", ".", "transport", ".", "perform_request", "(", "\"GET\"", ",", "_make_path", "(", "index", ",", "\"_search\"", ",", "\"template\"", ")", ",", "params", "=", "params", ",", "body", "=", "body", ")" ]
A query that accepts a query template and a map of key/value pairs to fill in template parameters. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/search-template.html>`_ :arg index: A list of index names to search, or a string containing a comma-separated list of index names to search; use `_all` or the empty string to perform the operation on all indices :arg body: The search definition template and its params :arg allow_no_indices: Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) :arg expand_wildcards: Whether to expand wildcard expression to concrete indices that are open, closed or both., default 'open', valid choices are: 'open', 'closed', 'none', 'all' :arg explain: Specify whether to return detailed information about score computation as part of a hit :arg ignore_unavailable: Whether specified concrete indices should be ignored when unavailable (missing or closed) :arg preference: Specify the node or shard the operation should be performed on (default: random) :arg profile: Specify whether to profile the query execution :arg routing: A comma-separated list of specific routing values :arg scroll: Specify how long a consistent view of the index should be maintained for scrolled search :arg search_type: Search operation type, valid choices are: 'query_then_fetch', 'query_and_fetch', 'dfs_query_then_fetch', 'dfs_query_and_fetch' :arg typed_keys: Specify whether aggregation and suggester names should be prefixed by their respective types in the response
[ "A", "query", "that", "accepts", "a", "query", "template", "and", "a", "map", "of", "key", "/", "value", "pairs", "to", "fill", "in", "template", "parameters", ".", "<http", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "search", "-", "template", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/__init__.py#L1155-L1189
train
elastic/elasticsearch-py
elasticsearch/client/__init__.py
Elasticsearch.scroll
def scroll(self, scroll_id=None, body=None, params=None): """ Scroll a search request created by specifying the scroll parameter. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-scroll.html>`_ :arg scroll_id: The scroll ID :arg body: The scroll ID if not passed by URL or query parameter. :arg scroll: Specify how long a consistent view of the index should be maintained for scrolled search :arg rest_total_hits_as_int: This parameter is used to restore the total hits as a number in the response. This param is added version 6.x to handle mixed cluster queries where nodes are in multiple versions (7.0 and 6.latest) """ if scroll_id in SKIP_IN_PATH and body in SKIP_IN_PATH: raise ValueError("You need to supply scroll_id or body.") elif scroll_id and not body: body = {"scroll_id": scroll_id} elif scroll_id: params["scroll_id"] = scroll_id return self.transport.perform_request( "GET", "/_search/scroll", params=params, body=body )
python
def scroll(self, scroll_id=None, body=None, params=None): """ Scroll a search request created by specifying the scroll parameter. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-scroll.html>`_ :arg scroll_id: The scroll ID :arg body: The scroll ID if not passed by URL or query parameter. :arg scroll: Specify how long a consistent view of the index should be maintained for scrolled search :arg rest_total_hits_as_int: This parameter is used to restore the total hits as a number in the response. This param is added version 6.x to handle mixed cluster queries where nodes are in multiple versions (7.0 and 6.latest) """ if scroll_id in SKIP_IN_PATH and body in SKIP_IN_PATH: raise ValueError("You need to supply scroll_id or body.") elif scroll_id and not body: body = {"scroll_id": scroll_id} elif scroll_id: params["scroll_id"] = scroll_id return self.transport.perform_request( "GET", "/_search/scroll", params=params, body=body )
[ "def", "scroll", "(", "self", ",", "scroll_id", "=", "None", ",", "body", "=", "None", ",", "params", "=", "None", ")", ":", "if", "scroll_id", "in", "SKIP_IN_PATH", "and", "body", "in", "SKIP_IN_PATH", ":", "raise", "ValueError", "(", "\"You need to supply scroll_id or body.\"", ")", "elif", "scroll_id", "and", "not", "body", ":", "body", "=", "{", "\"scroll_id\"", ":", "scroll_id", "}", "elif", "scroll_id", ":", "params", "[", "\"scroll_id\"", "]", "=", "scroll_id", "return", "self", ".", "transport", ".", "perform_request", "(", "\"GET\"", ",", "\"/_search/scroll\"", ",", "params", "=", "params", ",", "body", "=", "body", ")" ]
Scroll a search request created by specifying the scroll parameter. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-scroll.html>`_ :arg scroll_id: The scroll ID :arg body: The scroll ID if not passed by URL or query parameter. :arg scroll: Specify how long a consistent view of the index should be maintained for scrolled search :arg rest_total_hits_as_int: This parameter is used to restore the total hits as a number in the response. This param is added version 6.x to handle mixed cluster queries where nodes are in multiple versions (7.0 and 6.latest)
[ "Scroll", "a", "search", "request", "created", "by", "specifying", "the", "scroll", "parameter", ".", "<http", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "search", "-", "request", "-", "scroll", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/__init__.py#L1248-L1270
train
elastic/elasticsearch-py
elasticsearch/client/__init__.py
Elasticsearch.mtermvectors
def mtermvectors(self, doc_type=None, index=None, body=None, params=None): """ Multi termvectors API allows to get multiple termvectors based on an index, type and id. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-multi-termvectors.html>`_ :arg index: The index in which the document resides. :arg body: Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation. :arg field_statistics: Specifies if document count, sum of document frequencies and sum of total term frequencies should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs"., default True :arg fields: A comma-separated list of fields to return. Applies to all returned documents unless otherwise specified in body "params" or "docs". :arg ids: A comma-separated list of documents ids. You must define ids as parameter or set "ids" or "docs" in the request body :arg offsets: Specifies if term offsets should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs"., default True :arg parent: Parent id of documents. Applies to all returned documents unless otherwise specified in body "params" or "docs". :arg payloads: Specifies if term payloads should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs"., default True :arg positions: Specifies if term positions should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs"., default True :arg preference: Specify the node or shard the operation should be performed on (default: random) .Applies to all returned documents unless otherwise specified in body "params" or "docs". :arg realtime: Specifies if requests are real-time as opposed to near- real-time (default: true). :arg routing: Specific routing value. Applies to all returned documents unless otherwise specified in body "params" or "docs". :arg term_statistics: Specifies if total term frequency and document frequency should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs"., default False :arg version: Explicit version number for concurrency control :arg version_type: Specific version type, valid choices are: 'internal', 'external', 'external_gte', 'force' """ return self.transport.perform_request( "GET", _make_path(index, doc_type, "_mtermvectors"), params=params, body=body, )
python
def mtermvectors(self, doc_type=None, index=None, body=None, params=None): """ Multi termvectors API allows to get multiple termvectors based on an index, type and id. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-multi-termvectors.html>`_ :arg index: The index in which the document resides. :arg body: Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation. :arg field_statistics: Specifies if document count, sum of document frequencies and sum of total term frequencies should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs"., default True :arg fields: A comma-separated list of fields to return. Applies to all returned documents unless otherwise specified in body "params" or "docs". :arg ids: A comma-separated list of documents ids. You must define ids as parameter or set "ids" or "docs" in the request body :arg offsets: Specifies if term offsets should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs"., default True :arg parent: Parent id of documents. Applies to all returned documents unless otherwise specified in body "params" or "docs". :arg payloads: Specifies if term payloads should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs"., default True :arg positions: Specifies if term positions should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs"., default True :arg preference: Specify the node or shard the operation should be performed on (default: random) .Applies to all returned documents unless otherwise specified in body "params" or "docs". :arg realtime: Specifies if requests are real-time as opposed to near- real-time (default: true). :arg routing: Specific routing value. Applies to all returned documents unless otherwise specified in body "params" or "docs". :arg term_statistics: Specifies if total term frequency and document frequency should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs"., default False :arg version: Explicit version number for concurrency control :arg version_type: Specific version type, valid choices are: 'internal', 'external', 'external_gte', 'force' """ return self.transport.perform_request( "GET", _make_path(index, doc_type, "_mtermvectors"), params=params, body=body, )
[ "def", "mtermvectors", "(", "self", ",", "doc_type", "=", "None", ",", "index", "=", "None", ",", "body", "=", "None", ",", "params", "=", "None", ")", ":", "return", "self", ".", "transport", ".", "perform_request", "(", "\"GET\"", ",", "_make_path", "(", "index", ",", "doc_type", ",", "\"_mtermvectors\"", ")", ",", "params", "=", "params", ",", "body", "=", "body", ",", ")" ]
Multi termvectors API allows to get multiple termvectors based on an index, type and id. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-multi-termvectors.html>`_ :arg index: The index in which the document resides. :arg body: Define ids, documents, parameters or a list of parameters per document here. You must at least provide a list of document ids. See documentation. :arg field_statistics: Specifies if document count, sum of document frequencies and sum of total term frequencies should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs"., default True :arg fields: A comma-separated list of fields to return. Applies to all returned documents unless otherwise specified in body "params" or "docs". :arg ids: A comma-separated list of documents ids. You must define ids as parameter or set "ids" or "docs" in the request body :arg offsets: Specifies if term offsets should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs"., default True :arg parent: Parent id of documents. Applies to all returned documents unless otherwise specified in body "params" or "docs". :arg payloads: Specifies if term payloads should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs"., default True :arg positions: Specifies if term positions should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs"., default True :arg preference: Specify the node or shard the operation should be performed on (default: random) .Applies to all returned documents unless otherwise specified in body "params" or "docs". :arg realtime: Specifies if requests are real-time as opposed to near- real-time (default: true). :arg routing: Specific routing value. Applies to all returned documents unless otherwise specified in body "params" or "docs". :arg term_statistics: Specifies if total term frequency and document frequency should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs"., default False :arg version: Explicit version number for concurrency control :arg version_type: Specific version type, valid choices are: 'internal', 'external', 'external_gte', 'force'
[ "Multi", "termvectors", "API", "allows", "to", "get", "multiple", "termvectors", "based", "on", "an", "index", "type", "and", "id", ".", "<http", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "docs", "-", "multi", "-", "termvectors", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/__init__.py#L1565-L1615
train
elastic/elasticsearch-py
elasticsearch/client/__init__.py
Elasticsearch.put_script
def put_script(self, id, body, context=None, params=None): """ Create a script in given language with specified ID. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting.html>`_ :arg id: Script ID :arg body: The document """ for param in (id, body): if param in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument.") return self.transport.perform_request( "PUT", _make_path("_scripts", id, context), params=params, body=body )
python
def put_script(self, id, body, context=None, params=None): """ Create a script in given language with specified ID. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting.html>`_ :arg id: Script ID :arg body: The document """ for param in (id, body): if param in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument.") return self.transport.perform_request( "PUT", _make_path("_scripts", id, context), params=params, body=body )
[ "def", "put_script", "(", "self", ",", "id", ",", "body", ",", "context", "=", "None", ",", "params", "=", "None", ")", ":", "for", "param", "in", "(", "id", ",", "body", ")", ":", "if", "param", "in", "SKIP_IN_PATH", ":", "raise", "ValueError", "(", "\"Empty value passed for a required argument.\"", ")", "return", "self", ".", "transport", ".", "perform_request", "(", "\"PUT\"", ",", "_make_path", "(", "\"_scripts\"", ",", "id", ",", "context", ")", ",", "params", "=", "params", ",", "body", "=", "body", ")" ]
Create a script in given language with specified ID. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting.html>`_ :arg id: Script ID :arg body: The document
[ "Create", "a", "script", "in", "given", "language", "with", "specified", "ID", ".", "<http", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "modules", "-", "scripting", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/__init__.py#L1618-L1631
train
elastic/elasticsearch-py
elasticsearch/client/__init__.py
Elasticsearch.render_search_template
def render_search_template(self, id=None, body=None, params=None): """ `<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-template.html>`_ :arg id: The id of the stored search template :arg body: The search definition template and its params """ return self.transport.perform_request( "GET", _make_path("_render", "template", id), params=params, body=body )
python
def render_search_template(self, id=None, body=None, params=None): """ `<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-template.html>`_ :arg id: The id of the stored search template :arg body: The search definition template and its params """ return self.transport.perform_request( "GET", _make_path("_render", "template", id), params=params, body=body )
[ "def", "render_search_template", "(", "self", ",", "id", "=", "None", ",", "body", "=", "None", ",", "params", "=", "None", ")", ":", "return", "self", ".", "transport", ".", "perform_request", "(", "\"GET\"", ",", "_make_path", "(", "\"_render\"", ",", "\"template\"", ",", "id", ")", ",", "params", "=", "params", ",", "body", "=", "body", ")" ]
`<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-template.html>`_ :arg id: The id of the stored search template :arg body: The search definition template and its params
[ "<http", ":", "//", "www", ".", "elasticsearch", ".", "org", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "search", "-", "template", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/__init__.py#L1662-L1671
train
elastic/elasticsearch-py
elasticsearch/client/__init__.py
Elasticsearch.msearch_template
def msearch_template(self, body, index=None, params=None): """ The /_search/template endpoint allows to use the mustache language to pre render search requests, before they are executed and fill existing templates with template parameters. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/search-template.html>`_ :arg body: The request definitions (metadata-search request definition pairs), separated by newlines :arg index: A list of index names, or a string containing a comma-separated list of index names, to use as the default :arg max_concurrent_searches: Controls the maximum number of concurrent searches the multi search api will execute :arg search_type: Search operation type, valid choices are: 'query_then_fetch', 'query_and_fetch', 'dfs_query_then_fetch', 'dfs_query_and_fetch' :arg typed_keys: Specify whether aggregation and suggester names should be prefixed by their respective types in the response """ if body in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'body'.") return self.transport.perform_request( "GET", _make_path(index, "_msearch", "template"), params=params, body=self._bulk_body(body), headers={"content-type": "application/x-ndjson"}, )
python
def msearch_template(self, body, index=None, params=None): """ The /_search/template endpoint allows to use the mustache language to pre render search requests, before they are executed and fill existing templates with template parameters. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/search-template.html>`_ :arg body: The request definitions (metadata-search request definition pairs), separated by newlines :arg index: A list of index names, or a string containing a comma-separated list of index names, to use as the default :arg max_concurrent_searches: Controls the maximum number of concurrent searches the multi search api will execute :arg search_type: Search operation type, valid choices are: 'query_then_fetch', 'query_and_fetch', 'dfs_query_then_fetch', 'dfs_query_and_fetch' :arg typed_keys: Specify whether aggregation and suggester names should be prefixed by their respective types in the response """ if body in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'body'.") return self.transport.perform_request( "GET", _make_path(index, "_msearch", "template"), params=params, body=self._bulk_body(body), headers={"content-type": "application/x-ndjson"}, )
[ "def", "msearch_template", "(", "self", ",", "body", ",", "index", "=", "None", ",", "params", "=", "None", ")", ":", "if", "body", "in", "SKIP_IN_PATH", ":", "raise", "ValueError", "(", "\"Empty value passed for a required argument 'body'.\"", ")", "return", "self", ".", "transport", ".", "perform_request", "(", "\"GET\"", ",", "_make_path", "(", "index", ",", "\"_msearch\"", ",", "\"template\"", ")", ",", "params", "=", "params", ",", "body", "=", "self", ".", "_bulk_body", "(", "body", ")", ",", "headers", "=", "{", "\"content-type\"", ":", "\"application/x-ndjson\"", "}", ",", ")" ]
The /_search/template endpoint allows to use the mustache language to pre render search requests, before they are executed and fill existing templates with template parameters. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/search-template.html>`_ :arg body: The request definitions (metadata-search request definition pairs), separated by newlines :arg index: A list of index names, or a string containing a comma-separated list of index names, to use as the default :arg max_concurrent_searches: Controls the maximum number of concurrent searches the multi search api will execute :arg search_type: Search operation type, valid choices are: 'query_then_fetch', 'query_and_fetch', 'dfs_query_then_fetch', 'dfs_query_and_fetch' :arg typed_keys: Specify whether aggregation and suggester names should be prefixed by their respective types in the response
[ "The", "/", "_search", "/", "template", "endpoint", "allows", "to", "use", "the", "mustache", "language", "to", "pre", "render", "search", "requests", "before", "they", "are", "executed", "and", "fill", "existing", "templates", "with", "template", "parameters", ".", "<http", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "search", "-", "template", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/__init__.py#L1674-L1701
train
elastic/elasticsearch-py
elasticsearch/client/__init__.py
Elasticsearch.field_caps
def field_caps(self, index=None, body=None, params=None): """ The field capabilities API allows to retrieve the capabilities of fields among multiple indices. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/search-field-caps.html>`_ :arg index: A list of index names, or a string containing a comma-separated list of index names; use `_all` or the empty string to perform the operation on all indices :arg body: Field json objects containing an array of field names :arg allow_no_indices: Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) :arg expand_wildcards: Whether to expand wildcard expression to concrete indices that are open, closed or both., default 'open', valid choices are: 'open', 'closed', 'none', 'all' :arg fields: A comma-separated list of field names :arg ignore_unavailable: Whether specified concrete indices should be ignored when unavailable (missing or closed) """ return self.transport.perform_request( "GET", _make_path(index, "_field_caps"), params=params, body=body )
python
def field_caps(self, index=None, body=None, params=None): """ The field capabilities API allows to retrieve the capabilities of fields among multiple indices. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/search-field-caps.html>`_ :arg index: A list of index names, or a string containing a comma-separated list of index names; use `_all` or the empty string to perform the operation on all indices :arg body: Field json objects containing an array of field names :arg allow_no_indices: Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) :arg expand_wildcards: Whether to expand wildcard expression to concrete indices that are open, closed or both., default 'open', valid choices are: 'open', 'closed', 'none', 'all' :arg fields: A comma-separated list of field names :arg ignore_unavailable: Whether specified concrete indices should be ignored when unavailable (missing or closed) """ return self.transport.perform_request( "GET", _make_path(index, "_field_caps"), params=params, body=body )
[ "def", "field_caps", "(", "self", ",", "index", "=", "None", ",", "body", "=", "None", ",", "params", "=", "None", ")", ":", "return", "self", ".", "transport", ".", "perform_request", "(", "\"GET\"", ",", "_make_path", "(", "index", ",", "\"_field_caps\"", ")", ",", "params", "=", "params", ",", "body", "=", "body", ")" ]
The field capabilities API allows to retrieve the capabilities of fields among multiple indices. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/search-field-caps.html>`_ :arg index: A list of index names, or a string containing a comma-separated list of index names; use `_all` or the empty string to perform the operation on all indices :arg body: Field json objects containing an array of field names :arg allow_no_indices: Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) :arg expand_wildcards: Whether to expand wildcard expression to concrete indices that are open, closed or both., default 'open', valid choices are: 'open', 'closed', 'none', 'all' :arg fields: A comma-separated list of field names :arg ignore_unavailable: Whether specified concrete indices should be ignored when unavailable (missing or closed)
[ "The", "field", "capabilities", "API", "allows", "to", "retrieve", "the", "capabilities", "of", "fields", "among", "multiple", "indices", ".", "<http", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "search", "-", "field", "-", "caps", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/__init__.py#L1706-L1727
train
elastic/elasticsearch-py
elasticsearch/client/xpack/monitoring.py
MonitoringClient.bulk
def bulk(self, body, doc_type=None, params=None): """ `<http://www.elastic.co/guide/en/monitoring/current/appendix-api-bulk.html>`_ :arg body: The operation definition and data (action-data pairs), separated by newlines :arg doc_type: Default document type for items which don't provide one :arg interval: Collection interval (e.g., '10s' or '10000ms') of the payload :arg system_api_version: API Version of the monitored system :arg system_id: Identifier of the monitored system """ if body in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'body'.") return self.transport.perform_request( "POST", _make_path("_monitoring", doc_type, "bulk"), params=params, body=self._bulk_body(body), )
python
def bulk(self, body, doc_type=None, params=None): """ `<http://www.elastic.co/guide/en/monitoring/current/appendix-api-bulk.html>`_ :arg body: The operation definition and data (action-data pairs), separated by newlines :arg doc_type: Default document type for items which don't provide one :arg interval: Collection interval (e.g., '10s' or '10000ms') of the payload :arg system_api_version: API Version of the monitored system :arg system_id: Identifier of the monitored system """ if body in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'body'.") return self.transport.perform_request( "POST", _make_path("_monitoring", doc_type, "bulk"), params=params, body=self._bulk_body(body), )
[ "def", "bulk", "(", "self", ",", "body", ",", "doc_type", "=", "None", ",", "params", "=", "None", ")", ":", "if", "body", "in", "SKIP_IN_PATH", ":", "raise", "ValueError", "(", "\"Empty value passed for a required argument 'body'.\"", ")", "return", "self", ".", "transport", ".", "perform_request", "(", "\"POST\"", ",", "_make_path", "(", "\"_monitoring\"", ",", "doc_type", ",", "\"bulk\"", ")", ",", "params", "=", "params", ",", "body", "=", "self", ".", "_bulk_body", "(", "body", ")", ",", ")" ]
`<http://www.elastic.co/guide/en/monitoring/current/appendix-api-bulk.html>`_ :arg body: The operation definition and data (action-data pairs), separated by newlines :arg doc_type: Default document type for items which don't provide one :arg interval: Collection interval (e.g., '10s' or '10000ms') of the payload :arg system_api_version: API Version of the monitored system :arg system_id: Identifier of the monitored system
[ "<http", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "monitoring", "/", "current", "/", "appendix", "-", "api", "-", "bulk", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/xpack/monitoring.py#L6-L25
train
elastic/elasticsearch-py
elasticsearch/transport.py
Transport.add_connection
def add_connection(self, host): """ Create a new :class:`~elasticsearch.Connection` instance and add it to the pool. :arg host: kwargs that will be used to create the instance """ self.hosts.append(host) self.set_connections(self.hosts)
python
def add_connection(self, host): """ Create a new :class:`~elasticsearch.Connection` instance and add it to the pool. :arg host: kwargs that will be used to create the instance """ self.hosts.append(host) self.set_connections(self.hosts)
[ "def", "add_connection", "(", "self", ",", "host", ")", ":", "self", ".", "hosts", ".", "append", "(", "host", ")", "self", ".", "set_connections", "(", "self", ".", "hosts", ")" ]
Create a new :class:`~elasticsearch.Connection` instance and add it to the pool. :arg host: kwargs that will be used to create the instance
[ "Create", "a", "new", ":", "class", ":", "~elasticsearch", ".", "Connection", "instance", "and", "add", "it", "to", "the", "pool", "." ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/transport.py#L124-L131
train
elastic/elasticsearch-py
elasticsearch/transport.py
Transport.get_connection
def get_connection(self): """ Retreive a :class:`~elasticsearch.Connection` instance from the :class:`~elasticsearch.ConnectionPool` instance. """ if self.sniffer_timeout: if time.time() >= self.last_sniff + self.sniffer_timeout: self.sniff_hosts() return self.connection_pool.get_connection()
python
def get_connection(self): """ Retreive a :class:`~elasticsearch.Connection` instance from the :class:`~elasticsearch.ConnectionPool` instance. """ if self.sniffer_timeout: if time.time() >= self.last_sniff + self.sniffer_timeout: self.sniff_hosts() return self.connection_pool.get_connection()
[ "def", "get_connection", "(", "self", ")", ":", "if", "self", ".", "sniffer_timeout", ":", "if", "time", ".", "time", "(", ")", ">=", "self", ".", "last_sniff", "+", "self", ".", "sniffer_timeout", ":", "self", ".", "sniff_hosts", "(", ")", "return", "self", ".", "connection_pool", ".", "get_connection", "(", ")" ]
Retreive a :class:`~elasticsearch.Connection` instance from the :class:`~elasticsearch.ConnectionPool` instance.
[ "Retreive", "a", ":", "class", ":", "~elasticsearch", ".", "Connection", "instance", "from", "the", ":", "class", ":", "~elasticsearch", ".", "ConnectionPool", "instance", "." ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/transport.py#L164-L172
train
elastic/elasticsearch-py
elasticsearch/transport.py
Transport.sniff_hosts
def sniff_hosts(self, initial=False): """ Obtain a list of nodes from the cluster and create a new connection pool using the information retrieved. To extract the node connection parameters use the ``nodes_to_host_callback``. :arg initial: flag indicating if this is during startup (``sniff_on_start``), ignore the ``sniff_timeout`` if ``True`` """ node_info = self._get_sniff_data(initial) hosts = list(filter(None, (self._get_host_info(n) for n in node_info))) # we weren't able to get any nodes or host_info_callback blocked all - # raise error. if not hosts: raise TransportError("N/A", "Unable to sniff hosts - no viable hosts found.") self.set_connections(hosts)
python
def sniff_hosts(self, initial=False): """ Obtain a list of nodes from the cluster and create a new connection pool using the information retrieved. To extract the node connection parameters use the ``nodes_to_host_callback``. :arg initial: flag indicating if this is during startup (``sniff_on_start``), ignore the ``sniff_timeout`` if ``True`` """ node_info = self._get_sniff_data(initial) hosts = list(filter(None, (self._get_host_info(n) for n in node_info))) # we weren't able to get any nodes or host_info_callback blocked all - # raise error. if not hosts: raise TransportError("N/A", "Unable to sniff hosts - no viable hosts found.") self.set_connections(hosts)
[ "def", "sniff_hosts", "(", "self", ",", "initial", "=", "False", ")", ":", "node_info", "=", "self", ".", "_get_sniff_data", "(", "initial", ")", "hosts", "=", "list", "(", "filter", "(", "None", ",", "(", "self", ".", "_get_host_info", "(", "n", ")", "for", "n", "in", "node_info", ")", ")", ")", "# we weren't able to get any nodes or host_info_callback blocked all -", "# raise error.", "if", "not", "hosts", ":", "raise", "TransportError", "(", "\"N/A\"", ",", "\"Unable to sniff hosts - no viable hosts found.\"", ")", "self", ".", "set_connections", "(", "hosts", ")" ]
Obtain a list of nodes from the cluster and create a new connection pool using the information retrieved. To extract the node connection parameters use the ``nodes_to_host_callback``. :arg initial: flag indicating if this is during startup (``sniff_on_start``), ignore the ``sniff_timeout`` if ``True``
[ "Obtain", "a", "list", "of", "nodes", "from", "the", "cluster", "and", "create", "a", "new", "connection", "pool", "using", "the", "information", "retrieved", "." ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/transport.py#L225-L244
train
elastic/elasticsearch-py
elasticsearch/transport.py
Transport.mark_dead
def mark_dead(self, connection): """ Mark a connection as dead (failed) in the connection pool. If sniffing on failure is enabled this will initiate the sniffing process. :arg connection: instance of :class:`~elasticsearch.Connection` that failed """ # mark as dead even when sniffing to avoid hitting this host during the sniff process self.connection_pool.mark_dead(connection) if self.sniff_on_connection_fail: self.sniff_hosts()
python
def mark_dead(self, connection): """ Mark a connection as dead (failed) in the connection pool. If sniffing on failure is enabled this will initiate the sniffing process. :arg connection: instance of :class:`~elasticsearch.Connection` that failed """ # mark as dead even when sniffing to avoid hitting this host during the sniff process self.connection_pool.mark_dead(connection) if self.sniff_on_connection_fail: self.sniff_hosts()
[ "def", "mark_dead", "(", "self", ",", "connection", ")", ":", "# mark as dead even when sniffing to avoid hitting this host during the sniff process", "self", ".", "connection_pool", ".", "mark_dead", "(", "connection", ")", "if", "self", ".", "sniff_on_connection_fail", ":", "self", ".", "sniff_hosts", "(", ")" ]
Mark a connection as dead (failed) in the connection pool. If sniffing on failure is enabled this will initiate the sniffing process. :arg connection: instance of :class:`~elasticsearch.Connection` that failed
[ "Mark", "a", "connection", "as", "dead", "(", "failed", ")", "in", "the", "connection", "pool", ".", "If", "sniffing", "on", "failure", "is", "enabled", "this", "will", "initiate", "the", "sniffing", "process", "." ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/transport.py#L246-L256
train
elastic/elasticsearch-py
elasticsearch/transport.py
Transport.perform_request
def perform_request(self, method, url, headers=None, params=None, body=None): """ Perform the actual request. Retrieve a connection from the connection pool, pass all the information to it's perform_request method and return the data. If an exception was raised, mark the connection as failed and retry (up to `max_retries` times). If the operation was succesful and the connection used was previously marked as dead, mark it as live, resetting it's failure count. :arg method: HTTP method to use :arg url: absolute url (without host) to target :arg headers: dictionary of headers, will be handed over to the underlying :class:`~elasticsearch.Connection` class :arg params: dictionary of query parameters, will be handed over to the underlying :class:`~elasticsearch.Connection` class for serialization :arg body: body of the request, will be serializes using serializer and passed to the connection """ if body is not None: body = self.serializer.dumps(body) # some clients or environments don't support sending GET with body if method in ('HEAD', 'GET') and self.send_get_body_as != 'GET': # send it as post instead if self.send_get_body_as == 'POST': method = 'POST' # or as source parameter elif self.send_get_body_as == 'source': if params is None: params = {} params['source'] = body body = None if body is not None: try: body = body.encode('utf-8', 'surrogatepass') except (UnicodeDecodeError, AttributeError): # bytes/str - no need to re-encode pass ignore = () timeout = None if params: timeout = params.pop('request_timeout', None) ignore = params.pop('ignore', ()) if isinstance(ignore, int): ignore = (ignore, ) for attempt in range(self.max_retries + 1): connection = self.get_connection() try: # add a delay before attempting the next retry # 0, 1, 3, 7, etc... delay = 2**attempt - 1 time.sleep(delay) status, headers_response, data = connection.perform_request(method, url, params, body, headers=headers, ignore=ignore, timeout=timeout) except TransportError as e: if method == 'HEAD' and e.status_code == 404: return False retry = False if isinstance(e, ConnectionTimeout): retry = self.retry_on_timeout elif isinstance(e, ConnectionError): retry = True elif e.status_code in self.retry_on_status: retry = True if retry: # only mark as dead if we are retrying self.mark_dead(connection) # raise exception on last retry if attempt == self.max_retries: raise else: raise else: # connection didn't fail, confirm it's live status self.connection_pool.mark_live(connection) if method == 'HEAD': return 200 <= status < 300 if data: data = self.deserializer.loads(data, headers_response.get('content-type')) return data
python
def perform_request(self, method, url, headers=None, params=None, body=None): """ Perform the actual request. Retrieve a connection from the connection pool, pass all the information to it's perform_request method and return the data. If an exception was raised, mark the connection as failed and retry (up to `max_retries` times). If the operation was succesful and the connection used was previously marked as dead, mark it as live, resetting it's failure count. :arg method: HTTP method to use :arg url: absolute url (without host) to target :arg headers: dictionary of headers, will be handed over to the underlying :class:`~elasticsearch.Connection` class :arg params: dictionary of query parameters, will be handed over to the underlying :class:`~elasticsearch.Connection` class for serialization :arg body: body of the request, will be serializes using serializer and passed to the connection """ if body is not None: body = self.serializer.dumps(body) # some clients or environments don't support sending GET with body if method in ('HEAD', 'GET') and self.send_get_body_as != 'GET': # send it as post instead if self.send_get_body_as == 'POST': method = 'POST' # or as source parameter elif self.send_get_body_as == 'source': if params is None: params = {} params['source'] = body body = None if body is not None: try: body = body.encode('utf-8', 'surrogatepass') except (UnicodeDecodeError, AttributeError): # bytes/str - no need to re-encode pass ignore = () timeout = None if params: timeout = params.pop('request_timeout', None) ignore = params.pop('ignore', ()) if isinstance(ignore, int): ignore = (ignore, ) for attempt in range(self.max_retries + 1): connection = self.get_connection() try: # add a delay before attempting the next retry # 0, 1, 3, 7, etc... delay = 2**attempt - 1 time.sleep(delay) status, headers_response, data = connection.perform_request(method, url, params, body, headers=headers, ignore=ignore, timeout=timeout) except TransportError as e: if method == 'HEAD' and e.status_code == 404: return False retry = False if isinstance(e, ConnectionTimeout): retry = self.retry_on_timeout elif isinstance(e, ConnectionError): retry = True elif e.status_code in self.retry_on_status: retry = True if retry: # only mark as dead if we are retrying self.mark_dead(connection) # raise exception on last retry if attempt == self.max_retries: raise else: raise else: # connection didn't fail, confirm it's live status self.connection_pool.mark_live(connection) if method == 'HEAD': return 200 <= status < 300 if data: data = self.deserializer.loads(data, headers_response.get('content-type')) return data
[ "def", "perform_request", "(", "self", ",", "method", ",", "url", ",", "headers", "=", "None", ",", "params", "=", "None", ",", "body", "=", "None", ")", ":", "if", "body", "is", "not", "None", ":", "body", "=", "self", ".", "serializer", ".", "dumps", "(", "body", ")", "# some clients or environments don't support sending GET with body", "if", "method", "in", "(", "'HEAD'", ",", "'GET'", ")", "and", "self", ".", "send_get_body_as", "!=", "'GET'", ":", "# send it as post instead", "if", "self", ".", "send_get_body_as", "==", "'POST'", ":", "method", "=", "'POST'", "# or as source parameter", "elif", "self", ".", "send_get_body_as", "==", "'source'", ":", "if", "params", "is", "None", ":", "params", "=", "{", "}", "params", "[", "'source'", "]", "=", "body", "body", "=", "None", "if", "body", "is", "not", "None", ":", "try", ":", "body", "=", "body", ".", "encode", "(", "'utf-8'", ",", "'surrogatepass'", ")", "except", "(", "UnicodeDecodeError", ",", "AttributeError", ")", ":", "# bytes/str - no need to re-encode", "pass", "ignore", "=", "(", ")", "timeout", "=", "None", "if", "params", ":", "timeout", "=", "params", ".", "pop", "(", "'request_timeout'", ",", "None", ")", "ignore", "=", "params", ".", "pop", "(", "'ignore'", ",", "(", ")", ")", "if", "isinstance", "(", "ignore", ",", "int", ")", ":", "ignore", "=", "(", "ignore", ",", ")", "for", "attempt", "in", "range", "(", "self", ".", "max_retries", "+", "1", ")", ":", "connection", "=", "self", ".", "get_connection", "(", ")", "try", ":", "# add a delay before attempting the next retry", "# 0, 1, 3, 7, etc...", "delay", "=", "2", "**", "attempt", "-", "1", "time", ".", "sleep", "(", "delay", ")", "status", ",", "headers_response", ",", "data", "=", "connection", ".", "perform_request", "(", "method", ",", "url", ",", "params", ",", "body", ",", "headers", "=", "headers", ",", "ignore", "=", "ignore", ",", "timeout", "=", "timeout", ")", "except", "TransportError", "as", "e", ":", "if", "method", "==", "'HEAD'", "and", "e", ".", "status_code", "==", "404", ":", "return", "False", "retry", "=", "False", "if", "isinstance", "(", "e", ",", "ConnectionTimeout", ")", ":", "retry", "=", "self", ".", "retry_on_timeout", "elif", "isinstance", "(", "e", ",", "ConnectionError", ")", ":", "retry", "=", "True", "elif", "e", ".", "status_code", "in", "self", ".", "retry_on_status", ":", "retry", "=", "True", "if", "retry", ":", "# only mark as dead if we are retrying", "self", ".", "mark_dead", "(", "connection", ")", "# raise exception on last retry", "if", "attempt", "==", "self", ".", "max_retries", ":", "raise", "else", ":", "raise", "else", ":", "# connection didn't fail, confirm it's live status", "self", ".", "connection_pool", ".", "mark_live", "(", "connection", ")", "if", "method", "==", "'HEAD'", ":", "return", "200", "<=", "status", "<", "300", "if", "data", ":", "data", "=", "self", ".", "deserializer", ".", "loads", "(", "data", ",", "headers_response", ".", "get", "(", "'content-type'", ")", ")", "return", "data" ]
Perform the actual request. Retrieve a connection from the connection pool, pass all the information to it's perform_request method and return the data. If an exception was raised, mark the connection as failed and retry (up to `max_retries` times). If the operation was succesful and the connection used was previously marked as dead, mark it as live, resetting it's failure count. :arg method: HTTP method to use :arg url: absolute url (without host) to target :arg headers: dictionary of headers, will be handed over to the underlying :class:`~elasticsearch.Connection` class :arg params: dictionary of query parameters, will be handed over to the underlying :class:`~elasticsearch.Connection` class for serialization :arg body: body of the request, will be serializes using serializer and passed to the connection
[ "Perform", "the", "actual", "request", ".", "Retrieve", "a", "connection", "from", "the", "connection", "pool", "pass", "all", "the", "information", "to", "it", "s", "perform_request", "method", "and", "return", "the", "data", "." ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/transport.py#L258-L350
train
elastic/elasticsearch-py
elasticsearch/client/xpack/security.py
SecurityClient.change_password
def change_password(self, body, username=None, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-change-password.html>`_ :arg body: the new password for the user :arg username: The username of the user to change the password for :arg refresh: If `true` (the default) then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` then do nothing with refreshes., valid choices are: 'true', 'false', 'wait_for' """ if body in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'body'.") return self.transport.perform_request( "PUT", _make_path("_security", "user", username, "_password"), params=params, body=body, )
python
def change_password(self, body, username=None, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-change-password.html>`_ :arg body: the new password for the user :arg username: The username of the user to change the password for :arg refresh: If `true` (the default) then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` then do nothing with refreshes., valid choices are: 'true', 'false', 'wait_for' """ if body in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'body'.") return self.transport.perform_request( "PUT", _make_path("_security", "user", username, "_password"), params=params, body=body, )
[ "def", "change_password", "(", "self", ",", "body", ",", "username", "=", "None", ",", "params", "=", "None", ")", ":", "if", "body", "in", "SKIP_IN_PATH", ":", "raise", "ValueError", "(", "\"Empty value passed for a required argument 'body'.\"", ")", "return", "self", ".", "transport", ".", "perform_request", "(", "\"PUT\"", ",", "_make_path", "(", "\"_security\"", ",", "\"user\"", ",", "username", ",", "\"_password\"", ")", ",", "params", "=", "params", ",", "body", "=", "body", ",", ")" ]
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-change-password.html>`_ :arg body: the new password for the user :arg username: The username of the user to change the password for :arg refresh: If `true` (the default) then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` then do nothing with refreshes., valid choices are: 'true', 'false', 'wait_for'
[ "<https", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "security", "-", "api", "-", "change", "-", "password", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/xpack/security.py#L15-L34
train
elastic/elasticsearch-py
elasticsearch/client/xpack/security.py
SecurityClient.clear_cached_realms
def clear_cached_realms(self, realms, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-clear-cache.html>`_ :arg realms: Comma-separated list of realms to clear :arg usernames: Comma-separated list of usernames to clear from the cache """ if realms in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'realms'.") return self.transport.perform_request( "POST", _make_path("_security", "realm", realms, "_clear_cache"), params=params, )
python
def clear_cached_realms(self, realms, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-clear-cache.html>`_ :arg realms: Comma-separated list of realms to clear :arg usernames: Comma-separated list of usernames to clear from the cache """ if realms in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'realms'.") return self.transport.perform_request( "POST", _make_path("_security", "realm", realms, "_clear_cache"), params=params, )
[ "def", "clear_cached_realms", "(", "self", ",", "realms", ",", "params", "=", "None", ")", ":", "if", "realms", "in", "SKIP_IN_PATH", ":", "raise", "ValueError", "(", "\"Empty value passed for a required argument 'realms'.\"", ")", "return", "self", ".", "transport", ".", "perform_request", "(", "\"POST\"", ",", "_make_path", "(", "\"_security\"", ",", "\"realm\"", ",", "realms", ",", "\"_clear_cache\"", ")", ",", "params", "=", "params", ",", ")" ]
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-clear-cache.html>`_ :arg realms: Comma-separated list of realms to clear :arg usernames: Comma-separated list of usernames to clear from the cache
[ "<https", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "security", "-", "api", "-", "clear", "-", "cache", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/xpack/security.py#L37-L51
train
elastic/elasticsearch-py
elasticsearch/client/xpack/security.py
SecurityClient.clear_cached_roles
def clear_cached_roles(self, name, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-clear-role-cache.html>`_ :arg name: Role name """ if name in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'name'.") return self.transport.perform_request( "POST", _make_path("_security", "role", name, "_clear_cache"), params=params )
python
def clear_cached_roles(self, name, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-clear-role-cache.html>`_ :arg name: Role name """ if name in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'name'.") return self.transport.perform_request( "POST", _make_path("_security", "role", name, "_clear_cache"), params=params )
[ "def", "clear_cached_roles", "(", "self", ",", "name", ",", "params", "=", "None", ")", ":", "if", "name", "in", "SKIP_IN_PATH", ":", "raise", "ValueError", "(", "\"Empty value passed for a required argument 'name'.\"", ")", "return", "self", ".", "transport", ".", "perform_request", "(", "\"POST\"", ",", "_make_path", "(", "\"_security\"", ",", "\"role\"", ",", "name", ",", "\"_clear_cache\"", ")", ",", "params", "=", "params", ")" ]
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-clear-role-cache.html>`_ :arg name: Role name
[ "<https", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "security", "-", "api", "-", "clear", "-", "role", "-", "cache", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/xpack/security.py#L54-L64
train
elastic/elasticsearch-py
elasticsearch/client/xpack/security.py
SecurityClient.create_api_key
def create_api_key(self, body, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-create-api-key.html>`_ :arg body: The api key request to create an API key :arg refresh: If `true` (the default) then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` then do nothing with refreshes., valid choices are: 'true', 'false', 'wait_for' """ if body in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'body'.") return self.transport.perform_request( "PUT", "/_security/api_key", params=params, body=body )
python
def create_api_key(self, body, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-create-api-key.html>`_ :arg body: The api key request to create an API key :arg refresh: If `true` (the default) then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` then do nothing with refreshes., valid choices are: 'true', 'false', 'wait_for' """ if body in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'body'.") return self.transport.perform_request( "PUT", "/_security/api_key", params=params, body=body )
[ "def", "create_api_key", "(", "self", ",", "body", ",", "params", "=", "None", ")", ":", "if", "body", "in", "SKIP_IN_PATH", ":", "raise", "ValueError", "(", "\"Empty value passed for a required argument 'body'.\"", ")", "return", "self", ".", "transport", ".", "perform_request", "(", "\"PUT\"", ",", "\"/_security/api_key\"", ",", "params", "=", "params", ",", "body", "=", "body", ")" ]
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-create-api-key.html>`_ :arg body: The api key request to create an API key :arg refresh: If `true` (the default) then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` then do nothing with refreshes., valid choices are: 'true', 'false', 'wait_for'
[ "<https", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "security", "-", "api", "-", "create", "-", "api", "-", "key", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/xpack/security.py#L67-L82
train
elastic/elasticsearch-py
elasticsearch/client/xpack/security.py
SecurityClient.delete_privileges
def delete_privileges(self, application, name, params=None): """ `<TODO>`_ :arg application: Application name :arg name: Privilege name :arg refresh: If `true` (the default) then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` then do nothing with refreshes., valid choices are: 'true', 'false', 'wait_for' """ for param in (application, name): if param in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument.") return self.transport.perform_request( "DELETE", _make_path("_security", "privilege", application, name), params=params, )
python
def delete_privileges(self, application, name, params=None): """ `<TODO>`_ :arg application: Application name :arg name: Privilege name :arg refresh: If `true` (the default) then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` then do nothing with refreshes., valid choices are: 'true', 'false', 'wait_for' """ for param in (application, name): if param in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument.") return self.transport.perform_request( "DELETE", _make_path("_security", "privilege", application, name), params=params, )
[ "def", "delete_privileges", "(", "self", ",", "application", ",", "name", ",", "params", "=", "None", ")", ":", "for", "param", "in", "(", "application", ",", "name", ")", ":", "if", "param", "in", "SKIP_IN_PATH", ":", "raise", "ValueError", "(", "\"Empty value passed for a required argument.\"", ")", "return", "self", ".", "transport", ".", "perform_request", "(", "\"DELETE\"", ",", "_make_path", "(", "\"_security\"", ",", "\"privilege\"", ",", "application", ",", "name", ")", ",", "params", "=", "params", ",", ")" ]
`<TODO>`_ :arg application: Application name :arg name: Privilege name :arg refresh: If `true` (the default) then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` then do nothing with refreshes., valid choices are: 'true', 'false', 'wait_for'
[ "<TODO", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/xpack/security.py#L85-L104
train
elastic/elasticsearch-py
elasticsearch/client/xpack/security.py
SecurityClient.delete_user
def delete_user(self, username, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-delete-user.html>`_ :arg username: username :arg refresh: If `true` (the default) then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` then do nothing with refreshes., valid choices are: 'true', 'false', 'wait_for' """ if username in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'username'.") return self.transport.perform_request( "DELETE", _make_path("_security", "user", username), params=params )
python
def delete_user(self, username, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-delete-user.html>`_ :arg username: username :arg refresh: If `true` (the default) then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` then do nothing with refreshes., valid choices are: 'true', 'false', 'wait_for' """ if username in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'username'.") return self.transport.perform_request( "DELETE", _make_path("_security", "user", username), params=params )
[ "def", "delete_user", "(", "self", ",", "username", ",", "params", "=", "None", ")", ":", "if", "username", "in", "SKIP_IN_PATH", ":", "raise", "ValueError", "(", "\"Empty value passed for a required argument 'username'.\"", ")", "return", "self", ".", "transport", ".", "perform_request", "(", "\"DELETE\"", ",", "_make_path", "(", "\"_security\"", ",", "\"user\"", ",", "username", ")", ",", "params", "=", "params", ")" ]
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-delete-user.html>`_ :arg username: username :arg refresh: If `true` (the default) then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` then do nothing with refreshes., valid choices are: 'true', 'false', 'wait_for'
[ "<https", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "security", "-", "api", "-", "delete", "-", "user", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/xpack/security.py#L143-L158
train
elastic/elasticsearch-py
elasticsearch/client/xpack/security.py
SecurityClient.get_privileges
def get_privileges(self, application=None, name=None, params=None): """ `<TODO>`_ :arg application: Application name :arg name: Privilege name """ return self.transport.perform_request( "GET", _make_path("_security", "privilege", application, name), params=params, )
python
def get_privileges(self, application=None, name=None, params=None): """ `<TODO>`_ :arg application: Application name :arg name: Privilege name """ return self.transport.perform_request( "GET", _make_path("_security", "privilege", application, name), params=params, )
[ "def", "get_privileges", "(", "self", ",", "application", "=", "None", ",", "name", "=", "None", ",", "params", "=", "None", ")", ":", "return", "self", ".", "transport", ".", "perform_request", "(", "\"GET\"", ",", "_make_path", "(", "\"_security\"", ",", "\"privilege\"", ",", "application", ",", "name", ")", ",", "params", "=", "params", ",", ")" ]
`<TODO>`_ :arg application: Application name :arg name: Privilege name
[ "<TODO", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/xpack/security.py#L213-L224
train
elastic/elasticsearch-py
elasticsearch/client/xpack/security.py
SecurityClient.get_role
def get_role(self, name=None, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-get-role.html>`_ :arg name: Role name """ return self.transport.perform_request( "GET", _make_path("_security", "role", name), params=params )
python
def get_role(self, name=None, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-get-role.html>`_ :arg name: Role name """ return self.transport.perform_request( "GET", _make_path("_security", "role", name), params=params )
[ "def", "get_role", "(", "self", ",", "name", "=", "None", ",", "params", "=", "None", ")", ":", "return", "self", ".", "transport", ".", "perform_request", "(", "\"GET\"", ",", "_make_path", "(", "\"_security\"", ",", "\"role\"", ",", "name", ")", ",", "params", "=", "params", ")" ]
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-get-role.html>`_ :arg name: Role name
[ "<https", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "security", "-", "api", "-", "get", "-", "role", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/xpack/security.py#L227-L235
train
elastic/elasticsearch-py
elasticsearch/client/xpack/security.py
SecurityClient.get_role_mapping
def get_role_mapping(self, name=None, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-get-role-mapping.html>`_ :arg name: Role-Mapping name """ return self.transport.perform_request( "GET", _make_path("_security", "role_mapping", name), params=params )
python
def get_role_mapping(self, name=None, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-get-role-mapping.html>`_ :arg name: Role-Mapping name """ return self.transport.perform_request( "GET", _make_path("_security", "role_mapping", name), params=params )
[ "def", "get_role_mapping", "(", "self", ",", "name", "=", "None", ",", "params", "=", "None", ")", ":", "return", "self", ".", "transport", ".", "perform_request", "(", "\"GET\"", ",", "_make_path", "(", "\"_security\"", ",", "\"role_mapping\"", ",", "name", ")", ",", "params", "=", "params", ")" ]
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-get-role-mapping.html>`_ :arg name: Role-Mapping name
[ "<https", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "security", "-", "api", "-", "get", "-", "role", "-", "mapping", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/xpack/security.py#L238-L246
train
elastic/elasticsearch-py
elasticsearch/client/xpack/security.py
SecurityClient.get_token
def get_token(self, body, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-get-token.html>`_ :arg body: The token request to get """ if body in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'body'.") return self.transport.perform_request( "POST", "/_security/oauth2/token", params=params, body=body )
python
def get_token(self, body, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-get-token.html>`_ :arg body: The token request to get """ if body in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'body'.") return self.transport.perform_request( "POST", "/_security/oauth2/token", params=params, body=body )
[ "def", "get_token", "(", "self", ",", "body", ",", "params", "=", "None", ")", ":", "if", "body", "in", "SKIP_IN_PATH", ":", "raise", "ValueError", "(", "\"Empty value passed for a required argument 'body'.\"", ")", "return", "self", ".", "transport", ".", "perform_request", "(", "\"POST\"", ",", "\"/_security/oauth2/token\"", ",", "params", "=", "params", ",", "body", "=", "body", ")" ]
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-get-token.html>`_ :arg body: The token request to get
[ "<https", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "security", "-", "api", "-", "get", "-", "token", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/xpack/security.py#L249-L259
train
elastic/elasticsearch-py
elasticsearch/client/xpack/security.py
SecurityClient.get_user
def get_user(self, username=None, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-get-user.html>`_ :arg username: A comma-separated list of usernames """ return self.transport.perform_request( "GET", _make_path("_security", "user", username), params=params )
python
def get_user(self, username=None, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-get-user.html>`_ :arg username: A comma-separated list of usernames """ return self.transport.perform_request( "GET", _make_path("_security", "user", username), params=params )
[ "def", "get_user", "(", "self", ",", "username", "=", "None", ",", "params", "=", "None", ")", ":", "return", "self", ".", "transport", ".", "perform_request", "(", "\"GET\"", ",", "_make_path", "(", "\"_security\"", ",", "\"user\"", ",", "username", ")", ",", "params", "=", "params", ")" ]
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-get-user.html>`_ :arg username: A comma-separated list of usernames
[ "<https", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "security", "-", "api", "-", "get", "-", "user", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/xpack/security.py#L262-L270
train
elastic/elasticsearch-py
elasticsearch/client/xpack/security.py
SecurityClient.has_privileges
def has_privileges(self, body, user=None, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-has-privileges.html>`_ :arg body: The privileges to test :arg user: Username """ if body in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'body'.") return self.transport.perform_request( "GET", _make_path("_security", "user", user, "_has_privileges"), params=params, body=body, )
python
def has_privileges(self, body, user=None, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-has-privileges.html>`_ :arg body: The privileges to test :arg user: Username """ if body in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'body'.") return self.transport.perform_request( "GET", _make_path("_security", "user", user, "_has_privileges"), params=params, body=body, )
[ "def", "has_privileges", "(", "self", ",", "body", ",", "user", "=", "None", ",", "params", "=", "None", ")", ":", "if", "body", "in", "SKIP_IN_PATH", ":", "raise", "ValueError", "(", "\"Empty value passed for a required argument 'body'.\"", ")", "return", "self", ".", "transport", ".", "perform_request", "(", "\"GET\"", ",", "_make_path", "(", "\"_security\"", ",", "\"user\"", ",", "user", ",", "\"_has_privileges\"", ")", ",", "params", "=", "params", ",", "body", "=", "body", ",", ")" ]
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-has-privileges.html>`_ :arg body: The privileges to test :arg user: Username
[ "<https", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "security", "-", "api", "-", "has", "-", "privileges", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/xpack/security.py#L282-L296
train
elastic/elasticsearch-py
elasticsearch/client/xpack/security.py
SecurityClient.invalidate_api_key
def invalidate_api_key(self, body, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-invalidate-api-key.html>`_ :arg body: The api key request to invalidate API key(s) """ if body in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'body'.") return self.transport.perform_request( "DELETE", "/_security/api_key", params=params, body=body )
python
def invalidate_api_key(self, body, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-invalidate-api-key.html>`_ :arg body: The api key request to invalidate API key(s) """ if body in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'body'.") return self.transport.perform_request( "DELETE", "/_security/api_key", params=params, body=body )
[ "def", "invalidate_api_key", "(", "self", ",", "body", ",", "params", "=", "None", ")", ":", "if", "body", "in", "SKIP_IN_PATH", ":", "raise", "ValueError", "(", "\"Empty value passed for a required argument 'body'.\"", ")", "return", "self", ".", "transport", ".", "perform_request", "(", "\"DELETE\"", ",", "\"/_security/api_key\"", ",", "params", "=", "params", ",", "body", "=", "body", ")" ]
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-invalidate-api-key.html>`_ :arg body: The api key request to invalidate API key(s)
[ "<https", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "security", "-", "api", "-", "invalidate", "-", "api", "-", "key", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/xpack/security.py#L299-L309
train
elastic/elasticsearch-py
elasticsearch/client/xpack/security.py
SecurityClient.invalidate_token
def invalidate_token(self, body, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-invalidate-token.html>`_ :arg body: The token to invalidate """ if body in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'body'.") return self.transport.perform_request( "DELETE", "/_security/oauth2/token", params=params, body=body )
python
def invalidate_token(self, body, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-invalidate-token.html>`_ :arg body: The token to invalidate """ if body in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'body'.") return self.transport.perform_request( "DELETE", "/_security/oauth2/token", params=params, body=body )
[ "def", "invalidate_token", "(", "self", ",", "body", ",", "params", "=", "None", ")", ":", "if", "body", "in", "SKIP_IN_PATH", ":", "raise", "ValueError", "(", "\"Empty value passed for a required argument 'body'.\"", ")", "return", "self", ".", "transport", ".", "perform_request", "(", "\"DELETE\"", ",", "\"/_security/oauth2/token\"", ",", "params", "=", "params", ",", "body", "=", "body", ")" ]
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-invalidate-token.html>`_ :arg body: The token to invalidate
[ "<https", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "security", "-", "api", "-", "invalidate", "-", "token", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/xpack/security.py#L312-L322
train
elastic/elasticsearch-py
elasticsearch/client/xpack/security.py
SecurityClient.put_privileges
def put_privileges(self, body, params=None): """ `<TODO>`_ :arg body: The privilege(s) to add :arg refresh: If `true` (the default) then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` then do nothing with refreshes., valid choices are: 'true', 'false', 'wait_for' """ if body in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'body'.") return self.transport.perform_request( "PUT", "/_security/privilege/", params=params, body=body )
python
def put_privileges(self, body, params=None): """ `<TODO>`_ :arg body: The privilege(s) to add :arg refresh: If `true` (the default) then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` then do nothing with refreshes., valid choices are: 'true', 'false', 'wait_for' """ if body in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'body'.") return self.transport.perform_request( "PUT", "/_security/privilege/", params=params, body=body )
[ "def", "put_privileges", "(", "self", ",", "body", ",", "params", "=", "None", ")", ":", "if", "body", "in", "SKIP_IN_PATH", ":", "raise", "ValueError", "(", "\"Empty value passed for a required argument 'body'.\"", ")", "return", "self", ".", "transport", ".", "perform_request", "(", "\"PUT\"", ",", "\"/_security/privilege/\"", ",", "params", "=", "params", ",", "body", "=", "body", ")" ]
`<TODO>`_ :arg body: The privilege(s) to add :arg refresh: If `true` (the default) then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` then do nothing with refreshes., valid choices are: 'true', 'false', 'wait_for'
[ "<TODO", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/xpack/security.py#L325-L340
train
elastic/elasticsearch-py
elasticsearch/client/xpack/security.py
SecurityClient.put_user
def put_user(self, username, body, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-put-user.html>`_ :arg username: The username of the User :arg body: The user to add :arg refresh: If `true` (the default) then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` then do nothing with refreshes., valid choices are: 'true', 'false', 'wait_for' """ for param in (username, body): if param in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument.") return self.transport.perform_request( "PUT", _make_path("_security", "user", username), params=params, body=body )
python
def put_user(self, username, body, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-put-user.html>`_ :arg username: The username of the User :arg body: The user to add :arg refresh: If `true` (the default) then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` then do nothing with refreshes., valid choices are: 'true', 'false', 'wait_for' """ for param in (username, body): if param in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument.") return self.transport.perform_request( "PUT", _make_path("_security", "user", username), params=params, body=body )
[ "def", "put_user", "(", "self", ",", "username", ",", "body", ",", "params", "=", "None", ")", ":", "for", "param", "in", "(", "username", ",", "body", ")", ":", "if", "param", "in", "SKIP_IN_PATH", ":", "raise", "ValueError", "(", "\"Empty value passed for a required argument.\"", ")", "return", "self", ".", "transport", ".", "perform_request", "(", "\"PUT\"", ",", "_make_path", "(", "\"_security\"", ",", "\"user\"", ",", "username", ")", ",", "params", "=", "params", ",", "body", "=", "body", ")" ]
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-put-user.html>`_ :arg username: The username of the User :arg body: The user to add :arg refresh: If `true` (the default) then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` then do nothing with refreshes., valid choices are: 'true', 'false', 'wait_for'
[ "<https", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "security", "-", "api", "-", "put", "-", "user", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/xpack/security.py#L386-L403
train
elastic/elasticsearch-py
elasticsearch/client/xpack/ilm.py
IlmClient.delete_lifecycle
def delete_lifecycle(self, policy=None, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/ilm-delete-lifecycle.html>`_ :arg policy: The name of the index lifecycle policy """ return self.transport.perform_request( "DELETE", _make_path("_ilm", "policy", policy), params=params )
python
def delete_lifecycle(self, policy=None, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/ilm-delete-lifecycle.html>`_ :arg policy: The name of the index lifecycle policy """ return self.transport.perform_request( "DELETE", _make_path("_ilm", "policy", policy), params=params )
[ "def", "delete_lifecycle", "(", "self", ",", "policy", "=", "None", ",", "params", "=", "None", ")", ":", "return", "self", ".", "transport", ".", "perform_request", "(", "\"DELETE\"", ",", "_make_path", "(", "\"_ilm\"", ",", "\"policy\"", ",", "policy", ")", ",", "params", "=", "params", ")" ]
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/ilm-delete-lifecycle.html>`_ :arg policy: The name of the index lifecycle policy
[ "<https", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "ilm", "-", "delete", "-", "lifecycle", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/xpack/ilm.py#L6-L14
train
elastic/elasticsearch-py
elasticsearch/client/xpack/ilm.py
IlmClient.explain_lifecycle
def explain_lifecycle(self, index=None, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/ilm-explain-lifecycle.html>`_ :arg index: The name of the index to explain """ return self.transport.perform_request( "GET", _make_path(index, "_ilm", "explain"), params=params )
python
def explain_lifecycle(self, index=None, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/ilm-explain-lifecycle.html>`_ :arg index: The name of the index to explain """ return self.transport.perform_request( "GET", _make_path(index, "_ilm", "explain"), params=params )
[ "def", "explain_lifecycle", "(", "self", ",", "index", "=", "None", ",", "params", "=", "None", ")", ":", "return", "self", ".", "transport", ".", "perform_request", "(", "\"GET\"", ",", "_make_path", "(", "index", ",", "\"_ilm\"", ",", "\"explain\"", ")", ",", "params", "=", "params", ")" ]
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/ilm-explain-lifecycle.html>`_ :arg index: The name of the index to explain
[ "<https", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "ilm", "-", "explain", "-", "lifecycle", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/xpack/ilm.py#L17-L25
train
elastic/elasticsearch-py
elasticsearch/client/xpack/ilm.py
IlmClient.get_lifecycle
def get_lifecycle(self, policy=None, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/ilm-get-lifecycle.html>`_ :arg policy: The name of the index lifecycle policy """ return self.transport.perform_request( "GET", _make_path("_ilm", "policy", policy), params=params )
python
def get_lifecycle(self, policy=None, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/ilm-get-lifecycle.html>`_ :arg policy: The name of the index lifecycle policy """ return self.transport.perform_request( "GET", _make_path("_ilm", "policy", policy), params=params )
[ "def", "get_lifecycle", "(", "self", ",", "policy", "=", "None", ",", "params", "=", "None", ")", ":", "return", "self", ".", "transport", ".", "perform_request", "(", "\"GET\"", ",", "_make_path", "(", "\"_ilm\"", ",", "\"policy\"", ",", "policy", ")", ",", "params", "=", "params", ")" ]
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/ilm-get-lifecycle.html>`_ :arg policy: The name of the index lifecycle policy
[ "<https", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "ilm", "-", "get", "-", "lifecycle", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/xpack/ilm.py#L28-L36
train
elastic/elasticsearch-py
elasticsearch/client/xpack/ilm.py
IlmClient.move_to_step
def move_to_step(self, index=None, body=None, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/ilm-move-to-step.html>`_ :arg index: The name of the index whose lifecycle step is to change :arg body: The new lifecycle step to move to """ return self.transport.perform_request( "POST", _make_path("_ilm", "move", index), params=params, body=body )
python
def move_to_step(self, index=None, body=None, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/ilm-move-to-step.html>`_ :arg index: The name of the index whose lifecycle step is to change :arg body: The new lifecycle step to move to """ return self.transport.perform_request( "POST", _make_path("_ilm", "move", index), params=params, body=body )
[ "def", "move_to_step", "(", "self", ",", "index", "=", "None", ",", "body", "=", "None", ",", "params", "=", "None", ")", ":", "return", "self", ".", "transport", ".", "perform_request", "(", "\"POST\"", ",", "_make_path", "(", "\"_ilm\"", ",", "\"move\"", ",", "index", ")", ",", "params", "=", "params", ",", "body", "=", "body", ")" ]
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/ilm-move-to-step.html>`_ :arg index: The name of the index whose lifecycle step is to change :arg body: The new lifecycle step to move to
[ "<https", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "ilm", "-", "move", "-", "to", "-", "step", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/xpack/ilm.py#L46-L55
train
elastic/elasticsearch-py
elasticsearch/client/xpack/ilm.py
IlmClient.put_lifecycle
def put_lifecycle(self, policy=None, body=None, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/ilm-put-lifecycle.html>`_ :arg policy: The name of the index lifecycle policy :arg body: The lifecycle policy definition to register """ return self.transport.perform_request( "PUT", _make_path("_ilm", "policy", policy), params=params, body=body )
python
def put_lifecycle(self, policy=None, body=None, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/ilm-put-lifecycle.html>`_ :arg policy: The name of the index lifecycle policy :arg body: The lifecycle policy definition to register """ return self.transport.perform_request( "PUT", _make_path("_ilm", "policy", policy), params=params, body=body )
[ "def", "put_lifecycle", "(", "self", ",", "policy", "=", "None", ",", "body", "=", "None", ",", "params", "=", "None", ")", ":", "return", "self", ".", "transport", ".", "perform_request", "(", "\"PUT\"", ",", "_make_path", "(", "\"_ilm\"", ",", "\"policy\"", ",", "policy", ")", ",", "params", "=", "params", ",", "body", "=", "body", ")" ]
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/ilm-put-lifecycle.html>`_ :arg policy: The name of the index lifecycle policy :arg body: The lifecycle policy definition to register
[ "<https", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "ilm", "-", "put", "-", "lifecycle", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/xpack/ilm.py#L58-L67
train
elastic/elasticsearch-py
elasticsearch/client/xpack/ilm.py
IlmClient.remove_policy
def remove_policy(self, index=None, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/ilm-remove-policy.html>`_ :arg index: The name of the index to remove policy on """ return self.transport.perform_request( "POST", _make_path(index, "_ilm", "remove"), params=params )
python
def remove_policy(self, index=None, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/ilm-remove-policy.html>`_ :arg index: The name of the index to remove policy on """ return self.transport.perform_request( "POST", _make_path(index, "_ilm", "remove"), params=params )
[ "def", "remove_policy", "(", "self", ",", "index", "=", "None", ",", "params", "=", "None", ")", ":", "return", "self", ".", "transport", ".", "perform_request", "(", "\"POST\"", ",", "_make_path", "(", "index", ",", "\"_ilm\"", ",", "\"remove\"", ")", ",", "params", "=", "params", ")" ]
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/ilm-remove-policy.html>`_ :arg index: The name of the index to remove policy on
[ "<https", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "ilm", "-", "remove", "-", "policy", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/xpack/ilm.py#L70-L78
train
elastic/elasticsearch-py
elasticsearch/client/xpack/ilm.py
IlmClient.retry
def retry(self, index=None, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/ilm-retry-policy.html>`_ :arg index: The name of the indices (comma-separated) whose failed lifecycle step is to be retry """ return self.transport.perform_request( "POST", _make_path(index, "_ilm", "retry"), params=params )
python
def retry(self, index=None, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/ilm-retry-policy.html>`_ :arg index: The name of the indices (comma-separated) whose failed lifecycle step is to be retry """ return self.transport.perform_request( "POST", _make_path(index, "_ilm", "retry"), params=params )
[ "def", "retry", "(", "self", ",", "index", "=", "None", ",", "params", "=", "None", ")", ":", "return", "self", ".", "transport", ".", "perform_request", "(", "\"POST\"", ",", "_make_path", "(", "index", ",", "\"_ilm\"", ",", "\"retry\"", ")", ",", "params", "=", "params", ")" ]
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/ilm-retry-policy.html>`_ :arg index: The name of the indices (comma-separated) whose failed lifecycle step is to be retry
[ "<https", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "ilm", "-", "retry", "-", "policy", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/xpack/ilm.py#L81-L90
train
elastic/elasticsearch-py
elasticsearch/client/xpack/license.py
LicenseClient.post
def post(self, body=None, params=None): """ `<https://www.elastic.co/guide/en/x-pack/current/license-management.html>`_ :arg body: licenses to be installed :arg acknowledge: whether the user has acknowledged acknowledge messages (default: false) """ return self.transport.perform_request( "PUT", "/_license", params=params, body=body )
python
def post(self, body=None, params=None): """ `<https://www.elastic.co/guide/en/x-pack/current/license-management.html>`_ :arg body: licenses to be installed :arg acknowledge: whether the user has acknowledged acknowledge messages (default: false) """ return self.transport.perform_request( "PUT", "/_license", params=params, body=body )
[ "def", "post", "(", "self", ",", "body", "=", "None", ",", "params", "=", "None", ")", ":", "return", "self", ".", "transport", ".", "perform_request", "(", "\"PUT\"", ",", "\"/_license\"", ",", "params", "=", "params", ",", "body", "=", "body", ")" ]
`<https://www.elastic.co/guide/en/x-pack/current/license-management.html>`_ :arg body: licenses to be installed :arg acknowledge: whether the user has acknowledged acknowledge messages (default: false)
[ "<https", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "x", "-", "pack", "/", "current", "/", "license", "-", "management", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/xpack/license.py#L41-L51
train
elastic/elasticsearch-py
example/load.py
parse_commits
def parse_commits(head, name): """ Go through the git repository log and generate a document per commit containing all the metadata. """ for commit in head.traverse(): yield { '_id': commit.hexsha, 'repository': name, 'committed_date': datetime.fromtimestamp(commit.committed_date), 'committer': { 'name': commit.committer.name, 'email': commit.committer.email, }, 'authored_date': datetime.fromtimestamp(commit.authored_date), 'author': { 'name': commit.author.name, 'email': commit.author.email, }, 'description': commit.message, 'parent_shas': [p.hexsha for p in commit.parents], # we only care about the filenames, not the per-file stats 'files': list(commit.stats.files), 'stats': commit.stats.total, }
python
def parse_commits(head, name): """ Go through the git repository log and generate a document per commit containing all the metadata. """ for commit in head.traverse(): yield { '_id': commit.hexsha, 'repository': name, 'committed_date': datetime.fromtimestamp(commit.committed_date), 'committer': { 'name': commit.committer.name, 'email': commit.committer.email, }, 'authored_date': datetime.fromtimestamp(commit.authored_date), 'author': { 'name': commit.author.name, 'email': commit.author.email, }, 'description': commit.message, 'parent_shas': [p.hexsha for p in commit.parents], # we only care about the filenames, not the per-file stats 'files': list(commit.stats.files), 'stats': commit.stats.total, }
[ "def", "parse_commits", "(", "head", ",", "name", ")", ":", "for", "commit", "in", "head", ".", "traverse", "(", ")", ":", "yield", "{", "'_id'", ":", "commit", ".", "hexsha", ",", "'repository'", ":", "name", ",", "'committed_date'", ":", "datetime", ".", "fromtimestamp", "(", "commit", ".", "committed_date", ")", ",", "'committer'", ":", "{", "'name'", ":", "commit", ".", "committer", ".", "name", ",", "'email'", ":", "commit", ".", "committer", ".", "email", ",", "}", ",", "'authored_date'", ":", "datetime", ".", "fromtimestamp", "(", "commit", ".", "authored_date", ")", ",", "'author'", ":", "{", "'name'", ":", "commit", ".", "author", ".", "name", ",", "'email'", ":", "commit", ".", "author", ".", "email", ",", "}", ",", "'description'", ":", "commit", ".", "message", ",", "'parent_shas'", ":", "[", "p", ".", "hexsha", "for", "p", "in", "commit", ".", "parents", "]", ",", "# we only care about the filenames, not the per-file stats", "'files'", ":", "list", "(", "commit", ".", "stats", ".", "files", ")", ",", "'stats'", ":", "commit", ".", "stats", ".", "total", ",", "}" ]
Go through the git repository log and generate a document per commit containing all the metadata.
[ "Go", "through", "the", "git", "repository", "log", "and", "generate", "a", "document", "per", "commit", "containing", "all", "the", "metadata", "." ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/example/load.py#L76-L100
train
elastic/elasticsearch-py
example/load.py
load_repo
def load_repo(client, path=None, index='git'): """ Parse a git repository with all it's commits and load it into elasticsearch using `client`. If the index doesn't exist it will be created. """ path = dirname(dirname(abspath(__file__))) if path is None else path repo_name = basename(path) repo = git.Repo(path) create_git_index(client, index) # we let the streaming bulk continuously process the commits as they come # in - since the `parse_commits` function is a generator this will avoid # loading all the commits into memory for ok, result in streaming_bulk( client, parse_commits(repo.refs.master.commit, repo_name), index=index, doc_type='doc', chunk_size=50 # keep the batch sizes small for appearances only ): action, result = result.popitem() doc_id = '/%s/doc/%s' % (index, result['_id']) # process the information from ES whether the document has been # successfully indexed if not ok: print('Failed to %s document %s: %r' % (action, doc_id, result)) else: print(doc_id)
python
def load_repo(client, path=None, index='git'): """ Parse a git repository with all it's commits and load it into elasticsearch using `client`. If the index doesn't exist it will be created. """ path = dirname(dirname(abspath(__file__))) if path is None else path repo_name = basename(path) repo = git.Repo(path) create_git_index(client, index) # we let the streaming bulk continuously process the commits as they come # in - since the `parse_commits` function is a generator this will avoid # loading all the commits into memory for ok, result in streaming_bulk( client, parse_commits(repo.refs.master.commit, repo_name), index=index, doc_type='doc', chunk_size=50 # keep the batch sizes small for appearances only ): action, result = result.popitem() doc_id = '/%s/doc/%s' % (index, result['_id']) # process the information from ES whether the document has been # successfully indexed if not ok: print('Failed to %s document %s: %r' % (action, doc_id, result)) else: print(doc_id)
[ "def", "load_repo", "(", "client", ",", "path", "=", "None", ",", "index", "=", "'git'", ")", ":", "path", "=", "dirname", "(", "dirname", "(", "abspath", "(", "__file__", ")", ")", ")", "if", "path", "is", "None", "else", "path", "repo_name", "=", "basename", "(", "path", ")", "repo", "=", "git", ".", "Repo", "(", "path", ")", "create_git_index", "(", "client", ",", "index", ")", "# we let the streaming bulk continuously process the commits as they come", "# in - since the `parse_commits` function is a generator this will avoid", "# loading all the commits into memory", "for", "ok", ",", "result", "in", "streaming_bulk", "(", "client", ",", "parse_commits", "(", "repo", ".", "refs", ".", "master", ".", "commit", ",", "repo_name", ")", ",", "index", "=", "index", ",", "doc_type", "=", "'doc'", ",", "chunk_size", "=", "50", "# keep the batch sizes small for appearances only", ")", ":", "action", ",", "result", "=", "result", ".", "popitem", "(", ")", "doc_id", "=", "'/%s/doc/%s'", "%", "(", "index", ",", "result", "[", "'_id'", "]", ")", "# process the information from ES whether the document has been", "# successfully indexed", "if", "not", "ok", ":", "print", "(", "'Failed to %s document %s: %r'", "%", "(", "action", ",", "doc_id", ",", "result", ")", ")", "else", ":", "print", "(", "doc_id", ")" ]
Parse a git repository with all it's commits and load it into elasticsearch using `client`. If the index doesn't exist it will be created.
[ "Parse", "a", "git", "repository", "with", "all", "it", "s", "commits", "and", "load", "it", "into", "elasticsearch", "using", "client", ".", "If", "the", "index", "doesn", "t", "exist", "it", "will", "be", "created", "." ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/example/load.py#L102-L130
train
elastic/elasticsearch-py
elasticsearch/client/xpack/rollup.py
RollupClient.get_jobs
def get_jobs(self, id=None, params=None): """ `<>`_ :arg id: The ID of the job(s) to fetch. Accepts glob patterns, or left blank for all jobs """ return self.transport.perform_request( "GET", _make_path("_rollup", "job", id), params=params )
python
def get_jobs(self, id=None, params=None): """ `<>`_ :arg id: The ID of the job(s) to fetch. Accepts glob patterns, or left blank for all jobs """ return self.transport.perform_request( "GET", _make_path("_rollup", "job", id), params=params )
[ "def", "get_jobs", "(", "self", ",", "id", "=", "None", ",", "params", "=", "None", ")", ":", "return", "self", ".", "transport", ".", "perform_request", "(", "\"GET\"", ",", "_make_path", "(", "\"_rollup\"", ",", "\"job\"", ",", "id", ")", ",", "params", "=", "params", ")" ]
`<>`_ :arg id: The ID of the job(s) to fetch. Accepts glob patterns, or left blank for all jobs
[ "<", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/xpack/rollup.py#L19-L28
train
elastic/elasticsearch-py
elasticsearch/client/xpack/rollup.py
RollupClient.get_rollup_caps
def get_rollup_caps(self, id=None, params=None): """ `<>`_ :arg id: The ID of the index to check rollup capabilities on, or left blank for all jobs """ return self.transport.perform_request( "GET", _make_path("_rollup", "data", id), params=params )
python
def get_rollup_caps(self, id=None, params=None): """ `<>`_ :arg id: The ID of the index to check rollup capabilities on, or left blank for all jobs """ return self.transport.perform_request( "GET", _make_path("_rollup", "data", id), params=params )
[ "def", "get_rollup_caps", "(", "self", ",", "id", "=", "None", ",", "params", "=", "None", ")", ":", "return", "self", ".", "transport", ".", "perform_request", "(", "\"GET\"", ",", "_make_path", "(", "\"_rollup\"", ",", "\"data\"", ",", "id", ")", ",", "params", "=", "params", ")" ]
`<>`_ :arg id: The ID of the index to check rollup capabilities on, or left blank for all jobs
[ "<", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/xpack/rollup.py#L31-L40
train
elastic/elasticsearch-py
elasticsearch/client/xpack/rollup.py
RollupClient.put_job
def put_job(self, id, body, params=None): """ `<>`_ :arg id: The ID of the job to create :arg body: The job configuration """ for param in (id, body): if param in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument.") return self.transport.perform_request( "PUT", _make_path("_rollup", "job", id), params=params, body=body )
python
def put_job(self, id, body, params=None): """ `<>`_ :arg id: The ID of the job to create :arg body: The job configuration """ for param in (id, body): if param in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument.") return self.transport.perform_request( "PUT", _make_path("_rollup", "job", id), params=params, body=body )
[ "def", "put_job", "(", "self", ",", "id", ",", "body", ",", "params", "=", "None", ")", ":", "for", "param", "in", "(", "id", ",", "body", ")", ":", "if", "param", "in", "SKIP_IN_PATH", ":", "raise", "ValueError", "(", "\"Empty value passed for a required argument.\"", ")", "return", "self", ".", "transport", ".", "perform_request", "(", "\"PUT\"", ",", "_make_path", "(", "\"_rollup\"", ",", "\"job\"", ",", "id", ")", ",", "params", "=", "params", ",", "body", "=", "body", ")" ]
`<>`_ :arg id: The ID of the job to create :arg body: The job configuration
[ "<", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/xpack/rollup.py#L57-L69
train
elastic/elasticsearch-py
elasticsearch/client/xpack/deprecation.py
DeprecationClient.info
def info(self, index=None, params=None): """ `<http://www.elastic.co/guide/en/migration/current/migration-api-deprecation.html>`_ :arg index: Index pattern """ return self.transport.perform_request( "GET", _make_path(index, "_xpack", "migration", "deprecations"), params=params, )
python
def info(self, index=None, params=None): """ `<http://www.elastic.co/guide/en/migration/current/migration-api-deprecation.html>`_ :arg index: Index pattern """ return self.transport.perform_request( "GET", _make_path(index, "_xpack", "migration", "deprecations"), params=params, )
[ "def", "info", "(", "self", ",", "index", "=", "None", ",", "params", "=", "None", ")", ":", "return", "self", ".", "transport", ".", "perform_request", "(", "\"GET\"", ",", "_make_path", "(", "index", ",", "\"_xpack\"", ",", "\"migration\"", ",", "\"deprecations\"", ")", ",", "params", "=", "params", ",", ")" ]
`<http://www.elastic.co/guide/en/migration/current/migration-api-deprecation.html>`_ :arg index: Index pattern
[ "<http", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "migration", "/", "current", "/", "migration", "-", "api", "-", "deprecation", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/xpack/deprecation.py#L6-L16
train
elastic/elasticsearch-py
elasticsearch/client/nodes.py
NodesClient.info
def info(self, node_id=None, metric=None, params=None): """ The cluster nodes info API allows to retrieve one or more (or all) of the cluster nodes information. `<https://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-nodes-info.html>`_ :arg node_id: A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes :arg metric: A comma-separated list of metrics you wish returned. Leave empty to return all. :arg flat_settings: Return settings in flat format (default: false) :arg timeout: Explicit operation timeout """ return self.transport.perform_request( "GET", _make_path("_nodes", node_id, metric), params=params )
python
def info(self, node_id=None, metric=None, params=None): """ The cluster nodes info API allows to retrieve one or more (or all) of the cluster nodes information. `<https://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-nodes-info.html>`_ :arg node_id: A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes :arg metric: A comma-separated list of metrics you wish returned. Leave empty to return all. :arg flat_settings: Return settings in flat format (default: false) :arg timeout: Explicit operation timeout """ return self.transport.perform_request( "GET", _make_path("_nodes", node_id, metric), params=params )
[ "def", "info", "(", "self", ",", "node_id", "=", "None", ",", "metric", "=", "None", ",", "params", "=", "None", ")", ":", "return", "self", ".", "transport", ".", "perform_request", "(", "\"GET\"", ",", "_make_path", "(", "\"_nodes\"", ",", "node_id", ",", "metric", ")", ",", "params", "=", "params", ")" ]
The cluster nodes info API allows to retrieve one or more (or all) of the cluster nodes information. `<https://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-nodes-info.html>`_ :arg node_id: A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes :arg metric: A comma-separated list of metrics you wish returned. Leave empty to return all. :arg flat_settings: Return settings in flat format (default: false) :arg timeout: Explicit operation timeout
[ "The", "cluster", "nodes", "info", "API", "allows", "to", "retrieve", "one", "or", "more", "(", "or", "all", ")", "of", "the", "cluster", "nodes", "information", ".", "<https", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "cluster", "-", "nodes", "-", "info", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/nodes.py#L17-L34
train
elastic/elasticsearch-py
elasticsearch/client/nodes.py
NodesClient.stats
def stats(self, node_id=None, metric=None, index_metric=None, params=None): """ The cluster nodes stats API allows to retrieve one or more (or all) of the cluster nodes statistics. `<https://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-nodes-stats.html>`_ :arg node_id: A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes :arg metric: Limit the information returned to the specified metrics :arg index_metric: Limit the information returned for `indices` metric to the specific index metrics. Isn't used if `indices` (or `all`) metric isn't specified. :arg completion_fields: A comma-separated list of fields for `fielddata` and `suggest` index metric (supports wildcards) :arg fielddata_fields: A comma-separated list of fields for `fielddata` index metric (supports wildcards) :arg fields: A comma-separated list of fields for `fielddata` and `completion` index metric (supports wildcards) :arg groups: A comma-separated list of search groups for `search` index metric :arg include_segment_file_sizes: Whether to report the aggregated disk usage of each one of the Lucene index files (only applies if segment stats are requested), default False :arg level: Return indices stats aggregated at index, node or shard level, default 'node', valid choices are: 'indices', 'node', 'shards' :arg timeout: Explicit operation timeout :arg types: A comma-separated list of document types for the `indexing` index metric """ return self.transport.perform_request( "GET", _make_path("_nodes", node_id, "stats", metric, index_metric), params=params, )
python
def stats(self, node_id=None, metric=None, index_metric=None, params=None): """ The cluster nodes stats API allows to retrieve one or more (or all) of the cluster nodes statistics. `<https://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-nodes-stats.html>`_ :arg node_id: A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes :arg metric: Limit the information returned to the specified metrics :arg index_metric: Limit the information returned for `indices` metric to the specific index metrics. Isn't used if `indices` (or `all`) metric isn't specified. :arg completion_fields: A comma-separated list of fields for `fielddata` and `suggest` index metric (supports wildcards) :arg fielddata_fields: A comma-separated list of fields for `fielddata` index metric (supports wildcards) :arg fields: A comma-separated list of fields for `fielddata` and `completion` index metric (supports wildcards) :arg groups: A comma-separated list of search groups for `search` index metric :arg include_segment_file_sizes: Whether to report the aggregated disk usage of each one of the Lucene index files (only applies if segment stats are requested), default False :arg level: Return indices stats aggregated at index, node or shard level, default 'node', valid choices are: 'indices', 'node', 'shards' :arg timeout: Explicit operation timeout :arg types: A comma-separated list of document types for the `indexing` index metric """ return self.transport.perform_request( "GET", _make_path("_nodes", node_id, "stats", metric, index_metric), params=params, )
[ "def", "stats", "(", "self", ",", "node_id", "=", "None", ",", "metric", "=", "None", ",", "index_metric", "=", "None", ",", "params", "=", "None", ")", ":", "return", "self", ".", "transport", ".", "perform_request", "(", "\"GET\"", ",", "_make_path", "(", "\"_nodes\"", ",", "node_id", ",", "\"stats\"", ",", "metric", ",", "index_metric", ")", ",", "params", "=", "params", ",", ")" ]
The cluster nodes stats API allows to retrieve one or more (or all) of the cluster nodes statistics. `<https://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-nodes-stats.html>`_ :arg node_id: A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes :arg metric: Limit the information returned to the specified metrics :arg index_metric: Limit the information returned for `indices` metric to the specific index metrics. Isn't used if `indices` (or `all`) metric isn't specified. :arg completion_fields: A comma-separated list of fields for `fielddata` and `suggest` index metric (supports wildcards) :arg fielddata_fields: A comma-separated list of fields for `fielddata` index metric (supports wildcards) :arg fields: A comma-separated list of fields for `fielddata` and `completion` index metric (supports wildcards) :arg groups: A comma-separated list of search groups for `search` index metric :arg include_segment_file_sizes: Whether to report the aggregated disk usage of each one of the Lucene index files (only applies if segment stats are requested), default False :arg level: Return indices stats aggregated at index, node or shard level, default 'node', valid choices are: 'indices', 'node', 'shards' :arg timeout: Explicit operation timeout :arg types: A comma-separated list of document types for the `indexing` index metric
[ "The", "cluster", "nodes", "stats", "API", "allows", "to", "retrieve", "one", "or", "more", "(", "or", "all", ")", "of", "the", "cluster", "nodes", "statistics", ".", "<https", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "cluster", "-", "nodes", "-", "stats", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/nodes.py#L46-L82
train
elastic/elasticsearch-py
elasticsearch/client/nodes.py
NodesClient.hot_threads
def hot_threads(self, node_id=None, params=None): """ An API allowing to get the current hot threads on each node in the cluster. `<https://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-nodes-hot-threads.html>`_ :arg node_id: A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes :arg type: The type to sample (default: cpu), valid choices are: 'cpu', 'wait', 'block' :arg ignore_idle_threads: Don't show threads that are in known-idle places, such as waiting on a socket select or pulling from an empty task queue (default: true) :arg interval: The interval for the second sampling of threads :arg snapshots: Number of samples of thread stacktrace (default: 10) :arg threads: Specify the number of threads to provide information for (default: 3) :arg timeout: Explicit operation timeout """ # avoid python reserved words if params and "type_" in params: params["type"] = params.pop("type_") return self.transport.perform_request( "GET", _make_path("_cluster", "nodes", node_id, "hotthreads"), params=params )
python
def hot_threads(self, node_id=None, params=None): """ An API allowing to get the current hot threads on each node in the cluster. `<https://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-nodes-hot-threads.html>`_ :arg node_id: A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes :arg type: The type to sample (default: cpu), valid choices are: 'cpu', 'wait', 'block' :arg ignore_idle_threads: Don't show threads that are in known-idle places, such as waiting on a socket select or pulling from an empty task queue (default: true) :arg interval: The interval for the second sampling of threads :arg snapshots: Number of samples of thread stacktrace (default: 10) :arg threads: Specify the number of threads to provide information for (default: 3) :arg timeout: Explicit operation timeout """ # avoid python reserved words if params and "type_" in params: params["type"] = params.pop("type_") return self.transport.perform_request( "GET", _make_path("_cluster", "nodes", node_id, "hotthreads"), params=params )
[ "def", "hot_threads", "(", "self", ",", "node_id", "=", "None", ",", "params", "=", "None", ")", ":", "# avoid python reserved words", "if", "params", "and", "\"type_\"", "in", "params", ":", "params", "[", "\"type\"", "]", "=", "params", ".", "pop", "(", "\"type_\"", ")", "return", "self", ".", "transport", ".", "perform_request", "(", "\"GET\"", ",", "_make_path", "(", "\"_cluster\"", ",", "\"nodes\"", ",", "node_id", ",", "\"hotthreads\"", ")", ",", "params", "=", "params", ")" ]
An API allowing to get the current hot threads on each node in the cluster. `<https://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-nodes-hot-threads.html>`_ :arg node_id: A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes :arg type: The type to sample (default: cpu), valid choices are: 'cpu', 'wait', 'block' :arg ignore_idle_threads: Don't show threads that are in known-idle places, such as waiting on a socket select or pulling from an empty task queue (default: true) :arg interval: The interval for the second sampling of threads :arg snapshots: Number of samples of thread stacktrace (default: 10) :arg threads: Specify the number of threads to provide information for (default: 3) :arg timeout: Explicit operation timeout
[ "An", "API", "allowing", "to", "get", "the", "current", "hot", "threads", "on", "each", "node", "in", "the", "cluster", ".", "<https", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "cluster", "-", "nodes", "-", "hot", "-", "threads", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/nodes.py#L87-L112
train
elastic/elasticsearch-py
elasticsearch/client/nodes.py
NodesClient.usage
def usage(self, node_id=None, metric=None, params=None): """ The cluster nodes usage API allows to retrieve information on the usage of features for each node. `<http://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-nodes-usage.html>`_ :arg node_id: A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes :arg metric: Limit the information returned to the specified metrics :arg human: Whether to return time and byte values in human-readable format., default False :arg timeout: Explicit operation timeout """ return self.transport.perform_request( "GET", _make_path("_nodes", node_id, "usage", metric), params=params )
python
def usage(self, node_id=None, metric=None, params=None): """ The cluster nodes usage API allows to retrieve information on the usage of features for each node. `<http://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-nodes-usage.html>`_ :arg node_id: A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes :arg metric: Limit the information returned to the specified metrics :arg human: Whether to return time and byte values in human-readable format., default False :arg timeout: Explicit operation timeout """ return self.transport.perform_request( "GET", _make_path("_nodes", node_id, "usage", metric), params=params )
[ "def", "usage", "(", "self", ",", "node_id", "=", "None", ",", "metric", "=", "None", ",", "params", "=", "None", ")", ":", "return", "self", ".", "transport", ".", "perform_request", "(", "\"GET\"", ",", "_make_path", "(", "\"_nodes\"", ",", "node_id", ",", "\"usage\"", ",", "metric", ")", ",", "params", "=", "params", ")" ]
The cluster nodes usage API allows to retrieve information on the usage of features for each node. `<http://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-nodes-usage.html>`_ :arg node_id: A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes :arg metric: Limit the information returned to the specified metrics :arg human: Whether to return time and byte values in human-readable format., default False :arg timeout: Explicit operation timeout
[ "The", "cluster", "nodes", "usage", "API", "allows", "to", "retrieve", "information", "on", "the", "usage", "of", "features", "for", "each", "node", ".", "<http", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "master", "/", "cluster", "-", "nodes", "-", "usage", ".", "html", ">", "_" ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/nodes.py#L115-L132
train
elastic/elasticsearch-py
elasticsearch/helpers/actions.py
_chunk_actions
def _chunk_actions(actions, chunk_size, max_chunk_bytes, serializer): """ Split actions into chunks by number or size, serialize them into strings in the process. """ bulk_actions, bulk_data = [], [] size, action_count = 0, 0 for action, data in actions: raw_data, raw_action = data, action action = serializer.dumps(action) # +1 to account for the trailing new line character cur_size = len(action.encode("utf-8")) + 1 if data is not None: data = serializer.dumps(data) cur_size += len(data.encode("utf-8")) + 1 # full chunk, send it and start a new one if bulk_actions and ( size + cur_size > max_chunk_bytes or action_count == chunk_size ): yield bulk_data, bulk_actions bulk_actions, bulk_data = [], [] size, action_count = 0, 0 bulk_actions.append(action) if data is not None: bulk_actions.append(data) bulk_data.append((raw_action, raw_data)) else: bulk_data.append((raw_action,)) size += cur_size action_count += 1 if bulk_actions: yield bulk_data, bulk_actions
python
def _chunk_actions(actions, chunk_size, max_chunk_bytes, serializer): """ Split actions into chunks by number or size, serialize them into strings in the process. """ bulk_actions, bulk_data = [], [] size, action_count = 0, 0 for action, data in actions: raw_data, raw_action = data, action action = serializer.dumps(action) # +1 to account for the trailing new line character cur_size = len(action.encode("utf-8")) + 1 if data is not None: data = serializer.dumps(data) cur_size += len(data.encode("utf-8")) + 1 # full chunk, send it and start a new one if bulk_actions and ( size + cur_size > max_chunk_bytes or action_count == chunk_size ): yield bulk_data, bulk_actions bulk_actions, bulk_data = [], [] size, action_count = 0, 0 bulk_actions.append(action) if data is not None: bulk_actions.append(data) bulk_data.append((raw_action, raw_data)) else: bulk_data.append((raw_action,)) size += cur_size action_count += 1 if bulk_actions: yield bulk_data, bulk_actions
[ "def", "_chunk_actions", "(", "actions", ",", "chunk_size", ",", "max_chunk_bytes", ",", "serializer", ")", ":", "bulk_actions", ",", "bulk_data", "=", "[", "]", ",", "[", "]", "size", ",", "action_count", "=", "0", ",", "0", "for", "action", ",", "data", "in", "actions", ":", "raw_data", ",", "raw_action", "=", "data", ",", "action", "action", "=", "serializer", ".", "dumps", "(", "action", ")", "# +1 to account for the trailing new line character", "cur_size", "=", "len", "(", "action", ".", "encode", "(", "\"utf-8\"", ")", ")", "+", "1", "if", "data", "is", "not", "None", ":", "data", "=", "serializer", ".", "dumps", "(", "data", ")", "cur_size", "+=", "len", "(", "data", ".", "encode", "(", "\"utf-8\"", ")", ")", "+", "1", "# full chunk, send it and start a new one", "if", "bulk_actions", "and", "(", "size", "+", "cur_size", ">", "max_chunk_bytes", "or", "action_count", "==", "chunk_size", ")", ":", "yield", "bulk_data", ",", "bulk_actions", "bulk_actions", ",", "bulk_data", "=", "[", "]", ",", "[", "]", "size", ",", "action_count", "=", "0", ",", "0", "bulk_actions", ".", "append", "(", "action", ")", "if", "data", "is", "not", "None", ":", "bulk_actions", ".", "append", "(", "data", ")", "bulk_data", ".", "append", "(", "(", "raw_action", ",", "raw_data", ")", ")", "else", ":", "bulk_data", ".", "append", "(", "(", "raw_action", ",", ")", ")", "size", "+=", "cur_size", "action_count", "+=", "1", "if", "bulk_actions", ":", "yield", "bulk_data", ",", "bulk_actions" ]
Split actions into chunks by number or size, serialize them into strings in the process.
[ "Split", "actions", "into", "chunks", "by", "number", "or", "size", "serialize", "them", "into", "strings", "in", "the", "process", "." ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/helpers/actions.py#L56-L92
train
elastic/elasticsearch-py
elasticsearch/helpers/actions.py
_process_bulk_chunk
def _process_bulk_chunk( client, bulk_actions, bulk_data, raise_on_exception=True, raise_on_error=True, *args, **kwargs ): """ Send a bulk request to elasticsearch and process the output. """ # if raise on error is set, we need to collect errors per chunk before raising them errors = [] try: # send the actual request resp = client.bulk("\n".join(bulk_actions) + "\n", *args, **kwargs) except TransportError as e: # default behavior - just propagate exception if raise_on_exception: raise e # if we are not propagating, mark all actions in current chunk as failed err_message = str(e) exc_errors = [] for data in bulk_data: # collect all the information about failed actions op_type, action = data[0].copy().popitem() info = {"error": err_message, "status": e.status_code, "exception": e} if op_type != "delete": info["data"] = data[1] info.update(action) exc_errors.append({op_type: info}) # emulate standard behavior for failed actions if raise_on_error: raise BulkIndexError( "%i document(s) failed to index." % len(exc_errors), exc_errors ) else: for err in exc_errors: yield False, err return # go through request-response pairs and detect failures for data, (op_type, item) in zip( bulk_data, map(methodcaller("popitem"), resp["items"]) ): ok = 200 <= item.get("status", 500) < 300 if not ok and raise_on_error: # include original document source if len(data) > 1: item["data"] = data[1] errors.append({op_type: item}) if ok or not errors: # if we are not just recording all errors to be able to raise # them all at once, yield items individually yield ok, {op_type: item} if errors: raise BulkIndexError("%i document(s) failed to index." % len(errors), errors)
python
def _process_bulk_chunk( client, bulk_actions, bulk_data, raise_on_exception=True, raise_on_error=True, *args, **kwargs ): """ Send a bulk request to elasticsearch and process the output. """ # if raise on error is set, we need to collect errors per chunk before raising them errors = [] try: # send the actual request resp = client.bulk("\n".join(bulk_actions) + "\n", *args, **kwargs) except TransportError as e: # default behavior - just propagate exception if raise_on_exception: raise e # if we are not propagating, mark all actions in current chunk as failed err_message = str(e) exc_errors = [] for data in bulk_data: # collect all the information about failed actions op_type, action = data[0].copy().popitem() info = {"error": err_message, "status": e.status_code, "exception": e} if op_type != "delete": info["data"] = data[1] info.update(action) exc_errors.append({op_type: info}) # emulate standard behavior for failed actions if raise_on_error: raise BulkIndexError( "%i document(s) failed to index." % len(exc_errors), exc_errors ) else: for err in exc_errors: yield False, err return # go through request-response pairs and detect failures for data, (op_type, item) in zip( bulk_data, map(methodcaller("popitem"), resp["items"]) ): ok = 200 <= item.get("status", 500) < 300 if not ok and raise_on_error: # include original document source if len(data) > 1: item["data"] = data[1] errors.append({op_type: item}) if ok or not errors: # if we are not just recording all errors to be able to raise # them all at once, yield items individually yield ok, {op_type: item} if errors: raise BulkIndexError("%i document(s) failed to index." % len(errors), errors)
[ "def", "_process_bulk_chunk", "(", "client", ",", "bulk_actions", ",", "bulk_data", ",", "raise_on_exception", "=", "True", ",", "raise_on_error", "=", "True", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# if raise on error is set, we need to collect errors per chunk before raising them", "errors", "=", "[", "]", "try", ":", "# send the actual request", "resp", "=", "client", ".", "bulk", "(", "\"\\n\"", ".", "join", "(", "bulk_actions", ")", "+", "\"\\n\"", ",", "*", "args", ",", "*", "*", "kwargs", ")", "except", "TransportError", "as", "e", ":", "# default behavior - just propagate exception", "if", "raise_on_exception", ":", "raise", "e", "# if we are not propagating, mark all actions in current chunk as failed", "err_message", "=", "str", "(", "e", ")", "exc_errors", "=", "[", "]", "for", "data", "in", "bulk_data", ":", "# collect all the information about failed actions", "op_type", ",", "action", "=", "data", "[", "0", "]", ".", "copy", "(", ")", ".", "popitem", "(", ")", "info", "=", "{", "\"error\"", ":", "err_message", ",", "\"status\"", ":", "e", ".", "status_code", ",", "\"exception\"", ":", "e", "}", "if", "op_type", "!=", "\"delete\"", ":", "info", "[", "\"data\"", "]", "=", "data", "[", "1", "]", "info", ".", "update", "(", "action", ")", "exc_errors", ".", "append", "(", "{", "op_type", ":", "info", "}", ")", "# emulate standard behavior for failed actions", "if", "raise_on_error", ":", "raise", "BulkIndexError", "(", "\"%i document(s) failed to index.\"", "%", "len", "(", "exc_errors", ")", ",", "exc_errors", ")", "else", ":", "for", "err", "in", "exc_errors", ":", "yield", "False", ",", "err", "return", "# go through request-response pairs and detect failures", "for", "data", ",", "(", "op_type", ",", "item", ")", "in", "zip", "(", "bulk_data", ",", "map", "(", "methodcaller", "(", "\"popitem\"", ")", ",", "resp", "[", "\"items\"", "]", ")", ")", ":", "ok", "=", "200", "<=", "item", ".", "get", "(", "\"status\"", ",", "500", ")", "<", "300", "if", "not", "ok", "and", "raise_on_error", ":", "# include original document source", "if", "len", "(", "data", ")", ">", "1", ":", "item", "[", "\"data\"", "]", "=", "data", "[", "1", "]", "errors", ".", "append", "(", "{", "op_type", ":", "item", "}", ")", "if", "ok", "or", "not", "errors", ":", "# if we are not just recording all errors to be able to raise", "# them all at once, yield items individually", "yield", "ok", ",", "{", "op_type", ":", "item", "}", "if", "errors", ":", "raise", "BulkIndexError", "(", "\"%i document(s) failed to index.\"", "%", "len", "(", "errors", ")", ",", "errors", ")" ]
Send a bulk request to elasticsearch and process the output.
[ "Send", "a", "bulk", "request", "to", "elasticsearch", "and", "process", "the", "output", "." ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/helpers/actions.py#L95-L158
train
elastic/elasticsearch-py
elasticsearch/helpers/actions.py
streaming_bulk
def streaming_bulk( client, actions, chunk_size=500, max_chunk_bytes=100 * 1024 * 1024, raise_on_error=True, expand_action_callback=expand_action, raise_on_exception=True, max_retries=0, initial_backoff=2, max_backoff=600, yield_ok=True, *args, **kwargs ): """ Streaming bulk consumes actions from the iterable passed in and yields results per action. For non-streaming usecases use :func:`~elasticsearch.helpers.bulk` which is a wrapper around streaming bulk that returns summary information about the bulk operation once the entire input is consumed and sent. If you specify ``max_retries`` it will also retry any documents that were rejected with a ``429`` status code. To do this it will wait (**by calling time.sleep which will block**) for ``initial_backoff`` seconds and then, every subsequent rejection for the same chunk, for double the time every time up to ``max_backoff`` seconds. :arg client: instance of :class:`~elasticsearch.Elasticsearch` to use :arg actions: iterable containing the actions to be executed :arg chunk_size: number of docs in one chunk sent to es (default: 500) :arg max_chunk_bytes: the maximum size of the request in bytes (default: 100MB) :arg raise_on_error: raise ``BulkIndexError`` containing errors (as `.errors`) from the execution of the last chunk when some occur. By default we raise. :arg raise_on_exception: if ``False`` then don't propagate exceptions from call to ``bulk`` and just report the items that failed as failed. :arg expand_action_callback: callback executed on each action passed in, should return a tuple containing the action line and the data line (`None` if data line should be omitted). :arg max_retries: maximum number of times a document will be retried when ``429`` is received, set to 0 (default) for no retries on ``429`` :arg initial_backoff: number of seconds we should wait before the first retry. Any subsequent retries will be powers of ``initial_backoff * 2**retry_number`` :arg max_backoff: maximum number of seconds a retry will wait :arg yield_ok: if set to False will skip successful documents in the output """ actions = map(expand_action_callback, actions) for bulk_data, bulk_actions in _chunk_actions( actions, chunk_size, max_chunk_bytes, client.transport.serializer ): for attempt in range(max_retries + 1): to_retry, to_retry_data = [], [] if attempt: time.sleep(min(max_backoff, initial_backoff * 2 ** (attempt - 1))) try: for data, (ok, info) in zip( bulk_data, _process_bulk_chunk( client, bulk_actions, bulk_data, raise_on_exception, raise_on_error, *args, **kwargs ), ): if not ok: action, info = info.popitem() # retry if retries enabled, we get 429, and we are not # in the last attempt if ( max_retries and info["status"] == 429 and (attempt + 1) <= max_retries ): # _process_bulk_chunk expects strings so we need to # re-serialize the data to_retry.extend( map(client.transport.serializer.dumps, data) ) to_retry_data.append(data) else: yield ok, {action: info} elif yield_ok: yield ok, info except TransportError as e: # suppress 429 errors since we will retry them if attempt == max_retries or e.status_code != 429: raise else: if not to_retry: break # retry only subset of documents that didn't succeed bulk_actions, bulk_data = to_retry, to_retry_data
python
def streaming_bulk( client, actions, chunk_size=500, max_chunk_bytes=100 * 1024 * 1024, raise_on_error=True, expand_action_callback=expand_action, raise_on_exception=True, max_retries=0, initial_backoff=2, max_backoff=600, yield_ok=True, *args, **kwargs ): """ Streaming bulk consumes actions from the iterable passed in and yields results per action. For non-streaming usecases use :func:`~elasticsearch.helpers.bulk` which is a wrapper around streaming bulk that returns summary information about the bulk operation once the entire input is consumed and sent. If you specify ``max_retries`` it will also retry any documents that were rejected with a ``429`` status code. To do this it will wait (**by calling time.sleep which will block**) for ``initial_backoff`` seconds and then, every subsequent rejection for the same chunk, for double the time every time up to ``max_backoff`` seconds. :arg client: instance of :class:`~elasticsearch.Elasticsearch` to use :arg actions: iterable containing the actions to be executed :arg chunk_size: number of docs in one chunk sent to es (default: 500) :arg max_chunk_bytes: the maximum size of the request in bytes (default: 100MB) :arg raise_on_error: raise ``BulkIndexError`` containing errors (as `.errors`) from the execution of the last chunk when some occur. By default we raise. :arg raise_on_exception: if ``False`` then don't propagate exceptions from call to ``bulk`` and just report the items that failed as failed. :arg expand_action_callback: callback executed on each action passed in, should return a tuple containing the action line and the data line (`None` if data line should be omitted). :arg max_retries: maximum number of times a document will be retried when ``429`` is received, set to 0 (default) for no retries on ``429`` :arg initial_backoff: number of seconds we should wait before the first retry. Any subsequent retries will be powers of ``initial_backoff * 2**retry_number`` :arg max_backoff: maximum number of seconds a retry will wait :arg yield_ok: if set to False will skip successful documents in the output """ actions = map(expand_action_callback, actions) for bulk_data, bulk_actions in _chunk_actions( actions, chunk_size, max_chunk_bytes, client.transport.serializer ): for attempt in range(max_retries + 1): to_retry, to_retry_data = [], [] if attempt: time.sleep(min(max_backoff, initial_backoff * 2 ** (attempt - 1))) try: for data, (ok, info) in zip( bulk_data, _process_bulk_chunk( client, bulk_actions, bulk_data, raise_on_exception, raise_on_error, *args, **kwargs ), ): if not ok: action, info = info.popitem() # retry if retries enabled, we get 429, and we are not # in the last attempt if ( max_retries and info["status"] == 429 and (attempt + 1) <= max_retries ): # _process_bulk_chunk expects strings so we need to # re-serialize the data to_retry.extend( map(client.transport.serializer.dumps, data) ) to_retry_data.append(data) else: yield ok, {action: info} elif yield_ok: yield ok, info except TransportError as e: # suppress 429 errors since we will retry them if attempt == max_retries or e.status_code != 429: raise else: if not to_retry: break # retry only subset of documents that didn't succeed bulk_actions, bulk_data = to_retry, to_retry_data
[ "def", "streaming_bulk", "(", "client", ",", "actions", ",", "chunk_size", "=", "500", ",", "max_chunk_bytes", "=", "100", "*", "1024", "*", "1024", ",", "raise_on_error", "=", "True", ",", "expand_action_callback", "=", "expand_action", ",", "raise_on_exception", "=", "True", ",", "max_retries", "=", "0", ",", "initial_backoff", "=", "2", ",", "max_backoff", "=", "600", ",", "yield_ok", "=", "True", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "actions", "=", "map", "(", "expand_action_callback", ",", "actions", ")", "for", "bulk_data", ",", "bulk_actions", "in", "_chunk_actions", "(", "actions", ",", "chunk_size", ",", "max_chunk_bytes", ",", "client", ".", "transport", ".", "serializer", ")", ":", "for", "attempt", "in", "range", "(", "max_retries", "+", "1", ")", ":", "to_retry", ",", "to_retry_data", "=", "[", "]", ",", "[", "]", "if", "attempt", ":", "time", ".", "sleep", "(", "min", "(", "max_backoff", ",", "initial_backoff", "*", "2", "**", "(", "attempt", "-", "1", ")", ")", ")", "try", ":", "for", "data", ",", "(", "ok", ",", "info", ")", "in", "zip", "(", "bulk_data", ",", "_process_bulk_chunk", "(", "client", ",", "bulk_actions", ",", "bulk_data", ",", "raise_on_exception", ",", "raise_on_error", ",", "*", "args", ",", "*", "*", "kwargs", ")", ",", ")", ":", "if", "not", "ok", ":", "action", ",", "info", "=", "info", ".", "popitem", "(", ")", "# retry if retries enabled, we get 429, and we are not", "# in the last attempt", "if", "(", "max_retries", "and", "info", "[", "\"status\"", "]", "==", "429", "and", "(", "attempt", "+", "1", ")", "<=", "max_retries", ")", ":", "# _process_bulk_chunk expects strings so we need to", "# re-serialize the data", "to_retry", ".", "extend", "(", "map", "(", "client", ".", "transport", ".", "serializer", ".", "dumps", ",", "data", ")", ")", "to_retry_data", ".", "append", "(", "data", ")", "else", ":", "yield", "ok", ",", "{", "action", ":", "info", "}", "elif", "yield_ok", ":", "yield", "ok", ",", "info", "except", "TransportError", "as", "e", ":", "# suppress 429 errors since we will retry them", "if", "attempt", "==", "max_retries", "or", "e", ".", "status_code", "!=", "429", ":", "raise", "else", ":", "if", "not", "to_retry", ":", "break", "# retry only subset of documents that didn't succeed", "bulk_actions", ",", "bulk_data", "=", "to_retry", ",", "to_retry_data" ]
Streaming bulk consumes actions from the iterable passed in and yields results per action. For non-streaming usecases use :func:`~elasticsearch.helpers.bulk` which is a wrapper around streaming bulk that returns summary information about the bulk operation once the entire input is consumed and sent. If you specify ``max_retries`` it will also retry any documents that were rejected with a ``429`` status code. To do this it will wait (**by calling time.sleep which will block**) for ``initial_backoff`` seconds and then, every subsequent rejection for the same chunk, for double the time every time up to ``max_backoff`` seconds. :arg client: instance of :class:`~elasticsearch.Elasticsearch` to use :arg actions: iterable containing the actions to be executed :arg chunk_size: number of docs in one chunk sent to es (default: 500) :arg max_chunk_bytes: the maximum size of the request in bytes (default: 100MB) :arg raise_on_error: raise ``BulkIndexError`` containing errors (as `.errors`) from the execution of the last chunk when some occur. By default we raise. :arg raise_on_exception: if ``False`` then don't propagate exceptions from call to ``bulk`` and just report the items that failed as failed. :arg expand_action_callback: callback executed on each action passed in, should return a tuple containing the action line and the data line (`None` if data line should be omitted). :arg max_retries: maximum number of times a document will be retried when ``429`` is received, set to 0 (default) for no retries on ``429`` :arg initial_backoff: number of seconds we should wait before the first retry. Any subsequent retries will be powers of ``initial_backoff * 2**retry_number`` :arg max_backoff: maximum number of seconds a retry will wait :arg yield_ok: if set to False will skip successful documents in the output
[ "Streaming", "bulk", "consumes", "actions", "from", "the", "iterable", "passed", "in", "and", "yields", "results", "per", "action", ".", "For", "non", "-", "streaming", "usecases", "use", ":", "func", ":", "~elasticsearch", ".", "helpers", ".", "bulk", "which", "is", "a", "wrapper", "around", "streaming", "bulk", "that", "returns", "summary", "information", "about", "the", "bulk", "operation", "once", "the", "entire", "input", "is", "consumed", "and", "sent", "." ]
2aab285c8f506f3863cbdaba3c90a685c510ba00
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/helpers/actions.py#L161-L262
train