Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def is_de_listed(self):
env = Environment.get_instance()
instrument = env.get_instrument(self._order_book_id)
current_date = env.trading_dt
if instrument.de_listed_date is not None:
if instrument.de_listed_date.date() > e... | [
"\n 判断合约是否过期\n "
] |
Please provide a description of the function:def bought_value(self):
user_system_log.warn(_(u"[abandon] {} is no longer valid.").format('stock_position.bought_value'))
return self._quantity * self._avg_price | [
"\n [已弃用]\n "
] |
Please provide a description of the function:def trading_pnl(self):
last_price = self._data_proxy.get_last_price(self._order_book_id)
return self._contract_multiplier * (self._trade_quantity * last_price - self._trade_cost) | [
"\n [float] 交易盈亏,策略在当前交易日产生的盈亏中来源于当日成交的部分\n "
] |
Please provide a description of the function:def position_pnl(self):
last_price = self._data_proxy.get_last_price(self._order_book_id)
if self._direction == POSITION_DIRECTION.LONG:
price_spread = last_price - self._last_price
else:
price_spread = self._last_pric... | [
"\n [float] 昨仓盈亏,策略在当前交易日产生的盈亏中来源于昨仓的部分\n "
] |
Please provide a description of the function:def register_event(self):
event_bus = Environment.get_instance().event_bus
event_bus.prepend_listener(EVENT.PRE_BEFORE_TRADING, self._pre_before_trading)
event_bus.prepend_listener(EVENT.POST_SETTLEMENT, self._post_settlement) | [
"\n 注册事件\n "
] |
Please provide a description of the function:def unit_net_value(self):
if self._units == 0:
return np.nan
return self.total_value / self._units | [
"\n [float] 实时净值\n "
] |
Please provide a description of the function:def daily_returns(self):
if self._static_unit_net_value == 0:
return np.nan
return 0 if self._static_unit_net_value == 0 else self.unit_net_value / self._static_unit_net_value - 1 | [
"\n [float] 当前最新一天的日收益\n "
] |
Please provide a description of the function:def total_value(self):
return sum(account.total_value for account in six.itervalues(self._accounts)) | [
"\n [float]总权益\n "
] |
Please provide a description of the function:def positions(self):
if self._mixed_positions is None:
self._mixed_positions = MixedPositions(self._accounts)
return self._mixed_positions | [
"\n [dict] 持仓\n "
] |
Please provide a description of the function:def cash(self):
return sum(account.cash for account in six.itervalues(self._accounts)) | [
"\n [float] 可用资金\n "
] |
Please provide a description of the function:def market_value(self):
return sum(account.market_value for account in six.itervalues(self._accounts)) | [
"\n [float] 市值\n "
] |
Please provide a description of the function:def buy_holding_pnl(self):
return (self.last_price - self.buy_avg_holding_price) * self.buy_quantity * self.contract_multiplier | [
"\n [float] 买方向当日持仓盈亏\n "
] |
Please provide a description of the function:def sell_holding_pnl(self):
return (self.sell_avg_holding_price - self.last_price) * self.sell_quantity * self.contract_multiplier | [
"\n [float] 卖方向当日持仓盈亏\n "
] |
Please provide a description of the function:def buy_pnl(self):
return (self.last_price - self._buy_avg_open_price) * self.buy_quantity * self.contract_multiplier | [
"\n [float] 买方向累计盈亏\n "
] |
Please provide a description of the function:def sell_pnl(self):
return (self._sell_avg_open_price - self.last_price) * self.sell_quantity * self.contract_multiplier | [
"\n [float] 卖方向累计盈亏\n "
] |
Please provide a description of the function:def buy_open_order_quantity(self):
return sum(order.unfilled_quantity for order in self.open_orders if
order.side == SIDE.BUY and order.position_effect == POSITION_EFFECT.OPEN) | [
"\n [int] 买方向挂单量\n "
] |
Please provide a description of the function:def sell_open_order_quantity(self):
return sum(order.unfilled_quantity for order in self.open_orders if
order.side == SIDE.SELL and order.position_effect == POSITION_EFFECT.OPEN) | [
"\n [int] 卖方向挂单量\n "
] |
Please provide a description of the function:def buy_close_order_quantity(self):
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]) | [
"\n [int] 买方向挂单量\n "
] |
Please provide a description of the function:def sell_close_order_quantity(self):
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]) | [
"\n [int] 卖方向挂单量\n "
] |
Please provide a description of the function:def buy_avg_holding_price(self):
return 0 if self.buy_quantity == 0 else self._buy_holding_cost / self.buy_quantity / self.contract_multiplier | [
"\n [float] 买方向持仓均价\n "
] |
Please provide a description of the function:def sell_avg_holding_price(self):
return 0 if self.sell_quantity == 0 else self._sell_holding_cost / self.sell_quantity / self.contract_multiplier | [
"\n [float] 卖方向持仓均价\n "
] |
Please provide a description of the function: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:
... | [
"\n 判断合约是否过期\n "
] |
Please provide a description of the function:def apply_trade(self, trade):
# close_trade: delta_cash = old_margin - margin + delta_realized_pnl
trade_quantity = trade.last_quantity
if trade.side == SIDE.BUY:
if trade.position_effect == POSITION_EFFECT.OPEN:
s... | [
"\n 应用成交,并计算交易产生的现金变动。\n\n 开仓:\n delta_cash\n = -1 * margin\n = -1 * quantity * contract_multiplier * price * margin_rate\n\n 平仓:\n delta_cash\n = old_margin - margin + delta_realized_pnl\n = (sum of (cost_price * quantity) of closed trade) * contract_m... |
Please provide a description of the function:def _close_holding(self, trade):
left_quantity = trade.last_quantity
delta = 0
if trade.side == SIDE.BUY:
# 先平昨仓
if trade.position_effect == POSITION_EFFECT.CLOSE and len(self._sell_old_holding_list) != 0:
... | [
"\n 应用平仓,并计算平仓盈亏\n\n 买平:\n delta_realized_pnl = sum of ((trade_price - cost_price)* quantity) of closed trades * contract_multiplier\n\n 卖平:\n delta_realized_pnl = sum of ((cost_price - trade_price)* quantity) of closed trades * contract_multiplier\n\n :param trade: rqalpha... |
Please provide a description of the function:def sector_code(self):
try:
return self.__dict__["sector_code"]
except (KeyError, ValueError):
raise AttributeError(
"Instrument(order_book_id={}) has no attribute 'sector_code' ".format(self.order_book_id)
... | [
"\n [str] 板块缩写代码,全球通用标准定义(股票专用)\n "
] |
Please provide a description of the function:def sector_code_name(self):
try:
return self.__dict__["sector_code_name"]
except (KeyError, ValueError):
raise AttributeError(
"Instrument(order_book_id={}) has no attribute 'sector_code_name' ".format(self.ord... | [
"\n [str] 以当地语言为标准的板块代码名(股票专用)\n "
] |
Please provide a description of the function:def industry_code(self):
try:
return self.__dict__["industry_code"]
except (KeyError, ValueError):
raise AttributeError(
"Instrument(order_book_id={}) has no attribute 'industry_code' ".format(self.order_book_i... | [
"\n [str] 国民经济行业分类代码,具体可参考“Industry列表” (股票专用)\n "
] |
Please provide a description of the function:def industry_name(self):
try:
return self.__dict__["industry_name"]
except (KeyError, ValueError):
raise AttributeError(
"Instrument(order_book_id={}) has no attribute 'industry_name' ".format(self.order_book_i... | [
"\n [str] 国民经济行业分类名称(股票专用)\n "
] |
Please provide a description of the function:def concept_names(self):
try:
return self.__dict__["concept_names"]
except (KeyError, ValueError):
raise AttributeError(
"Instrument(order_book_id={}) has no attribute 'concept_names' ".format(self.order_book_i... | [
"\n [str] 概念股分类,例如:’铁路基建’,’基金重仓’等(股票专用)\n "
] |
Please provide a description of the function:def board_type(self):
try:
return self.__dict__["board_type"]
except (KeyError, ValueError):
raise AttributeError(
"Instrument(order_book_id={}) has no attribute 'board_type' ".format(self.order_book_id)
... | [
"\n [str] 板块类别,’MainBoard’ - 主板,’GEM’ - 创业板(股票专用)\n "
] |
Please provide a description of the function:def status(self):
try:
return self.__dict__["status"]
except (KeyError, ValueError):
raise AttributeError(
"Instrument(order_book_id={}) has no attribute 'status' ".format(self.order_book_id)
) | [
"\n [str] 合约状态。’Active’ - 正常上市, ‘Delisted’ - 终止上市, ‘TemporarySuspended’ - 暂停上市,\n ‘PreIPO’ - 发行配售期间, ‘FailIPO’ - 发行失败(股票专用)\n "
] |
Please provide a description of the function:def special_type(self):
try:
return self.__dict__["special_type"]
except (KeyError, ValueError):
raise AttributeError(
"Instrument(order_book_id={}) has no attribute 'special_type' ".format(self.order_book_id)
... | [
"\n [str] 特别处理状态。’Normal’ - 正常上市, ‘ST’ - ST处理, ‘StarST’ - *ST代表该股票正在接受退市警告,\n ‘PT’ - 代表该股票连续3年收入为负,将被暂停交易, ‘Other’ - 其他(股票专用)\n "
] |
Please provide a description of the function:def contract_multiplier(self):
try:
return self.__dict__["contract_multiplier"]
except (KeyError, ValueError):
raise AttributeError(
"Instrument(order_book_id={}) has no attribute 'contract_multiplier' ".format... | [
"\n [float] 合约乘数,例如沪深300股指期货的乘数为300.0(期货专用)\n "
] |
Please provide a description of the function:def margin_rate(self):
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)
... | [
"\n [float] 合约最低保证金率(期货专用)\n "
] |
Please provide a description of the function:def underlying_order_book_id(self):
try:
return self.__dict__["underlying_order_book_id"]
except (KeyError, ValueError):
raise AttributeError(
"Instrument(order_book_id={}) has no attribute 'underlying_order_bo... | [
"\n [str] 合约标的代码,目前除股指期货(IH, IF, IC)之外的期货合约,这一字段全部为’null’(期货专用)\n "
] |
Please provide a description of the function:def underlying_symbol(self):
try:
return self.__dict__["underlying_symbol"]
except (KeyError, ValueError):
raise AttributeError(
"Instrument(order_book_id={}) has no attribute 'underlying_symbol' ".format(self.... | [
"\n [str] 合约标的代码,目前除股指期货(IH, IF, IC)之外的期货合约,这一字段全部为’null’(期货专用)\n "
] |
Please provide a description of the function:def maturity_date(self):
try:
return self.__dict__["maturity_date"]
except (KeyError, ValueError):
raise AttributeError(
"Instrument(order_book_id={}) has no attribute 'maturity_date' ".format(self.order_book_i... | [
"\n [datetime] 期货到期日。主力连续合约与指数连续合约都为 datetime(2999, 12, 31)(期货专用)\n "
] |
Please provide a description of the function:def settlement_method(self):
try:
return self.__dict__["settlement_method"]
except (KeyError, ValueError):
raise AttributeError(
"Instrument(order_book_id={}) has no attribute 'settlement_method' ".format(self.... | [
"\n [str] 交割方式,’CashSettlementRequired’ - 现金交割, ‘PhysicalSettlementRequired’ - 实物交割(期货专用)\n "
] |
Please provide a description of the function:def listing(self):
now = Environment.get_instance().calendar_dt
return self.listed_date <= now <= self.de_listed_date | [
"\n [bool] 该合约当前日期是否在交易\n "
] |
Please provide a description of the function: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 * tra... | [
"\n 计算手续费这个逻辑比较复杂,按照如下算法来计算:\n 1. 定义一个剩余手续费的概念,根据order_id存储在commission_map中,默认为min_commission\n 2. 当trade来时计算该trade产生的手续费cost_money\n 3. 如果cost_money > commission\n 3.1 如果commission 等于 min_commission,说明这是第一笔trade,此时,直接commission置0,返回cost_money即可\n 3.2 如果commissio... |
Please provide a description of the function: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
... | [
"\n 港交所收费项目繁多,按照如下逻辑计算税费:\n 1. 税费比例为 0.11%,不足 1 元按 1 元记,四舍五入保留两位小数(包括印花税、交易征费、交易系统使用费)。\n 2,五元固定费用(包括卖方收取的转手纸印花税、买方收取的过户费用)。\n "
] |
Please provide a description of the function: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 = Envir... | [
"\n [float] 昨日收盘价\n "
] |
Please provide a description of the function: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_... | [
"\n WARNING: 获取 bar_status 比较耗费性能,而且是lazy_compute,因此不要多次调用!!!!\n "
] |
Please provide a description of the function: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
dat... | [
"\n [float] 昨日结算价(期货专用)\n "
] |
Please provide a description of the function: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... | [
"\n 通用下单函数,策略可以通过该函数自由选择参数下单。\n\n :param id_or_ins: 下单标的物\n :type id_or_ins: :class:`~Instrument` object | `str`\n\n :param float amount: 下单量,需为正数\n\n :param side: 多空方向,多(SIDE.BUY)或空(SIDE.SELL)\n :type side: :class:`~SIDE` enum\n\n :param float price: 下单价格,默认为None,表示市价单\n\n :param position_e... |
Please provide a description of the function:def cancel_order(order):
env = Environment.get_instance()
if env.can_cancel_order(order):
env.broker.cancel_order(order)
return order | [
"\n 撤单\n\n :param order: 需要撤销的order对象\n :type order: :class:`~Order` object\n "
] |
Please provide a description of the function: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... | [
"\n 该方法用于更新现在关注的证券的集合(e.g.:股票池)。PS:会在下一个bar事件触发时候产生(新的关注的股票池更新)效果。并且update_universe会是覆盖(overwrite)的操作而不是在已有的股票池的基础上进行增量添加。比如已有的股票池为['000001.XSHE', '000024.XSHE']然后调用了update_universe(['000030.XSHE'])之后,股票池就会变成000030.XSHE一个股票了,随后的数据更新也只会跟踪000030.XSHE这一个股票了。\n\n :param id_or_symbols: 标的物\n :type id_or_symbols... |
Please provide a description of the function: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 isins... | [
"\n 订阅合约行情。该操作会导致合约池内合约的增加,从而影响handle_bar中处理bar数据的数量。\n\n 需要注意,用户在初次编写策略时候需要首先订阅合约行情,否则handle_bar不会被触发。\n\n :param id_or_symbols: 标的物\n :type id_or_symbols: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`]\n "
] |
Please provide a description of the function: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... | [
"\n 取消订阅合约行情。取消订阅会导致合约池内合约的减少,如果当前合约池中没有任何合约,则策略直接退出。\n\n :param id_or_symbols: 标的物\n :type id_or_symbols: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`]\n "
] |
Please provide a description of the function: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.Ti... | [
"\n 获取某个国家市场指定日期的收益率曲线水平。\n\n 数据为2002年至今的中债国债收益率曲线,来源于中央国债登记结算有限责任公司。\n\n :param date: 查询日期,默认为策略当前日期前一天\n :type date: `str` | `date` | `datetime` | `pandas.Timestamp`\n\n :param str tenor: 标准期限,'0S' - 隔夜,'1M' - 1个月,'1Y' - 1年,默认为全部期限\n\n :return: `pandas.DataFrame` - 查询时间段内无风险收益率曲线\n\n :example... |
Please provide a description of the function: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.calend... | [
"\n 获取指定合约的历史行情,同时支持日以及分钟历史数据。不能在init中调用。 注意,该API会自动跳过停牌数据。\n\n 日回测获取分钟历史数据:不支持\n\n 日回测获取日历史数据\n\n ========================= ===================================================\n 调用时间 返回数据\n ========================= ===================================================\n ... |
Please provide a description of the function: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 isinstanc... | [
"\n 获取某个国家市场的所有合约信息。使用者可以通过这一方法很快地对合约信息有一个快速了解,目前仅支持中国市场。\n\n :param str type: 需要查询合约类型,例如:type='CS'代表股票。默认是所有类型\n\n :param date: 查询时间点\n :type date: `str` | `datetime` | `date`\n\n\n :return: `pandas DataFrame` 所有合约的基本信息。\n\n 其中type参数传入的合约类型和对应的解释如下:\n\n ========================= ===========... |
Please provide a description of the function: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 Executio... | [
"\n 获得当前市场快照数据。只能在日内交易阶段调用,获取当日调用时点的市场快照数据。\n 市场快照数据记录了每日从开盘到当前的数据信息,可以理解为一个动态的day bar数据。\n 在目前分钟回测中,快照数据为当日所有分钟线累积而成,一般情况下,最后一个分钟线获取到的快照数据应当与当日的日线行情保持一致。\n 需要注意,在实盘模拟中,该函数返回的是调用当时的市场快照情况,所以在同一个handle_bar中不同时点调用可能返回的数据不同。\n 如果当日截止到调用时候对应股票没有任何成交,那么snapshot中的close, high, low, last几个价格水平都将以0表示。\n\n ... |
Please provide a description of the function:def dividend_receivable(self):
return sum(d['quantity'] * d['dividend_per_share'] for d in six.itervalues(self._dividend_receivable)) | [
"\n [float] 投资组合在分红现金收到账面之前的应收分红部分。具体细节在分红部分\n "
] |
Please provide a description of the function:def history_bars(self, instrument, bar_count, frequency, fields, dt, skip_suspended=True,
include_now=False, adjust_type='pre', adjust_orig=None):
raise NotImplementedError | [
"\n 获取历史数据\n\n :param instrument: 合约对象\n :type instrument: :class:`~Instrument`\n\n :param int bar_count: 获取的历史数据数量\n :param str frequency: 周期频率,`1d` 表示日周期, `1m` 表示分钟周期\n :param str fields: 返回数据字段\n\n ========================= ======================================... |
Please provide a description of the function: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... | [
"\n 落指定股数的买/卖单,最常见的落单方式之一。如有需要落单类型当做一个参量传入,如果忽略掉落单类型,那么默认是市价单(market order)。\n\n :param id_or_ins: 下单标的物\n :type id_or_ins: :class:`~Instrument` object | `str`\n\n :param int amount: 下单量, 正数代表买入,负数代表卖出。将会根据一手xx股来向下调整到一手的倍数,比如中国A股就是调整成100股的倍数。\n\n :param float price: 下单价格,默认为None,表示 :class:`~MarketOrd... |
Please provide a description of the function: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... | [
"\n 指定手数发送买/卖单。如有需要落单类型当做一个参量传入,如果忽略掉落单类型,那么默认是市价单(market order)。\n\n :param id_or_ins: 下单标的物\n :type id_or_ins: :class:`~Instrument` object | `str`\n\n :param int amount: 下单量, 正数代表买入,负数代表卖出。将会根据一手xx股来向下调整到一手的倍数,比如中国A股就是调整成100股的倍数。\n\n :param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要用... |
Please provide a description of the function: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"))
ord... | [
"\n 使用想要花费的金钱买入/卖出股票,而不是买入/卖出想要的股数,正数代表买入,负数代表卖出。股票的股数总是会被调整成对应的100的倍数(在A中国A股市场1手是100股)。如果资金不足,该API将不会创建发送订单。\n\n 需要注意:\n 当您提交一个买单时,cash_amount 代表的含义是您希望买入股票消耗的金额(包含税费),最终买入的股数不仅和发单的价格有关,还和税费相关的参数设置有关。\n 当您提交一个卖单时,cash_amount 代表的意义是您希望卖出股票的总价值。如果金额超出了您所持有股票的价值,那么您将卖出所有股票。\n\n :param id_or_ins: 下单标的物\... |
Please provide a description of the function: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[DEF... | [
"\n 发送一个花费价值等于目前投资组合(市场价值和目前现金的总和)一定百分比现金的买/卖单,正数代表买,负数代表卖。股票的股数总是会被调整成对应的一手的股票数的倍数(1手是100股)。百分比是一个小数,并且小于或等于1(<=100%),0.5表示的是50%.需要注意,如果资金不足,该API将不会创建发送订单。\n\n 需要注意:\n 发送买单时,percent 代表的是期望买入股票消耗的金额(包含税费)占投资组合总权益的比例。\n 发送卖单时,percent 代表的是期望卖出的股票总价值占投资组合总权益的比例。\n\n :param id_or_ins: 下单标的物\n :type id... |
Please provide a description of the function: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]... | [
"\n 买入/卖出并且自动调整该证券的仓位到一个目标价值。\n 加仓时,cash_amount 代表现有持仓的价值加上即将花费(包含税费)的现金的总价值。\n 减仓时,cash_amount 代表调整仓位的目标价至。\n\n 需要注意,如果资金不足,该API将不会创建发送订单。\n\n :param id_or_ins: 下单标的物\n :type id_or_ins: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`]\n\n :param float cash_amount:... |
Please provide a description of the function: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)
... | [
"\n 买入/卖出证券以自动调整该证券的仓位到占有一个目标价值。\n\n 加仓时,percent 代表证券已有持仓的价值加上即将花费的现金(包含税费)的总值占当前投资组合总价值的比例。\n 减仓时,percent 代表证券将被调整到的目标价至占当前投资组合总价值的比例。\n\n 其实我们需要计算一个position_to_adjust (即应该调整的仓位)\n\n `position_to_adjust = target_position - current_position`\n\n 投资组合价值等于所有已有仓位的价值和剩余现金的总和。买/卖单会被下舍入一手股数(A股是100的倍数)的倍... |
Please provide a description of the function: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) | [
"\n 判断某只股票是否全天停牌。\n\n :param str order_book_id: 某只股票的代码或股票代码,可传入单只股票的order_book_id, symbol\n\n :param int count: 回溯获取的数据个数。默认为当前能够获取到的最近的数据\n\n :return: count为1时 `bool`; count>1时 `pandas.DataFrame`\n "
] |
Please provide a description of the function:def update_bundle(data_bundle_path, locale):
import rqalpha.utils.bundle_helper
rqalpha.utils.bundle_helper.update_bundle(data_bundle_path, locale) | [
"\n Sync Data Bundle\n "
] |
Please provide a description of the function: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__securitie... | [
"\n Start to run a strategy\n "
] |
Please provide a description of the function: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:
si... | [
"\n Generate example strategies to target folder\n "
] |
Please provide a description of the function: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... | [
"\n Generate default config file\n "
] |
Please provide a description of the function:def mod(cmd, params):
def list(params):
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']):
... | [
"\n Mod management command\n\n rqalpha mod list \\n\n rqalpha mod install xxx \\n\n rqalpha mod uninstall xxx \\n\n rqalpha mod enable xxx \\n\n rqalpha mod disable xxx \\n\n\n ",
"\n List all mod configuration\n ",
"\n Install third-party Mod\n ",
"\n ... |
Please provide a description of the function: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) | [
"\n [sys_analyser] draw result DataFrame\n "
] |
Please provide a description of the function: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) | [
"\n [sys_analyser] Generate report from backtest output file\n "
] |
Please provide a description of the function:def margin(self):
return sum(position.margin for position in six.itervalues(self._positions)) | [
"\n [float] 总保证金\n "
] |
Please provide a description of the function:def buy_margin(self):
return sum(position.buy_margin for position in six.itervalues(self._positions)) | [
"\n [float] 买方向保证金\n "
] |
Please provide a description of the function:def sell_margin(self):
return sum(position.sell_margin for position in six.itervalues(self._positions)) | [
"\n [float] 卖方向保证金\n "
] |
Please provide a description of the function:def holding_pnl(self):
return sum(position.holding_pnl for position in six.itervalues(self._positions)) | [
"\n [float] 浮动盈亏\n "
] |
Please provide a description of the function:def realized_pnl(self):
return sum(position.realized_pnl for position in six.itervalues(self._positions)) | [
"\n [float] 平仓盈亏\n "
] |
Please provide a description of the function: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 | [
"\n 全品种通用智能调仓函数\n\n 如果不指定 price, 则相当于下 MarketOrder\n\n 如果 order_book_id 是股票,等同于调用 order_shares\n\n 如果 order_book_id 是期货,则进行智能下单:\n\n * quantity 表示调仓量\n * 如果 quantity 为正数,则先平 Sell 方向仓位,再开 Buy 方向仓位\n * 如果 quantity 为负数,则先平 Buy 反向仓位,再开 Sell 方向仓位\n\n :param order_book_id: 下单标的物\... |
Please provide a description of the function: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
... | [
"\n `<Clear SQL cursor>`_\n\n :arg body: Specify the cursor value in the `cursor` element to clean the\n cursor.\n "
] |
Please provide a description of the function: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) | [
"\n `<Execute SQL>`_\n\n :arg body: Use the `query` element to start a query. Use the `cursor`\n element to continue a query.\n :arg format: a short version of the Accept header, e.g. json, yaml\n "
] |
Please provide a description of the function: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... | [
"\n `<Translate SQL into Elasticsearch queries>`_\n\n :arg body: Specify the query in the `query` element.\n "
] |
Please provide a description of the function: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 lo... | [
" Log a successful API call. "
] |
Please provide a description of the function: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(
... | [
" Log an unsuccessful API call. "
] |
Please provide a description of the function: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', e... | [
" Locate appropriate exception and raise it. "
] |
Please provide a description of the function: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 ... | [
"\n Helper function to transform hosts argument to\n :class:`~elasticsearch.Elasticsearch` to a list of dicts.\n "
] |
Please provide a description of the function:def ping(self, params=None):
try:
return self.transport.perform_request("HEAD", "/", params=params)
except TransportError:
return False | [
"\n Returns True if the cluster is up, False otherwise.\n `<http://www.elastic.co/guide/>`_\n "
] |
Please provide a description of the function: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_... | [
"\n Get multiple documents based on an index, type (optional) and ids.\n `<http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-multi-get.html>`_\n\n :arg body: Document identifiers; can be either `docs` (containing full\n document information) or `ids` (when index and... |
Please provide a description of the function: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_reques... | [
"\n Update a document based on a script or partial data provided.\n `<http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update.html>`_\n\n :arg index: The name of the index\n :arg id: Document ID\n :arg body: The request definition using either `script` or partia... |
Please provide a description of the function: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"
r... | [
"\n Execute a search query and get back search hits that match the query.\n `<http://www.elastic.co/guide/en/elasticsearch/reference/current/search-search.html>`_\n\n :arg index: A list of index names to search, or a string containing a\n comma-separated list of index names to search... |
Please provide a description of the function: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
... | [
"\n Reindex all documents from one index to another.\n `<https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-reindex.html>`_\n\n :arg body: The search definition using the Query DSL and the prototype\n for the index request.\n :arg refresh: Should the effected... |
Please provide a description of the function:def reindex_rethrottle(self, task_id=None, params=None):
return self.transport.perform_request(
"POST", _make_path("_reindex", task_id, "_rethrottle"), params=params
) | [
"\n Change the value of ``requests_per_second`` of a running ``reindex`` task.\n `<https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-reindex.html>`_\n\n :arg task_id: The task id to rethrottle\n :arg requests_per_second: The throttle to set on this request in\n ... |
Please provide a description of the function:def search_shards(self, index=None, params=None):
return self.transport.perform_request(
"GET", _make_path(index, "_search_shards"), params=params
) | [
"\n The search shards api returns the indices and shards that a search\n request would be executed against. This can give useful feedback for working\n out issues or planning optimizations with routing and shard preferences.\n `<http://www.elastic.co/guide/en/elasticsearch/reference/curr... |
Please provide a description of the function: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
) | [
"\n A query that accepts a query template and a map of key/value pairs to\n fill in template parameters.\n `<http://www.elastic.co/guide/en/elasticsearch/reference/current/search-template.html>`_\n\n :arg index: A list of index names to search, or a string containing a\n comma... |
Please provide a description of the function: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": scrol... | [
"\n Scroll a search request created by specifying the scroll parameter.\n `<http://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-scroll.html>`_\n\n :arg scroll_id: The scroll ID\n :arg body: The scroll ID if not passed by URL or query parameter.\n :arg scr... |
Please provide a description of the function: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,
) | [
"\n Multi termvectors API allows to get multiple termvectors based on an\n index, type and id.\n `<http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-multi-termvectors.html>`_\n\n :arg index: The index in which the document resides.\n :arg body: Define ids, docume... |
Please provide a description of the function: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(
... | [
"\n Create a script in given language with specified ID.\n `<http://www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting.html>`_\n\n :arg id: Script ID\n :arg body: The document\n "
] |
Please provide a description of the function: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
) | [
"\n `<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-template.html>`_\n\n :arg id: The id of the stored search template\n :arg body: The search definition template and its params\n "
] |
Please provide a description of the function: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(in... | [
"\n The /_search/template endpoint allows to use the mustache language to\n pre render search requests, before they are executed and fill existing\n templates with template parameters.\n `<http://www.elastic.co/guide/en/elasticsearch/reference/current/search-template.html>`_\n\n :... |
Please provide a description of the function: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
) | [
"\n The field capabilities API allows to retrieve the capabilities of fields among multiple indices.\n `<http://www.elastic.co/guide/en/elasticsearch/reference/current/search-field-caps.html>`_\n\n :arg index: A list of index names, or a string containing a\n comma-separated list of ... |
Please provide a description of the function: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("_monitori... | [
"\n `<http://www.elastic.co/guide/en/monitoring/current/appendix-api-bulk.html>`_\n\n :arg body: The operation definition and data (action-data pairs),\n separated by newlines\n :arg doc_type: Default document type for items which don't provide one\n :arg interval: Collection ... |
Please provide a description of the function:def add_connection(self, host):
self.hosts.append(host)
self.set_connections(self.hosts) | [
"\n Create a new :class:`~elasticsearch.Connection` instance and add it to the pool.\n\n :arg host: kwargs that will be used to create the instance\n "
] |
Please provide a description of the function: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() | [
"\n Retreive a :class:`~elasticsearch.Connection` instance from the\n :class:`~elasticsearch.ConnectionPool` instance.\n "
] |
Please provide a description of the function: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 e... | [
"\n Obtain a list of nodes from the cluster and create a new connection\n pool using the information retrieved.\n\n To extract the node connection parameters use the ``nodes_to_host_callback``.\n\n :arg initial: flag indicating if this is during startup\n (``sniff_on_start``),... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.