INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
[int] 买方向挂单量
def buy_open_order_quantity(self): """ [int] 买方向挂单量 """ return sum(order.unfilled_quantity for order in self.open_orders if order.side == SIDE.BUY and order.position_effect == POSITION_EFFECT.OPEN)
[int] 卖方向挂单量
def sell_open_order_quantity(self): """ [int] 卖方向挂单量 """ return sum(order.unfilled_quantity for order in self.open_orders if order.side == SIDE.SELL and order.position_effect == POSITION_EFFECT.OPEN)
[int] 买方向挂单量
def buy_close_order_quantity(self): """ [int] 买方向挂单量 """ return sum(order.unfilled_quantity for order in self.open_orders if order.side == SIDE.BUY and order.position_effect in [POSITION_EFFECT.CLOSE, POSITION_EFFECT.CLOSE_TODAY])
[int] 卖方向挂单量
def sell_close_order_quantity(self): """ [int] 卖方向挂单量 """ return sum(order.unfilled_quantity for order in self.open_orders if order.side == SIDE.SELL and order.position_effect in [POSITION_EFFECT.CLOSE, POSITION_EFFECT.CLOSE_TODAY])
[float] 买方向持仓均价
def buy_avg_holding_price(self): """ [float] 买方向持仓均价 """ return 0 if self.buy_quantity == 0 else self._buy_holding_cost / self.buy_quantity / self.contract_multiplier
[float] 卖方向持仓均价
def sell_avg_holding_price(self): """ [float] 卖方向持仓均价 """ return 0 if self.sell_quantity == 0 else self._sell_holding_cost / self.sell_quantity / self.contract_multiplier
判断合约是否过期
def is_de_listed(self): """ 判断合约是否过期 """ instrument = Environment.get_instance().get_instrument(self._order_book_id) current_date = Environment.get_instance().trading_dt if instrument.de_listed_date is not None and current_date >= instrument.de_listed_date: re...
应用成交,并计算交易产生的现金变动。 开仓: delta_cash = -1 * margin = -1 * quantity * contract_multiplier * price * margin_rate 平仓: delta_cash = old_margin - margin + delta_realized_pnl = (sum of (cost_price * quantity) of closed trade) * contract_multiplier * margin_rate +...
def apply_trade(self, trade): """ 应用成交,并计算交易产生的现金变动。 开仓: delta_cash = -1 * margin = -1 * quantity * contract_multiplier * price * margin_rate 平仓: delta_cash = old_margin - margin + delta_realized_pnl = (sum of (cost_price * quantity) of c...
应用平仓,并计算平仓盈亏 买平: delta_realized_pnl = sum of ((trade_price - cost_price)* quantity) of closed trades * contract_multiplier 卖平: delta_realized_pnl = sum of ((cost_price - trade_price)* quantity) of closed trades * contract_multiplier :param trade: rqalpha.model.trade.Trade ...
def _close_holding(self, trade): """ 应用平仓,并计算平仓盈亏 买平: delta_realized_pnl = sum of ((trade_price - cost_price)* quantity) of closed trades * contract_multiplier 卖平: delta_realized_pnl = sum of ((cost_price - trade_price)* quantity) of closed trades * contract_multiplier ...
[str] 板块缩写代码,全球通用标准定义(股票专用)
def sector_code(self): """ [str] 板块缩写代码,全球通用标准定义(股票专用) """ try: return self.__dict__["sector_code"] except (KeyError, ValueError): raise AttributeError( "Instrument(order_book_id={}) has no attribute 'sector_code' ".format(self.order_book_i...
[str] 以当地语言为标准的板块代码名(股票专用)
def sector_code_name(self): """ [str] 以当地语言为标准的板块代码名(股票专用) """ try: return self.__dict__["sector_code_name"] except (KeyError, ValueError): raise AttributeError( "Instrument(order_book_id={}) has no attribute 'sector_code_name' ".format(sel...
[str] 国民经济行业分类代码,具体可参考“Industry列表” (股票专用)
def industry_code(self): """ [str] 国民经济行业分类代码,具体可参考“Industry列表” (股票专用) """ try: return self.__dict__["industry_code"] except (KeyError, ValueError): raise AttributeError( "Instrument(order_book_id={}) has no attribute 'industry_code' ".form...
[str] 国民经济行业分类名称(股票专用)
def industry_name(self): """ [str] 国民经济行业分类名称(股票专用) """ try: return self.__dict__["industry_name"] except (KeyError, ValueError): raise AttributeError( "Instrument(order_book_id={}) has no attribute 'industry_name' ".format(self.order_book_...
[str] 概念股分类,例如:’铁路基建’,’基金重仓’等(股票专用)
def concept_names(self): """ [str] 概念股分类,例如:’铁路基建’,’基金重仓’等(股票专用) """ try: return self.__dict__["concept_names"] except (KeyError, ValueError): raise AttributeError( "Instrument(order_book_id={}) has no attribute 'concept_names' ".format(sel...
[str] 板块类别,’MainBoard’ - 主板,’GEM’ - 创业板(股票专用)
def board_type(self): """ [str] 板块类别,’MainBoard’ - 主板,’GEM’ - 创业板(股票专用) """ try: return self.__dict__["board_type"] except (KeyError, ValueError): raise AttributeError( "Instrument(order_book_id={}) has no attribute 'board_type' ".format(se...
[str] 合约状态。’Active’ - 正常上市, ‘Delisted’ - 终止上市, ‘TemporarySuspended’ - 暂停上市, ‘PreIPO’ - 发行配售期间, ‘FailIPO’ - 发行失败(股票专用)
def status(self): """ [str] 合约状态。’Active’ - 正常上市, ‘Delisted’ - 终止上市, ‘TemporarySuspended’ - 暂停上市, ‘PreIPO’ - 发行配售期间, ‘FailIPO’ - 发行失败(股票专用) """ try: return self.__dict__["status"] except (KeyError, ValueError): raise AttributeError( ...
[str] 特别处理状态。’Normal’ - 正常上市, ‘ST’ - ST处理, ‘StarST’ - *ST代表该股票正在接受退市警告, ‘PT’ - 代表该股票连续3年收入为负,将被暂停交易, ‘Other’ - 其他(股票专用)
def special_type(self): """ [str] 特别处理状态。’Normal’ - 正常上市, ‘ST’ - ST处理, ‘StarST’ - *ST代表该股票正在接受退市警告, ‘PT’ - 代表该股票连续3年收入为负,将被暂停交易, ‘Other’ - 其他(股票专用) """ try: return self.__dict__["special_type"] except (KeyError, ValueError): raise AttributeError( ...
[float] 合约乘数,例如沪深300股指期货的乘数为300.0(期货专用)
def contract_multiplier(self): """ [float] 合约乘数,例如沪深300股指期货的乘数为300.0(期货专用) """ try: return self.__dict__["contract_multiplier"] except (KeyError, ValueError): raise AttributeError( "Instrument(order_book_id={}) has no attribute 'contract_mu...
[float] 合约最低保证金率(期货专用)
def margin_rate(self): """ [float] 合约最低保证金率(期货专用) """ try: return self.__dict__["margin_rate"] except (KeyError, ValueError): raise AttributeError( "Instrument(order_book_id={}) has no attribute 'margin_rate' ".format(self.order_book_id) ...
[str] 合约标的代码,目前除股指期货(IH, IF, IC)之外的期货合约,这一字段全部为’null’(期货专用)
def underlying_order_book_id(self): """ [str] 合约标的代码,目前除股指期货(IH, IF, IC)之外的期货合约,这一字段全部为’null’(期货专用) """ try: return self.__dict__["underlying_order_book_id"] except (KeyError, ValueError): raise AttributeError( "Instrument(order_book_id={})...
[str] 合约标的代码,目前除股指期货(IH, IF, IC)之外的期货合约,这一字段全部为’null’(期货专用)
def underlying_symbol(self): """ [str] 合约标的代码,目前除股指期货(IH, IF, IC)之外的期货合约,这一字段全部为’null’(期货专用) """ try: return self.__dict__["underlying_symbol"] except (KeyError, ValueError): raise AttributeError( "Instrument(order_book_id={}) has no attrib...
[datetime] 期货到期日。主力连续合约与指数连续合约都为 datetime(2999, 12, 31)(期货专用)
def maturity_date(self): """ [datetime] 期货到期日。主力连续合约与指数连续合约都为 datetime(2999, 12, 31)(期货专用) """ try: return self.__dict__["maturity_date"] except (KeyError, ValueError): raise AttributeError( "Instrument(order_book_id={}) has no attribute 'm...
[str] 交割方式,’CashSettlementRequired’ - 现金交割, ‘PhysicalSettlementRequired’ - 实物交割(期货专用)
def settlement_method(self): """ [str] 交割方式,’CashSettlementRequired’ - 现金交割, ‘PhysicalSettlementRequired’ - 实物交割(期货专用) """ try: return self.__dict__["settlement_method"] except (KeyError, ValueError): raise AttributeError( "Instrument(order...
[bool] 该合约当前日期是否在交易
def listing(self): """ [bool] 该合约当前日期是否在交易 """ now = Environment.get_instance().calendar_dt return self.listed_date <= now <= self.de_listed_date
计算手续费这个逻辑比较复杂,按照如下算法来计算: 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...
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,返回c...
港交所收费项目繁多,按照如下逻辑计算税费: 1. 税费比例为 0.11%,不足 1 元按 1 元记,四舍五入保留两位小数(包括印花税、交易征费、交易系统使用费)。 2,五元固定费用(包括卖方收取的转手纸印花税、买方收取的过户费用)。
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 ...
[float] 昨日收盘价
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.g...
WARNING: 获取 bar_status 比较耗费性能,而且是lazy_compute,因此不要多次调用!!!!
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:...
[float] 昨日结算价(期货专用)
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_...
通用下单函数,策略可以通过该函数自由选择参数下单。 :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...
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 order: 需要撤销的order对象 :type order: :class:`~Order` object
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
该方法用于更新现在关注的证券的集合(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:`~Ins...
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_sy...
订阅合约行情。该操作会导致合约池内合约的增加,从而影响handle_bar中处理bar数据的数量。 需要注意,用户在初次编写策略时候需要首先订阅合约行情,否则handle_bar不会被触发。 :param id_or_symbols: 标的物 :type id_or_symbols: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`]
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...
取消订阅合约行情。取消订阅会导致合约池内合约的减少,如果当前合约池中没有任何合约,则策略直接退出。 :param id_or_symbols: 标的物 :type id_or_symbols: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`]
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(...
获取某个国家市场指定日期的收益率曲线水平。 数据为2002年至今的中债国债收益率曲线,来源于中央国债登记结算有限责任公司。 :param date: 查询日期,默认为策略当前日期前一天 :type date: `str` | `date` | `datetime` | `pandas.Timestamp` :param str tenor: 标准期限,'0S' - 隔夜,'1M' - 1个月,'1Y' - 1年,默认为全部期限 :return: `pandas.DataFrame` - 查询时间段内无风险收益率曲线 :example: .. code-block:...
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.DataFra...
获取指定合约的历史行情,同时支持日以及分钟历史数据。不能在init中调用。 注意,该API会自动跳过停牌数据。 日回测获取分钟历史数据:不支持 日回测获取日历史数据 ========================= =================================================== 调用时间 返回数据 ========================= =================================================== T日before_trading ...
def history_bars( order_book_id, bar_count, frequency, fields=None, skip_suspended=True, include_now=False, adjust_type="pre", ): """ 获取指定合约的历史行情,同时支持日以及分钟历史数据。不能在init中调用。 注意,该API会自动跳过停牌数据。 日回测获取分钟历史数据:不支持 日回测获取日历史数据 ========================= ========================...
获取某个国家市场的所有合约信息。使用者可以通过这一方法很快地对合约信息有一个快速了解,目前仅支持中国市场。 :param str type: 需要查询合约类型,例如:type='CS'代表股票。默认是所有类型 :param date: 查询时间点 :type date: `str` | `datetime` | `date` :return: `pandas DataFrame` 所有合约的基本信息。 其中type参数传入的合约类型和对应的解释如下: ========================= ==================================...
def all_instruments(type=None, date=None): """ 获取某个国家市场的所有合约信息。使用者可以通过这一方法很快地对合约信息有一个快速了解,目前仅支持中国市场。 :param str type: 需要查询合约类型,例如:type='CS'代表股票。默认是所有类型 :param date: 查询时间点 :type date: `str` | `datetime` | `date` :return: `pandas DataFrame` 所有合约的基本信息。 其中type参数传入的合约类型和对应的解释如下: =======...
获得当前市场快照数据。只能在日内交易阶段调用,获取当日调用时点的市场快照数据。 市场快照数据记录了每日从开盘到当前的数据信息,可以理解为一个动态的day bar数据。 在目前分钟回测中,快照数据为当日所有分钟线累积而成,一般情况下,最后一个分钟线获取到的快照数据应当与当日的日线行情保持一致。 需要注意,在实盘模拟中,该函数返回的是调用当时的市场快照情况,所以在同一个handle_bar中不同时点调用可能返回的数据不同。 如果当日截止到调用时候对应股票没有任何成交,那么snapshot中的close, high, low, last几个价格水平都将以0表示。 :param str id_or_...
def current_snapshot(id_or_symbol): """ 获得当前市场快照数据。只能在日内交易阶段调用,获取当日调用时点的市场快照数据。 市场快照数据记录了每日从开盘到当前的数据信息,可以理解为一个动态的day bar数据。 在目前分钟回测中,快照数据为当日所有分钟线累积而成,一般情况下,最后一个分钟线获取到的快照数据应当与当日的日线行情保持一致。 需要注意,在实盘模拟中,该函数返回的是调用当时的市场快照情况,所以在同一个handle_bar中不同时点调用可能返回的数据不同。 如果当日截止到调用时候对应股票没有任何成交,那么snapshot中的close, hig...
[float] 投资组合在分红现金收到账面之前的应收分红部分。具体细节在分红部分
def dividend_receivable(self): """ [float] 投资组合在分红现金收到账面之前的应收分红部分。具体细节在分红部分 """ return sum(d['quantity'] * d['dividend_per_share'] for d in six.itervalues(self._dividend_receivable))
获取历史数据 :param instrument: 合约对象 :type instrument: :class:`~Instrument` :param int bar_count: 获取的历史数据数量 :param str frequency: 周期频率,`1d` 表示日周期, `1m` 表示分钟周期 :param str fields: 返回数据字段 ========================= =================================================== fi...
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: 获取的历史数据数量 ...
落指定股数的买/卖单,最常见的落单方式之一。如有需要落单类型当做一个参量传入,如果忽略掉落单类型,那么默认是市价单(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`, 此参数主要用于简化 `st...
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股的倍数。 ...
指定手数发送买/卖单。如有需要落单类型当做一个参量传入,如果忽略掉落单类型,那么默认是市价单(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` 参数。 ...
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...
发送一个花费价值等于目前投资组合(市场价值和目前现金的总和)一定百分比现金的买/卖单,正数代表买,负数代表卖。股票的股数总是会被调整成对应的一手的股票数的倍数(1手是100股)。百分比是一个小数,并且小于或等于1(<=100%),0.5表示的是50%.需要注意,如果资金不足,该API将不会创建发送订单。 需要注意: 发送买单时,percent 代表的是期望买入股票消耗的金额(包含税费)占投资组合总权益的比例。 发送卖单时,percent 代表的是期望卖出的股票总价值占投资组合总权益的比例。 :param id_or_ins: 下单标的物 :type id_or_ins: :class:`~...
def order_percent(id_or_ins, percent, price=None, style=None): """ 发送一个花费价值等于目前投资组合(市场价值和目前现金的总和)一定百分比现金的买/卖单,正数代表买,负数代表卖。股票的股数总是会被调整成对应的一手的股票数的倍数(1手是100股)。百分比是一个小数,并且小于或等于1(<=100%),0.5表示的是50%.需要注意,如果资金不足,该API将不会创建发送订单。 需要注意: 发送买单时,percent 代表的是期望买入股票消耗的金额(包含税费)占投资组合总权益的比例。 发送卖单时,percent 代表的是期望卖出的股票...
买入/卖出证券以自动调整该证券的仓位到占有一个目标价值。 加仓时,percent 代表证券已有持仓的价值加上即将花费的现金(包含税费)的总值占当前投资组合总价值的比例。 减仓时,percent 代表证券将被调整到的目标价至占当前投资组合总价值的比例。 其实我们需要计算一个position_to_adjust (即应该调整的仓位) `position_to_adjust = target_position - current_position` 投资组合价值等于所有已有仓位的价值和剩余现金的总和。买/卖单会被下舍入一手股数(A股是100的倍数)的倍数。目标百分比应该是一个小数,并且最大值...
def order_target_percent(id_or_ins, percent, price=None, style=None): """ 买入/卖出证券以自动调整该证券的仓位到占有一个目标价值。 加仓时,percent 代表证券已有持仓的价值加上即将花费的现金(包含税费)的总值占当前投资组合总价值的比例。 减仓时,percent 代表证券将被调整到的目标价至占当前投资组合总价值的比例。 其实我们需要计算一个position_to_adjust (即应该调整的仓位) `position_to_adjust = target_position - current_posit...
使用想要花费的金钱买入/卖出股票,而不是买入/卖出想要的股数,正数代表买入,负数代表卖出。股票的股数总是会被调整成对应的100的倍数(在A中国A股市场1手是100股)。如果资金不足,该API将不会创建发送订单。 需要注意: 当您提交一个买单时,cash_amount 代表的含义是您希望买入股票消耗的金额(包含税费),最终买入的股数不仅和发单的价格有关,还和税费相关的参数设置有关。 当您提交一个卖单时,cash_amount 代表的意义是您希望卖出股票的总价值。如果金额超出了您所持有股票的价值,那么您将卖出所有股票。 :param id_or_ins: 下单标的物 :type id_or_i...
def order_value(id_or_ins, cash_amount, price=None, style=None): """ 使用想要花费的金钱买入/卖出股票,而不是买入/卖出想要的股数,正数代表买入,负数代表卖出。股票的股数总是会被调整成对应的100的倍数(在A中国A股市场1手是100股)。如果资金不足,该API将不会创建发送订单。 需要注意: 当您提交一个买单时,cash_amount 代表的含义是您希望买入股票消耗的金额(包含税费),最终买入的股数不仅和发单的价格有关,还和税费相关的参数设置有关。 当您提交一个卖单时,cash_amount 代表的意义是您希望卖出股票的总价...
买入/卖出并且自动调整该证券的仓位到一个目标价值。 加仓时,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: 最终的该证券的仓位目标价值。 ...
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[:c...
判断某只股票是否全天停牌。 :param str order_book_id: 某只股票的代码或股票代码,可传入单只股票的order_book_id, symbol :param int count: 回溯获取的数据个数。默认为当前能够获取到的最近的数据 :return: count为1时 `bool`; count>1时 `pandas.DataFrame`
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() or...
Sync Data 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)
Start to run a strategy
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', No...
Generate example strategies to target folder
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:...
Generate default config file
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_...
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 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 i...
[sys_analyser] draw result DataFrame
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)
[sys_analyser] Generate report from backtest output file
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)
[float] 总保证金
def margin(self): """ [float] 总保证金 """ return sum(position.margin for position in six.itervalues(self._positions))
[float] 买方向保证金
def buy_margin(self): """ [float] 买方向保证金 """ return sum(position.buy_margin for position in six.itervalues(self._positions))
[float] 卖方向保证金
def sell_margin(self): """ [float] 卖方向保证金 """ return sum(position.sell_margin for position in six.itervalues(self._positions))
[float] 浮动盈亏
def holding_pnl(self): """ [float] 浮动盈亏 """ return sum(position.holding_pnl for position in six.itervalues(self._positions))
[float] 平仓盈亏
def realized_pnl(self): """ [float] 平仓盈亏 """ return sum(position.realized_pnl for position in six.itervalues(self._positions))
全品种通用智能调仓函数 如果不指定 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...
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 反向...
`<Clear SQL cursor>`_ :arg body: Specify the cursor value in the `cursor` element to clean the 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'.") ...
`<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
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: ...
`<Translate SQL into Elasticsearch queries>`_ :arg body: Specify the query in the `query` element.
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.tran...
Log a successful API call.
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 ...
Log an unsuccessful API call.
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...
Locate appropriate exception and raise it.
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('erro...
Helper function to transform hosts argument to :class:`~elasticsearch.Elasticsearch` to a list of dicts.
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,...
Returns True if the cluster is up, False otherwise. `<http://www.elastic.co/guide/>`_
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
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 i...
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 ...
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...
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 ...
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` ...
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 ...
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 refreshe...
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. ...
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-req...
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_pe...
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....
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://...
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 i...
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 in...
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 lon...
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...
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...
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...
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
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...
`<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
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 """ ...
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 reques...
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/elastic...
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 `_...
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...
`<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...
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 do...
Create a new :class:`~elasticsearch.Connection` instance and add it to the pool. :arg host: kwargs that will be used to create the instance
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)
Retreive a :class:`~elasticsearch.Connection` instance from the :class:`~elasticsearch.ConnectionPool` instance.
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() ...
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_t...
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 star...
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
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 ...
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 succesf...
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 connect...
`<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 t...
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 :ar...
`<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
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 ...
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-clear-role-cache.html>`_ :arg name: Role name
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...
`<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 ...
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 t...
`<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 `fal...
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...
`<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 ma...
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 ...
`<TODO>`_ :arg application: Application name :arg name: Privilege name
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...
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-get-role.html>`_ :arg name: Role name
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...
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-get-role-mapping.html>`_ :arg name: Role-Mapping name
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", "rol...
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-get-token.html>`_ :arg body: The token request to get
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 ...
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-get-user.html>`_ :arg username: A comma-separated list of usernames
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("_secur...
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-has-privileges.html>`_ :arg body: The privileges to test :arg user: Username
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 ValueErr...
`<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)
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...