INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
This function generates a 256 jet colormap of HTML - like hex string colors ( e. g. FF88AA )
def generateColorMap(): ''' This function generates a 256 jet colormap of HTML-like hex string colors (e.g. FF88AA) ''' Map = cm.jet(np.arange(256)) stringColors = [] for i in range(Map.shape[0]): rgb = (int(255*Map[i][0]), int(255*Map[i][1]), int(255*Map[i][2])) if (sys.vers...
Distance between two strings
def levenshtein(str1, s2): ''' Distance between two strings ''' N1 = len(str1) N2 = len(s2) stringRange = [range(N1 + 1)] * (N2 + 1) for i in range(N2 + 1): stringRange[i] = range(i,i + N1 + 1) for i in range(0,N2): for j in range(0,N1): if str1[j] == s2[i]: ...
Generates a list of colors based on a list of names ( strings ). Similar strings correspond to similar colors.
def text_list_to_colors(names): ''' Generates a list of colors based on a list of names (strings). Similar strings correspond to similar colors. ''' # STEP A: compute strings distance between all combnations of strings Dnames = np.zeros( (len(names), len(names)) ) for i in range(len(names)): ...
Generates a list of colors based on a list of names ( strings ). Similar strings correspond to similar colors.
def text_list_to_colors_simple(names): ''' Generates a list of colors based on a list of names (strings). Similar strings correspond to similar colors. ''' uNames = list(set(names)) uNames.sort() textToColor = [ uNames.index(n) for n in names ] textToColor = np.array(textToColor) textTo...
Generates a d3js chordial diagram that illustrates similarites
def chordialDiagram(fileStr, SM, Threshold, names, namesCategories): ''' Generates a d3js chordial diagram that illustrates similarites ''' colors = text_list_to_colors_simple(namesCategories) SM2 = SM.copy() SM2 = (SM2 + SM2.T) / 2.0 for i in range(SM2.shape[0]): M = Threshold # ...
This function generates a chordial visualization for the recordings of the provided path. ARGUMENTS: - folder: path of the folder that contains the WAV files to be processed - dimReductionMethod: method used to reduce the dimension of the initial feature space before computing the similarity. - priorKnowledge: if this ...
def visualizeFeaturesFolder(folder, dimReductionMethod, priorKnowledge = "none"): ''' This function generates a chordial visualization for the recordings of the provided path. ARGUMENTS: - folder: path of the folder that contains the WAV files to be processed - dimReductionMethod: ...
Computes zero crossing rate of frame
def stZCR(frame): """Computes zero crossing rate of frame""" count = len(frame) countZ = numpy.sum(numpy.abs(numpy.diff(numpy.sign(frame)))) / 2 return (numpy.float64(countZ) / numpy.float64(count-1.0))
Computes entropy of energy
def stEnergyEntropy(frame, n_short_blocks=10): """Computes entropy of energy""" Eol = numpy.sum(frame ** 2) # total frame energy L = len(frame) sub_win_len = int(numpy.floor(L / n_short_blocks)) if L != sub_win_len * n_short_blocks: frame = frame[0:sub_win_len * n_short_blocks] # ...
Computes spectral centroid of frame ( given abs ( FFT ))
def stSpectralCentroidAndSpread(X, fs): """Computes spectral centroid of frame (given abs(FFT))""" ind = (numpy.arange(1, len(X) + 1)) * (fs/(2.0 * len(X))) Xt = X.copy() Xt = Xt / Xt.max() NUM = numpy.sum(ind * Xt) DEN = numpy.sum(Xt) + eps # Centroid: C = (NUM / DEN) # Spread: ...
Computes the spectral entropy
def stSpectralEntropy(X, n_short_blocks=10): """Computes the spectral entropy""" L = len(X) # number of frame samples Eol = numpy.sum(X ** 2) # total spectral energy sub_win_len = int(numpy.floor(L / n_short_blocks)) # length of sub-frame if L != sub_win_len * n...
Computes the spectral flux feature of the current frame ARGUMENTS: X: the abs ( fft ) of the current frame X_prev: the abs ( fft ) of the previous frame
def stSpectralFlux(X, X_prev): """ Computes the spectral flux feature of the current frame ARGUMENTS: X: the abs(fft) of the current frame X_prev: the abs(fft) of the previous frame """ # compute the spectral flux as the sum of square distances: sumX = numpy.sum...
Computes spectral roll - off
def stSpectralRollOff(X, c, fs): """Computes spectral roll-off""" totalEnergy = numpy.sum(X ** 2) fftLength = len(X) Thres = c*totalEnergy # Ffind the spectral rolloff as the frequency position # where the respective spectral energy is equal to c*totalEnergy CumSum = numpy.cumsum(X ** 2) + ...
Computes harmonic ratio and pitch
def stHarmonic(frame, fs): """ Computes harmonic ratio and pitch """ M = numpy.round(0.016 * fs) - 1 R = numpy.correlate(frame, frame, mode='full') g = R[len(frame)-1] R = R[len(frame):-1] # estimate m0 (as the first zero crossing of R) [a, ] = numpy.nonzero(numpy.diff(numpy.sign(R...
Computes the triangular filterbank for MFCC computation ( used in the stFeatureExtraction function before the stMFCC function call ) This function is taken from the scikits. talkbox library ( MIT Licence ): https:// pypi. python. org/ pypi/ scikits. talkbox
def mfccInitFilterBanks(fs, nfft): """ Computes the triangular filterbank for MFCC computation (used in the stFeatureExtraction function before the stMFCC function call) This function is taken from the scikits.talkbox library (MIT Licence): https://pypi.python.org/pypi/scikits.talkbox """ ...
Computes the MFCCs of a frame given the fft mag
def stMFCC(X, fbank, n_mfcc_feats): """ Computes the MFCCs of a frame, given the fft mag ARGUMENTS: X: fft magnitude abs(FFT) fbank: filter bank (see mfccInitFilterBanks) RETURN ceps: MFCCs (13 element vector) Note: MFCC calculation is, in general, taken fr...
This function initializes the chroma matrices used in the calculation of the chroma features
def stChromaFeaturesInit(nfft, fs): """ This function initializes the chroma matrices used in the calculation of the chroma features """ freqs = numpy.array([((f + 1) * fs) / (2 * nfft) for f in range(nfft)]) Cp = 27.50 nChroma = numpy.round(12.0 * numpy.log2(freqs / Cp)).astype(int) ...
Short - term FFT mag for spectogram estimation: Returns: a numpy array ( nFFT x numOfShortTermWindows ) ARGUMENTS: signal: the input signal samples fs: the sampling freq ( in Hz ) win: the short - term window size ( in samples ) step: the short - term window step ( in samples ) PLOT: flag 1 if results are to be ploted ...
def stChromagram(signal, fs, win, step, PLOT=False): """ Short-term FFT mag for spectogram estimation: Returns: a numpy array (nFFT x numOfShortTermWindows) ARGUMENTS: signal: the input signal samples fs: the sampling freq (in Hz) win: the short-term...
This function extracts an estimate of the beat rate for a musical signal. ARGUMENTS: - st_features: a numpy array ( n_feats x numOfShortTermWindows ) - win_len: window size in seconds RETURNS: - BPM: estimates of beats per minute - Ratio: a confidence measure
def beatExtraction(st_features, win_len, PLOT=False): """ This function extracts an estimate of the beat rate for a musical signal. ARGUMENTS: - st_features: a numpy array (n_feats x numOfShortTermWindows) - win_len: window size in seconds RETURNS: - BPM: estimates o...
Short - term FFT mag for spectogram estimation: Returns: a numpy array ( nFFT x numOfShortTermWindows ) ARGUMENTS: signal: the input signal samples fs: the sampling freq ( in Hz ) win: the short - term window size ( in samples ) step: the short - term window step ( in samples ) PLOT: flag 1 if results are to be ploted ...
def stSpectogram(signal, fs, win, step, PLOT=False): """ Short-term FFT mag for spectogram estimation: Returns: a numpy array (nFFT x numOfShortTermWindows) ARGUMENTS: signal: the input signal samples fs: the sampling freq (in Hz) win: the short-term...
This function implements the shor - term windowing process. For each short - term window a set of features is extracted. This results to a sequence of feature vectors stored in a numpy matrix.
def stFeatureExtraction(signal, fs, win, step): """ This function implements the shor-term windowing process. For each short-term window a set of features is extracted. This results to a sequence of feature vectors, stored in a numpy matrix. ARGUMENTS signal: the input signal samples ...
Mid - term feature extraction
def mtFeatureExtraction(signal, fs, mt_win, mt_step, st_win, st_step): """ Mid-term feature extraction """ mt_win_ratio = int(round(mt_win / st_step)) mt_step_ratio = int(round(mt_step / st_step)) mt_features = [] st_features, f_names = stFeatureExtraction(signal, fs, st_win, st_step) ...
This function extracts the mid - term features of the WAVE files of a particular folder.
def dirWavFeatureExtraction(dirName, mt_win, mt_step, st_win, st_step, compute_beat=False): """ This function extracts the mid-term features of the WAVE files of a particular folder. The resulting feature vector is extracted by long-term averaging the mid-term features. Ther...
Same as dirWavFeatureExtraction but instead of a single dir it takes a list of paths as input and returns a list of feature matrices. EXAMPLE: [ features classNames ] = a. dirsWavFeatureExtraction ( [ audioData/ classSegmentsRec/ noise audioData/ classSegmentsRec/ speech audioData/ classSegmentsRec/ brush - teeth audio...
def dirsWavFeatureExtraction(dirNames, mt_win, mt_step, st_win, st_step, compute_beat=False): ''' Same as dirWavFeatureExtraction, but instead of a single dir it takes a list of paths as input and returns a list of feature matrices. EXAMPLE: [features, classNames] = a.dirsWavFeatureExtrac...
This function extracts the mid - term features of the WAVE files of a particular folder without averaging each file.
def dirWavFeatureExtractionNoAveraging(dirName, mt_win, mt_step, st_win, st_step): """ This function extracts the mid-term features of the WAVE files of a particular folder without averaging each file. ARGUMENTS: - dirName: the path of the WAVE directory - mt_win, mt_step: m...
This function is used as a wrapper to: a ) read the content of a WAV file b ) perform mid - term feature extraction on that signal c ) write the mid - term feature sequences to a numpy file
def mtFeatureExtractionToFile(fileName, midTermSize, midTermStep, shortTermSize, shortTermStep, outPutFile, storeStFeatures=False, storeToCSV=False, PLOT=False): """ This function is used as a wrapper to: a) read the content of a WAV file b) perform mid-term feature extract...
[ float ] 市值
def market_value(self): """ [float] 市值 """ return sum(position.market_value for position in six.itervalues(self._positions))
[ float ] 总费用
def transaction_cost(self): """ [float] 总费用 """ return sum(position.transaction_cost for position in six.itervalues(self._positions))
买入开仓。
def buy_open(id_or_ins, amount, price=None, style=None): """ 买入开仓。 :param id_or_ins: 下单标的物 :type id_or_ins: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`] :param int amount: 下单手数 :param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要用于简化 `style` 参数。 ...
平卖仓
def buy_close(id_or_ins, amount, price=None, style=None, close_today=False): """ 平卖仓 :param id_or_ins: 下单标的物 :type id_or_ins: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`] :param int amount: 下单手数 :param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要...
卖出开仓
def sell_open(id_or_ins, amount, price=None, style=None): """ 卖出开仓 :param id_or_ins: 下单标的物 :type id_or_ins: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`] :param int amount: 下单手数 :param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主要用于简化 `style` 参数。 ...
平买仓
def sell_close(id_or_ins, amount, price=None, style=None, close_today=False): """ 平买仓 :param id_or_ins: 下单标的物 :type id_or_ins: :class:`~Instrument` object | `str` | List[:class:`~Instrument`] | List[`str`] :param int amount: 下单手数 :param float price: 下单价格,默认为None,表示 :class:`~MarketOrder`, 此参数主...
获取某一期货品种在策略当前日期的可交易合约order_book_id列表。按照到期月份,下标从小到大排列,返回列表中第一个合约对应的就是该品种的近月合约。
def get_future_contracts(underlying_symbol): """ 获取某一期货品种在策略当前日期的可交易合约order_book_id列表。按照到期月份,下标从小到大排列,返回列表中第一个合约对应的就是该品种的近月合约。 :param str underlying_symbol: 期货合约品种,例如沪深300股指期货为'IF' :return: list[`str`] :example: 获取某一天的主力合约代码(策略当前日期是20161201): .. code-block:: python [In...
[ int ] 订单数量
def quantity(self): """ [int] 订单数量 """ if np.isnan(self._quantity): raise RuntimeError("Quantity of order {} is not supposed to be nan.".format(self.order_id)) return self._quantity
[ int ] 订单已成交数量
def filled_quantity(self): """ [int] 订单已成交数量 """ if np.isnan(self._filled_quantity): raise RuntimeError("Filled quantity of order {} is not supposed to be nan.".format(self.order_id)) return self._filled_quantity
[ float ] 冻结价格
def frozen_price(self): """ [float] 冻结价格 """ if np.isnan(self._frozen_price): raise RuntimeError("Frozen price of order {} is not supposed to be nan.".format(self.order_id)) return self._frozen_price
[ datetime. datetime ] 当前快照数据的时间戳
def datetime(self): """ [datetime.datetime] 当前快照数据的时间戳 """ try: dt = self._tick_dict['datetime'] except (KeyError, ValueError): return datetime.datetime.min else: if not isinstance(dt, datetime.datetime): if dt > 1000000...
[ float ] 获得该持仓的实时市场价值在股票投资组合价值中所占比例,取值范围 [ 0 1 ]
def value_percent(self): """ [float] 获得该持仓的实时市场价值在股票投资组合价值中所占比例,取值范围[0, 1] """ accounts = Environment.get_instance().portfolio.accounts if DEFAULT_ACCOUNT_TYPE.STOCK.name not in accounts: return 0 total_value = accounts[DEFAULT_ACCOUNT_TYPE.STOCK.name].total_v...
判断合约是否过期
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() > env.config.bas...
[ 已弃用 ]
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
[ float ] 交易盈亏,策略在当前交易日产生的盈亏中来源于当日成交的部分
def trading_pnl(self): """ [float] 交易盈亏,策略在当前交易日产生的盈亏中来源于当日成交的部分 """ last_price = self._data_proxy.get_last_price(self._order_book_id) return self._contract_multiplier * (self._trade_quantity * last_price - self._trade_cost)
[ float ] 昨仓盈亏,策略在当前交易日产生的盈亏中来源于昨仓的部分
def position_pnl(self): """ [float] 昨仓盈亏,策略在当前交易日产生的盈亏中来源于昨仓的部分 """ 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 = s...
注册事件
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)
[ float ] 实时净值
def unit_net_value(self): """ [float] 实时净值 """ if self._units == 0: return np.nan return self.total_value / self._units
[ float ] 当前最新一天的日收益
def daily_returns(self): """ [float] 当前最新一天的日收益 """ 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
[ float ] 总权益
def total_value(self): """ [float]总权益 """ return sum(account.total_value for account in six.itervalues(self._accounts))
[ dict ] 持仓
def positions(self): """ [dict] 持仓 """ if self._mixed_positions is None: self._mixed_positions = MixedPositions(self._accounts) return self._mixed_positions
[ float ] 可用资金
def cash(self): """ [float] 可用资金 """ return sum(account.cash for account in six.itervalues(self._accounts))
[ float ] 市值
def market_value(self): """ [float] 市值 """ return sum(account.market_value for account in six.itervalues(self._accounts))
[ float ] 买方向当日持仓盈亏
def buy_holding_pnl(self): """ [float] 买方向当日持仓盈亏 """ return (self.last_price - self.buy_avg_holding_price) * self.buy_quantity * self.contract_multiplier
[ float ] 卖方向当日持仓盈亏
def sell_holding_pnl(self): """ [float] 卖方向当日持仓盈亏 """ return (self.sell_avg_holding_price - self.last_price) * self.sell_quantity * self.contract_multiplier
[ float ] 买方向累计盈亏
def buy_pnl(self): """ [float] 买方向累计盈亏 """ return (self.last_price - self._buy_avg_open_price) * self.buy_quantity * self.contract_multiplier
[ float ] 卖方向累计盈亏
def sell_pnl(self): """ [float] 卖方向累计盈亏 """ return (self._sell_avg_open_price - self.last_price) * self.sell_quantity * self.contract_multiplier
[ 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...
应用成交,并计算交易产生的现金变动。
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...
应用平仓,并计算平仓盈亏
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 则说明这不是第一笔trade 此时,直接cost_money - commission即可 4....
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_...
通用下单函数,策略可以通过该函数自由选择参数下单。
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 ...
撤单
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这一个股票了。
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数据的数量。
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...
取消订阅合约行情。取消订阅会导致合约池内合约的减少,如果当前合约池中没有任何合约,则策略直接退出。
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(...
获取某个国家市场指定日期的收益率曲线水平。
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会自动跳过停牌数据。
def history_bars( order_book_id, bar_count, frequency, fields=None, skip_suspended=True, include_now=False, adjust_type="pre", ): """ 获取指定合约的历史行情,同时支持日以及分钟历史数据。不能在init中调用。 注意,该API会自动跳过停牌数据。 日回测获取分钟历史数据:不支持 日回测获取日历史数据 ========================= ========================...
获取某个国家市场的所有合约信息。使用者可以通过这一方法很快地对合约信息有一个快速了解,目前仅支持中国市场。
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表示。
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))
获取历史数据
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)。
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)。
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...
使用想要花费的金钱买入/ 卖出股票,而不是买入/ 卖出想要的股数,正数代表买入,负数代表卖出。股票的股数总是会被调整成对应的100的倍数(在A中国A股市场1手是100股)。如果资金不足,该API将不会创建发送订单。
def order_value(id_or_ins, cash_amount, price=None, style=None): """ 使用想要花费的金钱买入/卖出股票,而不是买入/卖出想要的股数,正数代表买入,负数代表卖出。股票的股数总是会被调整成对应的100的倍数(在A中国A股市场1手是100股)。如果资金不足,该API将不会创建发送订单。 需要注意: 当您提交一个买单时,cash_amount 代表的含义是您希望买入股票消耗的金额(包含税费),最终买入的股数不仅和发单的价格有关,还和税费相关的参数设置有关。 当您提交一个卖单时,cash_amount 代表的意义是您希望卖出股票的总价...
发送一个花费价值等于目前投资组合(市场价值和目前现金的总和)一定百分比现金的买/ 卖单,正数代表买,负数代表卖。股票的股数总是会被调整成对应的一手的股票数的倍数(1手是100股)。百分比是一个小数,并且小于或等于1(< = 100%),0. 5表示的是50%. 需要注意,如果资金不足,该API将不会创建发送订单。
def order_percent(id_or_ins, percent, price=None, style=None): """ 发送一个花费价值等于目前投资组合(市场价值和目前现金的总和)一定百分比现金的买/卖单,正数代表买,负数代表卖。股票的股数总是会被调整成对应的一手的股票数的倍数(1手是100股)。百分比是一个小数,并且小于或等于1(<=100%),0.5表示的是50%.需要注意,如果资金不足,该API将不会创建发送订单。 需要注意: 发送买单时,percent 代表的是期望买入股票消耗的金额(包含税费)占投资组合总权益的比例。 发送卖单时,percent 代表的是期望卖出的股票...
买入/ 卖出并且自动调整该证券的仓位到一个目标价值。 加仓时,cash_amount 代表现有持仓的价值加上即将花费(包含税费)的现金的总价值。 减仓时,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...
买入/ 卖出证券以自动调整该证券的仓位到占有一个目标价值。
def order_target_percent(id_or_ins, percent, price=None, style=None): """ 买入/卖出证券以自动调整该证券的仓位到占有一个目标价值。 加仓时,percent 代表证券已有持仓的价值加上即将花费的现金(包含税费)的总值占当前投资组合总价值的比例。 减仓时,percent 代表证券将被调整到的目标价至占当前投资组合总价值的比例。 其实我们需要计算一个position_to_adjust (即应该调整的仓位) `position_to_adjust = target_position - current_posit...
判断某只股票是否全天停牌。
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)