Search is not available for this dataset
text stringlengths 75 104k |
|---|
def _build_session(self, name, start_info, end_info):
"""Builds a session object."""
assert start_info is not None
result = api_pb2.Session(
name=name,
start_time_secs=start_info.start_time_secs,
model_uri=start_info.model_uri,
metric_values=self._build_session_metric_values... |
def _build_session_metric_values(self, session_name):
"""Builds the session metric values."""
# result is a list of api_pb2.MetricValue instances.
result = []
metric_infos = self._experiment.metric_infos
for metric_info in metric_infos:
metric_name = metric_info.name
try:
metric... |
def _aggregate_metrics(self, session_group):
"""Sets the metrics of the group based on aggregation_type."""
if (self._request.aggregation_type == api_pb2.AGGREGATION_AVG or
self._request.aggregation_type == api_pb2.AGGREGATION_UNSET):
_set_avg_session_metrics(session_group)
elif self._request... |
def _sort(self, session_groups):
"""Sorts 'session_groups' in place according to _request.col_params."""
# Sort by session_group name so we have a deterministic order.
session_groups.sort(key=operator.attrgetter('name'))
# Sort by lexicographical order of the _request.col_params whose order
# is no... |
def recordAnalyzeAudio(duration, outputWavFile, midTermBufferSizeSec, modelName, modelType):
'''
recordAnalyzeAudio(duration, outputWavFile, midTermBufferSizeSec, modelName, modelType)
This function is used to record and analyze audio segments, in a fix window basis.
ARGUMENTS:
- duration total recording dura... |
def annotation2files(wavFile, csvFile):
'''
Break an audio stream to segments of interest,
defined by a csv file
- wavFile: path to input wavfile
- csvFile: path to csvFile of segment limits
Input CSV file must be of the format <T1>\t<T2>\t<Label>
... |
def convertDirMP3ToWav(dirName, Fs, nC, useMp3TagsAsName = False):
'''
This function converts the MP3 files stored in a folder to WAV. If required, the output names of the WAV files are based on MP3 tags, otherwise the same names are used.
ARGUMENTS:
- dirName: the path of the folder where the MP3s... |
def convertFsDirWavToWav(dirName, Fs, nC):
'''
This function converts the WAV files stored in a folder to WAV using a different sampling freq and number of channels.
ARGUMENTS:
- dirName: the path of the folder where the WAVs are stored
- Fs: the sampling rate of the generated WAV fil... |
def readAudioFile(path):
'''
This function returns a numpy array that stores the audio samples of a specified WAV of AIFF file
'''
extension = os.path.splitext(path)[1]
try:
#if extension.lower() == '.wav':
#[Fs, x] = wavfile.read(path)
if extension.lower() == '.aif' or ... |
def stereo2mono(x):
'''
This function converts the input signal
(stored in a numpy array) to MONO (if it is STEREO)
'''
if isinstance(x, int):
return -1
if x.ndim==1:
return x
elif x.ndim==2:
if x.shape[1]==1:
return x.flatten()
else:
i... |
def selfSimilarityMatrix(featureVectors):
'''
This function computes the self-similarity matrix for a sequence
of feature vectors.
ARGUMENTS:
- featureVectors: a numpy matrix (nDims x nVectors) whose i-th column
corresponds to the i-th feature vector
RETURNS:
... |
def flags2segs(flags, window):
'''
ARGUMENTS:
- flags: a sequence of class flags (per time window)
- window: window duration (in seconds)
RETURNS:
- segs: a sequence of segment's limits: segs[i,0] is start and
segs[i,1] are start and end point of segment i
... |
def segs2flags(seg_start, seg_end, seg_label, win_size):
'''
This function converts segment endpoints and respective segment
labels to fix-sized class labels.
ARGUMENTS:
- seg_start: segment start points (in seconds)
- seg_end: segment endpoints (in seconds)
- seg_label: segment ... |
def computePreRec(cm, class_names):
'''
This function computes the precision, recall and f1 measures,
given a confusion matrix
'''
n_classes = cm.shape[0]
if len(class_names) != n_classes:
print("Error in computePreRec! Confusion matrix and class_names "
"list must be of th... |
def readSegmentGT(gt_file):
'''
This function reads a segmentation ground truth file, following a simple CSV format with the following columns:
<segment start>,<segment end>,<class label>
ARGUMENTS:
- gt_file: the path of the CSV segment file
RETURNS:
- seg_start: a numpy array ... |
def plotSegmentationResults(flags_ind, flags_ind_gt, class_names, mt_step, ONLY_EVALUATE=False):
'''
This function plots statistics on the classification-segmentation results produced either by the fix-sized supervised method or the HMM method.
It also computes the overall accuracy achieved by the respectiv... |
def trainHMM_computeStatistics(features, labels):
'''
This function computes the statistics used to train an HMM joint segmentation-classification model
using a sequence of sequential features and respective labels
ARGUMENTS:
- features: a numpy matrix of feature vectors (numOfDimensions x n_wi... |
def trainHMM_fromFile(wav_file, gt_file, hmm_model_name, mt_win, mt_step):
'''
This function trains a HMM model for segmentation-classification using a single annotated audio file
ARGUMENTS:
- wav_file: the path of the audio filename
- gt_file: the path of the ground truth filename
... |
def trainHMM_fromDir(dirPath, hmm_model_name, mt_win, mt_step):
'''
This function trains a HMM model for segmentation-classification using
a where WAV files and .segment (ground-truth files) are stored
ARGUMENTS:
- dirPath: the path of the data diretory
- hmm_model_name: the name of ... |
def mtFileClassification(input_file, model_name, model_type,
plot_results=False, gt_file=""):
'''
This function performs mid-term classification of an audio stream.
Towards this end, supervised knowledge is used, i.e. a pre-trained classifier.
ARGUMENTS:
- input_file: ... |
def silenceRemoval(x, fs, st_win, st_step, smoothWindow=0.5, weight=0.5, plot=False):
'''
Event Detection (silence removal)
ARGUMENTS:
- x: the input audio signal
- fs: sampling freq
- st_win, st_step: window size and step in seconds
- smoo... |
def speakerDiarization(filename, n_speakers, mt_size=2.0, mt_step=0.2,
st_win=0.05, lda_dim=35, plot_res=False):
'''
ARGUMENTS:
- filename: the name of the WAV file to be analyzed
- n_speakers the number of speakers (clusters) in the recording (<=0 for unknown)
... |
def speakerDiarizationEvaluateScript(folder_name, ldas):
'''
This function prints the cluster purity and speaker purity for
each WAV file stored in a provided directory (.SEGMENT files
are needed as ground-truth)
ARGUMENTS:
- folder_name: the full path of the folder ... |
def musicThumbnailing(x, fs, short_term_size=1.0, short_term_step=0.5,
thumb_size=10.0, limit_1 = 0, limit_2 = 1):
'''
This function detects instances of the most representative part of a
music recording, also called "music thumbnails".
A technique similar to the one proposed in [... |
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... |
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]:
... |
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)):
... |
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... |
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
# ... |
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: ... |
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)) |
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]
# ... |
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:
... |
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... |
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... |
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) + ... |
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... |
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
"""
... |
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... |
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)
... |
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... |
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... |
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... |
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
... |
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)
... |
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... |
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... |
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... |
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... |
def market_value(self):
"""
[float] 市值
"""
return sum(position.market_value for position in six.itervalues(self._positions)) |
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`, 此参数主... |
def get_future_contracts(underlying_symbol):
"""
获取某一期货品种在策略当前日期的可交易合约order_book_id列表。按照到期月份,下标从小到大排列,返回列表中第一个合约对应的就是该品种的近月合约。
:param str underlying_symbol: 期货合约品种,例如沪深300股指期货为'IF'
:return: list[`str`]
:example:
获取某一天的主力合约代码(策略当前日期是20161201):
.. code-block:: python
[In... |
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 |
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 |
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 |
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... |
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 |
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) |
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) |
def unit_net_value(self):
"""
[float] 实时净值
"""
if self._units == 0:
return np.nan
return self.total_value / self._units |
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 |
def total_value(self):
"""
[float]总权益
"""
return sum(account.total_value for account in six.itervalues(self._accounts)) |
def positions(self):
"""
[dict] 持仓
"""
if self._mixed_positions is None:
self._mixed_positions = MixedPositions(self._accounts)
return self._mixed_positions |
def cash(self):
"""
[float] 可用资金
"""
return sum(account.cash for account in six.itervalues(self._accounts)) |
def market_value(self):
"""
[float] 市值
"""
return sum(account.market_value for account in six.itervalues(self._accounts)) |
def buy_holding_pnl(self):
"""
[float] 买方向当日持仓盈亏
"""
return (self.last_price - self.buy_avg_holding_price) * self.buy_quantity * self.contract_multiplier |
def sell_holding_pnl(self):
"""
[float] 卖方向当日持仓盈亏
"""
return (self.sell_avg_holding_price - self.last_price) * self.sell_quantity * self.contract_multiplier |
def buy_pnl(self):
"""
[float] 买方向累计盈亏
"""
return (self.last_price - self._buy_avg_open_price) * self.buy_quantity * self.contract_multiplier |
def sell_pnl(self):
"""
[float] 卖方向累计盈亏
"""
return (self._sell_avg_open_price - self.last_price) * self.sell_quantity * self.contract_multiplier |
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) |
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) |
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]) |
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]) |
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 |
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
... |
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... |
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... |
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... |
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_... |
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... |
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... |
def status(self):
"""
[str] 合约状态。’Active’ - 正常上市, ‘Delisted’ - 终止上市, ‘TemporarySuspended’ - 暂停上市,
‘PreIPO’ - 发行配售期间, ‘FailIPO’ - 发行失败(股票专用)
"""
try:
return self.__dict__["status"]
except (KeyError, ValueError):
raise AttributeError(
... |
def special_type(self):
"""
[str] 特别处理状态。’Normal’ - 正常上市, ‘ST’ - ST处理, ‘StarST’ - *ST代表该股票正在接受退市警告,
‘PT’ - 代表该股票连续3年收入为负,将被暂停交易, ‘Other’ - 其他(股票专用)
"""
try:
return self.__dict__["special_type"]
except (KeyError, ValueError):
raise AttributeError(
... |
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... |
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)
... |
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={})... |
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... |
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... |
def settlement_method(self):
"""
[str] 交割方式,’CashSettlementRequired’ - 现金交割, ‘PhysicalSettlementRequired’ - 实物交割(期货专用)
"""
try:
return self.__dict__["settlement_method"]
except (KeyError, ValueError):
raise AttributeError(
"Instrument(order... |
def listing(self):
"""
[bool] 该合约当前日期是否在交易
"""
now = Environment.get_instance().calendar_dt
return self.listed_date <= now <= self.de_listed_date |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.