Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def _split_generators(self, dl_manager):
root_url = "http://images.cocodataset.org/"
urls = {
# Train/validation set
"train_images": "zips/train2014.zip",
"val_images": "zips/val2014.zip",
"trainval_annotations": "annotations/anno... | [
"Returns SplitGenerators."
] |
Please provide a description of the function:def _generate_examples(
self, image_dir, annotation_dir, split_type, has_annotation=True):
if has_annotation:
instance_filename = "instances_{}.json"
else:
instance_filename = "image_info_{}.json"
# Load the label names and images
inst... | [
"Generate examples as dicts.\n\n Args:\n image_dir: `str`, directory containing the images\n annotation_dir: `str`, directory containing\n split_type: `str`, <split_name><year> (ex: train2014)\n has_annotation: `bool`, when False (for the testing set), the annotations\n are not recorde... |
Please provide a description of the function:def str2ints(self, str_value):
if not self._encoder:
raise ValueError(
"Text.str2ints is not available because encoder hasn't been defined.")
return self._encoder.encode(str_value) | [
"Conversion string => encoded list[int]."
] |
Please provide a description of the function:def ints2str(self, int_values):
if not self._encoder:
raise ValueError(
"Text.ints2str is not available because encoder hasn't been defined.")
return self._encoder.decode(int_values) | [
"Conversion list[int] => decoded string."
] |
Please provide a description of the function:def maybe_build_from_corpus(self, corpus_generator, **kwargs):
if self._encoder_cls is not text_lib.SubwordTextEncoder:
return
if self.encoder:
return
vocab_size = self._encoder_config.vocab_size
self.encoder = text_lib.SubwordTextEncoder.bu... | [
"Call SubwordTextEncoder.build_from_corpus is encoder_cls is such."
] |
Please provide a description of the function:def sharded_filenames(filename_prefix, num_shards):
shard_suffix = "%05d-of-%05d"
return [
"%s-%s" % (filename_prefix, shard_suffix % (i, num_shards))
for i in range(num_shards)
] | [
"Sharded filenames given prefix and number of shards."
] |
Please provide a description of the function:def _walk_omniglot_dir(directory):
directory = os.path.join(directory, tf.io.gfile.listdir(directory)[0])
alphabets = sorted(tf.io.gfile.listdir(directory))
for alphabet in alphabets:
alphabet_dir = os.path.join(directory, alphabet)
characters = sorted(tf.io... | [
"Walk an Omniglot directory and yield examples."
] |
Please provide a description of the function:def _get_names(dirs):
alphabets = set()
label_names = {}
for d in dirs:
for example in _walk_omniglot_dir(d):
alphabet, alphabet_char_id, label, _ = example
alphabets.add(alphabet)
label_name = "%s_%d" % (alphabet, alphabet_char_id)
if la... | [
"Get alphabet and label names, union across all dirs."
] |
Please provide a description of the function:def size_str(size_in_bytes):
if not size_in_bytes:
return "?? GiB"
size_in_bytes = float(size_in_bytes)
for (name, size_bytes) in _NAME_LIST:
value = size_in_bytes / size_bytes
if value >= 1.0:
return "{:.2f} {}".format(value, name)
return "{} {... | [
"Returns a human readable size string.\n\n If size_in_bytes is None, then returns \"?? GiB\".\n\n For example `size_str(1.5 * tfds.units.GiB) == \"1.50 GiB\"`.\n\n Args:\n size_in_bytes: `int` or `None`, the size, in bytes, that we want to\n format as a human-readable size string.\n "
] |
Please provide a description of the function:def tqdm(self):
async_tqdm = utils.async_tqdm
with async_tqdm(total=0, desc='Dl Completed...', unit=' url') as pbar_url:
with async_tqdm(total=0, desc='Dl Size...', unit=' MiB') as pbar_dl_size:
self._pbar_url = pbar_url
self._pbar_dl_size ... | [
"Add a progression bar for the current download."
] |
Please provide a description of the function:def download(self, url, destination_path):
self._pbar_url.update_total(1)
future = self._executor.submit(self._sync_download, url, destination_path)
return promise.Promise.resolve(future) | [
"Download url to given path.\n\n Returns Promise -> sha256 of downloaded file.\n\n Args:\n url: address of resource to download.\n destination_path: `str`, path to directory where to download the resource.\n\n Returns:\n Promise obj -> (`str`, int): (downloaded object checksum, size in bytes... |
Please provide a description of the function:def _sync_kaggle_download(self, kaggle_url, destination_path):
kaggle_file = kaggle.KaggleFile.from_url(kaggle_url)
downloader = self.kaggle_downloader(kaggle_file.competition)
filepath = downloader.download_file(kaggle_file.filename, destination_path)
... | [
"Download with Kaggle API."
] |
Please provide a description of the function:def _get_drive_url(self, url, session):
response = session.get(url, stream=True)
if response.status_code != 200:
raise DownloadError(
'Failed to get url %s. HTTP code: %d.' % (url, response.status_code))
for k, v in response.cookies.items():
... | [
"Returns url, possibly with confirmation token."
] |
Please provide a description of the function:def _sync_download(self, url, destination_path):
proxies = {
'http': os.environ.get('TFDS_HTTP_PROXY', None),
'https': os.environ.get('TFDS_HTTPS_PROXY', None),
'ftp': os.environ.get('TFDS_FTP_PROXY', None)
}
if kaggle.KaggleFile.is_k... | [
"Synchronous version of `download` method."
] |
Please provide a description of the function:def _resize_image_if_necessary(image_fobj, target_pixels=None):
if target_pixels is None:
return image_fobj
cv2 = tfds.core.lazy_imports.cv2
# Decode image using OpenCV2.
image = cv2.imdecode(
np.fromstring(image_fobj.read(), dtype=np.uint8), flags=3)
... | [
"Resize an image to have (roughly) the given number of target pixels.\n\n Args:\n image_fobj: File object containing the original image.\n target_pixels: If given, number of pixels that the image must have.\n\n Returns:\n A file object.\n "
] |
Please provide a description of the function:def _generate_examples(self, images_dir_path, csv_path=None, csv_usage=None):
if csv_path:
with tf.io.gfile.GFile(csv_path) as csv_f:
reader = csv.DictReader(csv_f)
data = [(row["image"], int(row["level"]))
for row in reader
... | [
"Yields Example instances from given CSV.\n\n Args:\n images_dir_path: path to dir in which images are stored.\n csv_path: optional, path to csv file with two columns: name of image and\n label. If not provided, just scan image directory, don't set labels.\n csv_usage: optional, subset of e... |
Please provide a description of the function:def _slice_split_info_to_instruction_dicts(self, list_sliced_split_info):
instruction_dicts = []
for sliced_split_info in list_sliced_split_info:
mask = splits_lib.slice_to_percent_mask(sliced_split_info.slice_value)
# Compute filenames from the giv... | [
"Return the list of files and reading mask of the files to read."
] |
Please provide a description of the function:def _build_split_filenames(self, split_info_list):
filenames = []
for split_info in split_info_list:
filenames.extend(naming.filepaths_for_dataset_split(
dataset_name=self.name,
split=split_info.name,
num_shards=split_info.nu... | [
"Construct the split filenames associated with the split info.\n\n The filenames correspond to the pre-processed datasets files present in\n the root directory of the dataset.\n\n Args:\n split_info_list: (list[SplitInfo]) List of split from which generate the\n filenames\n\n Returns:\n ... |
Please provide a description of the function:def _generate_examples(self, data_path):
with tf.io.gfile.GFile(data_path, "rb") as fp:
images = np.load(fp)
images = np.transpose(images, (1, 0, 2, 3))
images = np.expand_dims(images, axis=-1)
for sequence in images:
yield dict(image_sequenc... | [
"Generate MovingMnist sequences.\n\n Args:\n data_path (str): Path to the data file\n\n Yields:\n 20 x 64 x 64 x 1 uint8 numpy arrays\n "
] |
Please provide a description of the function:def _parse_single_video(self, example_proto):
context_features = {
"game_duration_loops": tf.io.FixedLenFeature([1], tf.int64),
"game_duration_seconds": tf.io.FixedLenFeature([1], tf.float32),
"n_steps": tf.io.FixedLenFeature([1], tf.int64),
... | [
"Parses single video from the input tfrecords.\n\n Args:\n example_proto: tfExample proto with a single video.\n\n Returns:\n dict with all frames, positions and actions.\n "
] |
Please provide a description of the function:def _generate_examples(self, filepath):
# Simultaneously iterating through the different data sets in the hdf5
# file is >100x slower and the data set is small (26.7MB). Hence, we first
# load everything into memory before yielding the samples.
image_arr... | [
"Generates examples for the dSprites data set.\n\n Args:\n filepath: path to the dSprites hdf5 file.\n\n Yields:\n Dictionaries with images, latent classes, and latent values.\n "
] |
Please provide a description of the function:def _split_generators(self, dl_manager):
# Download images and annotations that come in separate archives.
# Note, that the extension of archives is .tar.gz even though the actual
# archives format is uncompressed tar.
dl_paths = dl_manager.download_and_... | [
"Returns splits."
] |
Please provide a description of the function:def _load_objects(csv_paths, csv_positions, prefix):
logging.info('Loading CSVs %s from positions %s with prefix %s',
csv_paths, csv_positions, prefix)
objects = collections.defaultdict(list)
for i, labels_path in enumerate(csv_paths):
with tf.io.... | [
"Returns objects listed within given CSV files."
] |
Please provide a description of the function:def _load_bboxes(csv_path, csv_positions, prefix):
logging.info('Loading CSVs %s from positions %s with prefix %s',
csv_path, csv_positions, prefix)
boxes = collections.defaultdict(list)
with tf.io.gfile.GFile(csv_path) as csv_f:
if csv_positions[... | [
"Returns bounded boxes listed within given CSV file."
] |
Please provide a description of the function:def _split_generators(self, dl_manager):
paths = dl_manager.download_and_extract(_URLS)
# Load labels from CSVs:
def load(names):
csv_positions = [0] * len(names)
return functools.partial(_load_objects, [paths[name] for name in names],
... | [
"Returns SplitGenerators."
] |
Please provide a description of the function:def _generate_examples(self, archive_paths, objects_getter, bboxes_getter,
prefixes=None):
trainable_classes = set(
self.info.features['objects_trainable']['label'].names)
for i, archive_path in enumerate(archive_paths):
pr... | [
"Yields examples."
] |
Please provide a description of the function:def _generate_examples(self, archive, directory):
reg = re.compile(os.path.join("^%s" % directory, "(?P<label>neg|pos)", ""))
for path, imdb_f in archive:
res = reg.match(path)
if not res:
continue
text = imdb_f.read().strip()
yie... | [
"Generate IMDB examples."
] |
Please provide a description of the function:def _get_url_hashes(path):
urls = _read_text_file(path)
def url_hash(u):
h = hashlib.sha1()
try:
u = u.encode('utf-8')
except UnicodeDecodeError:
logging.error('Cannot hash url: %s', u)
h.update(u)
return h.hexdigest()
return {url_has... | [
"Get hashes of urls in file."
] |
Please provide a description of the function:def _find_files(dl_paths, publisher, url_dict):
if publisher == 'cnn':
top_dir = os.path.join(dl_paths['cnn_stories'], 'cnn', 'stories')
elif publisher == 'dm':
top_dir = os.path.join(dl_paths['dm_stories'], 'dailymail', 'stories')
else:
logging.fatal('U... | [
"Find files corresponding to urls."
] |
Please provide a description of the function:def _subset_filenames(dl_paths, split):
assert isinstance(dl_paths, dict), dl_paths
# Get filenames for a split.
if split == tfds.Split.TRAIN:
urls = _get_url_hashes(dl_paths['train_urls'])
elif split == tfds.Split.VALIDATION:
urls = _get_url_hashes(dl_pat... | [
"Get filenames for a particular split."
] |
Please provide a description of the function:def _get_art_abs(story_file):
# Based on https://github.com/abisee/cnn-dailymail/blob/master/
# make_datafiles.py
lines = _read_text_file(story_file)
# Lowercase everything
lines = [line.lower() for line in lines]
# Put periods on the ends of lines that... | [
"Get abstract (highlights) and article from a story file path.",
"Adds a period to a line that is missing a period."
] |
Please provide a description of the function:def exporter(directory, method, datasets):
if method.lower() == 'json':
# Convert json_dict to a JSON styled string
json_string = json.dumps(datasets, indent=4)
savefile = open('{}/exported.json'.format(directory), 'w+')
savefile.writ... | [
"Export the results."
] |
Please provide a description of the function:def time_machine(host, mode):
now = datetime.datetime.now()
to = str(now.year) + str(now.day) + str(now.month)
if now.month > 6:
fro = str(now.year) + str(now.day) + str(now.month - 6)
else:
fro = str(now.year - 1) + str(now.day) + str(now.mont... | [
"Query archive.org."
] |
Please provide a description of the function:def zap(input_url, archive, domain, host, internal, robots, proxies):
if archive:
print('%s Fetching URLs from archive.org' % run)
if False:
archived_urls = time_machine(domain, 'domain')
else:
archived_urls = time_mac... | [
"Extract links from robots.txt and sitemap.xml."
] |
Please provide a description of the function:def requester(
url,
main_url=None,
delay=0,
cook=None,
headers=None,
timeout=10,
host=None,
proxies=[None],
user_agents=[None],
failed=None,
processed=None
):
cook = cook or ... | [
"Handle the requests and return the response body.",
"Default request"
] |
Please provide a description of the function:def intel_extractor(url, response):
for rintel in rintels:
res = re.sub(r'<(script).*?</\1>(?s)', '', response)
res = re.sub(r'<[^<]+?>', '', res)
matches = rintel[0].findall(res)
if matches:
for match in matches:
... | [
"Extract intel from the response body."
] |
Please provide a description of the function:def js_extractor(response):
# Extract .js files
matches = rscript.findall(response)
for match in matches:
match = match[2].replace('\'', '').replace('"', '')
verb('JS file', match)
bad_scripts.add(match) | [
"Extract js files from the response body"
] |
Please provide a description of the function:def extractor(url):
response = requester(url, main_url, delay, cook, headers, timeout, host, proxies, user_agents, failed, processed)
if clone:
mirror(url, response)
matches = rhref.findall(response)
for link in matches:
# Remove e... | [
"Extract details from the response body."
] |
Please provide a description of the function:def jscanner(url):
response = requester(url, main_url, delay, cook, headers, timeout, host, proxies, user_agents, failed, processed)
# Extract URLs/endpoints
matches = rendpoint.findall(response)
# Iterate over the matches, match is a tuple
for... | [
"Extract endpoints from JavaScript code."
] |
Please provide a description of the function:def updater():
print('%s Checking for updates' % run)
# Changes must be separated by ;
changes = '''major bug fixes;removed ninja mode;dropped python < 3.2 support;fixed unicode output;proxy support;more intels'''
latest_commit = requester('https://raw.g... | [
"Update the current installation.\n\n git clones the latest version and merges it with the current directory.\n "
] |
Please provide a description of the function:def find_subdomains(domain):
result = set()
response = get('https://findsubdomains.com/subdomains-of/' + domain).text
matches = findall(r'(?s)<div class="domains js-domain-name">(.*?)</div>', response)
for match in matches:
result.add(match.repla... | [
"Find subdomains according to the TLD."
] |
Please provide a description of the function:def flash(function, links, thread_count):
# Convert links (set) to list
links = list(links)
threadpool = concurrent.futures.ThreadPoolExecutor(
max_workers=thread_count)
futures = (threadpool.submit(function, link) for link in links)
for ... | [
"Process the URLs and uses a threadpool to execute a function."
] |
Please provide a description of the function:def regxy(pattern, response, supress_regex, custom):
try:
matches = re.findall(r'%s' % pattern, response)
for match in matches:
verb('Custom regex', match)
custom.add(match)
except:
supress_regex = True | [
"Extract a string based on regex pattern supplied by user."
] |
Please provide a description of the function:def is_link(url, processed, files):
if url not in processed:
is_file = url.endswith(BAD_TYPES)
if is_file:
files.add(url)
return False
return True
return False | [
"\n Determine whether or not a link should be crawled\n A url should not be crawled if it\n - Is a file\n - Has already been crawled\n\n Args:\n url: str Url to be processed\n processed: list[str] List of urls that have already been crawled\n\n Returns:\n bool If `url`... |
Please provide a description of the function:def remove_regex(urls, regex):
if not regex:
return urls
# To avoid iterating over the characters of a string
if not isinstance(urls, (list, set, tuple)):
urls = [urls]
try:
non_matching_urls = [url for url in urls if not re.se... | [
"\n Parse a list for non-matches to a regex.\n\n Args:\n urls: iterable of urls\n regex: string regex to be parsed for\n\n Returns:\n list of strings not matching regex\n "
] |
Please provide a description of the function:def writer(datasets, dataset_names, output_dir):
for dataset, dataset_name in zip(datasets, dataset_names):
if dataset:
filepath = output_dir + '/' + dataset_name + '.txt'
with open(filepath, 'w+') as out_file:
joined ... | [
"Write the results."
] |
Please provide a description of the function:def timer(diff, processed):
# Changes seconds into minutes and seconds
minutes, seconds = divmod(diff, 60)
try:
# Finds average time taken by requests
time_per_request = diff / float(len(processed))
except ZeroDivisionError:
time_... | [
"Return the passed time."
] |
Please provide a description of the function:def entropy(string):
entropy = 0
for number in range(256):
result = float(string.encode('utf-8').count(
chr(number))) / len(string.encode('utf-8'))
if result != 0:
entropy = entropy - result * math.log(result, 2)
retur... | [
"Calculate the entropy of a string."
] |
Please provide a description of the function:def extract_headers(headers):
sorted_headers = {}
matches = re.findall(r'(.*):\s(.*)', headers)
for match in matches:
header = match[0]
value = match[1]
try:
if value[-1] == ',':
value = value[:-1]
... | [
"This function extracts valid headers from interactive input."
] |
Please provide a description of the function:def top_level(url, fix_protocol=True):
ext = tld.get_tld(url, fix_protocol=fix_protocol)
toplevel = '.'.join(urlparse(url).netloc.split('.')[-2:]).split(
ext)[0] + ext
return toplevel | [
"Extract the top level domain from an URL."
] |
Please provide a description of the function:def proxy_type(v):
proxies = []
if re.match(r"((http|socks5):\/\/.)?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})", v):
proxies.append({"http": v,
"https": v})
return proxies
elif re.match(r"((http|socks5):\/\/.)?[-a-... | [
" Match IP:PORT or DOMAIN:PORT in a losse manner "
] |
Please provide a description of the function:def dnsdumpster(domain, output_dir):
response = requests.Session().get('https://dnsdumpster.com/').text
csrf_token = re.search(
r"name='csrfmiddlewaretoken' value='(.*?)'", response).group(1)
cookies = {'csrftoken': csrf_token}
headers = {'Refer... | [
"Query dnsdumpster.com."
] |
Please provide a description of the function:def prompt(default=None):
editor = 'nano'
with tempfile.NamedTemporaryFile(mode='r+') as tmpfile:
if default:
tmpfile.write(default)
tmpfile.flush()
child_pid = os.fork()
is_child = child_pid == 0
if is_c... | [
"Present the user a prompt."
] |
Please provide a description of the function:def start_market(self):
# 启动 trade_engine 线程
self.market.start()
# 注册 backtest_broker ,并且启动和它关联线程QAThread 存放在 kernels 词典中, { 'broker_name': QAThread }
#self.market.register(self.broker_name, self.broker)
self.market.connect(s... | [
"\n start the market thread and register backtest broker thread\n QAMarket 继承QATrader, QATrader 中有 trade_engine属性 , trade_engine类型是QA_Engine从 QA_Thread继承\n "
] |
Please provide a description of the function:def run(self):
# 如果出现了日期的改变 才会进行结算的事件
_date = None
while QA_util_if_tradetime(self.now):
for data in self.ingest_data: # 对于在ingest_data中的数据
# <class 'QUANTAXIS.QAData.QADataStruct.QA_DataStruct_Stock_day'>
... | [
"generator driven data flow\n "
] |
Please provide a description of the function:def message(self):
'the standard message which can be transfer'
return {
'source':
'account',
'frequence':
self.frequence,
'account_cookie':
self.account_cookie,
'portfolio_co... | [] |
Please provide a description of the function:def init_hold_with_account(self):
return self.init_hold.reset_index().assign(
account_cookie=self.account_cookie
).set_index(['code',
'account_cookie']) | [
"带account_cookie的初始化持仓\n\n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def start_date(self):
if self.start_==None:
if len(self.time_index_max) > 0:
return str(min(self.time_index_max))[0:10]
else:
print(
RuntimeWarning(
'QAACCOUN... | [
"账户的起始交易日期(只在回测中使用)\n\n Raises:\n RuntimeWarning -- [description]\n\n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def end_date(self):
if self.start_==None:
if len(self.time_index_max) > 0:
return str(max(self.time_index_max))[0:10]
else:
print(
RuntimeWarning(
'QAACCOUNT:... | [
"账户的交易结束日期(只在回测中使用)\n\n Raises:\n RuntimeWarning -- [description]\n\n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def history_table_min(self):
'区间交易历史的table'
if len(self.history_min) > 0:
lens = len(self.history_min[0])
else:
lens = len(self._history_headers)
return pd.DataFrame(
data=self.history_min,
colu... | [] |
Please provide a description of the function:def history_table(self):
'交易历史的table'
if len(self.history) > 0:
lens = len(self.history[0])
else:
lens = len(self._history_headers)
return pd.DataFrame(
data=self.history,
columns=self._history_... | [] |
Please provide a description of the function:def cash_table(self):
'现金的table'
_cash = pd.DataFrame(
data=[self.cash[1::],
self.time_index_max],
index=['cash',
'datetime']
).T
_cash = _cash.assign(
date=_cash.datetim... | [
"\n 实验性质\n @2018-06-09\n\n # 对于账户持仓的分解\n\n 1. 真实持仓hold:\n\n 正常模式/TZero模式:\n hold = 历史持仓(init_hold)+ 初始化账户后发生的所有交易导致的持仓(hold_available)\n\n 动态持仓(初始化账户后的持仓)hold_available:\n self.history 计算而得\n\n 2. 账户的可卖额度(sell_available)\n\n 正常模式:\n ... |
Please provide a description of the function:def hold(self):
return pd.concat(
[self.init_hold,
self.hold_available]
).groupby('code').sum().replace(0,
np.nan).dropna().sort_index() | [
"真实持仓\n "
] |
Please provide a description of the function:def hold_available(self):
return self.history_table.groupby('code').amount.sum().replace(
0,
np.nan
).dropna().sort_index() | [
"可用持仓\n "
] |
Please provide a description of the function:def trade(self):
return self.history_table.pivot_table(
index=['datetime',
'account_cookie'],
columns='code',
values='amount',
aggfunc=np.sum
).fillna(0).sort_index() | [
"每次交易的pivot表\n\n Returns:\n pd.DataFrame\n\n 此处的pivot_table一定要用np.sum\n "
] |
Please provide a description of the function:def daily_cash(self):
'每日交易结算时的现金表'
res = self.cash_table.drop_duplicates(subset='date', keep='last')
le=pd.DataFrame(pd.Series(data=None, index=pd.to_datetime(self.trade_range_max).set_names('date'), name='predrop'))
ri=res.set_index('date')
... | [] |
Please provide a description of the function:def daily_hold(self):
'每日交易结算时的持仓表'
data = self.trade.cumsum()
if len(data) < 1:
return None
else:
# print(data.index.levels[0])
data = data.assign(account_cookie=self.account_cookie).assign(
... | [] |
Please provide a description of the function:def daily_frozen(self):
'每日交易结算时的持仓表'
res_=self.history_table.assign(date=pd.to_datetime(self.history_table.datetime)).set_index('date').resample('D').frozen.last().fillna(method='pad')
res_=res_[res_.index.isin(self.trade_range)]
return res_ | [] |
Please provide a description of the function:def hold_table(self, datetime=None):
"到某一个时刻的持仓 如果给的是日期,则返回当日开盘前的持仓"
if datetime is None:
hold_available = self.history_table.set_index(
'datetime'
).sort_index().groupby('code').amount.sum().sort_index()
else:
... | [] |
Please provide a description of the function:def current_hold_price(self):
def weights(x):
n=len(x)
res=1
while res>0 or res<0:
res=sum(x[:n]['amount'])
n=n-1
x=x[n+1:]
if... | [
"计算目前持仓的成本 用于模拟盘和实盘查询\n\n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def hold_price(self, datetime=None):
def weights(x):
if sum(x['amount']) != 0:
return np.average(
x['price'],
weights=x['amount'],
returned=True
)
... | [
"计算持仓成本 如果给的是日期,则返回当日开盘前的持仓\n\n Keyword Arguments:\n datetime {[type]} -- [description] (default: {None})\n\n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def hold_time(self, datetime=None):
def weights(x):
if sum(x['amount']) != 0:
return pd.Timestamp(self.datetime
) - pd.to_datetime(x.datetime.max())
else:
return np.n... | [
"持仓时间\n\n Keyword Arguments:\n datetime {[type]} -- [description] (default: {None})\n "
] |
Please provide a description of the function:def reset_assets(self, init_cash=None):
'reset_history/cash/'
self.sell_available = copy.deepcopy(self.init_hold)
self.history = []
self.init_cash = init_cash
self.cash = [self.init_cash]
self.cash_available = self.cash[-1] | [] |
Please provide a description of the function:def receive_simpledeal(
self,
code,
trade_price,
trade_amount,
trade_towards,
trade_time,
message=None,
order_id=None,
trade_id=None,
realorder_id=None
... | [
"快速撮合成交接口\n\n\n 此接口是一个直接可以成交的接口, 所以务必确保给出的信息是可以成交的\n\n 此接口涉及的是\n 1. 股票/期货的成交\n 2. 历史记录的增加\n 3. 现金/持仓/冻结资金的处理\n\n Arguments:\n code {[type]} -- [description]\n trade_price {[type]} -- [description]\n trade_amount {[type]} -- [description]\n ... |
Please provide a description of the function:def receive_deal(
self,
code: str,
trade_id: str,
order_id: str,
realorder_id: str,
trade_price: float,
trade_amount: int,
trade_towards: int,
trade_time: str,
... | [
"更新deal\n\n Arguments:\n code {str} -- [description]\n trade_id {str} -- [description]\n order_id {str} -- [description]\n realorder_id {str} -- [description]\n trade_price {float} -- [description]\n trade_amount {int} -- [description]\n ... |
Please provide a description of the function:def send_order(
self,
code=None,
amount=None,
time=None,
towards=None,
price=None,
money=None,
order_model=None,
amount_model=None,
*args,
**kw... | [
"\n ATTENTION CHANGELOG 1.0.28\n 修改了Account的send_order方法, 区分按数量下单和按金额下单两种方式\n\n - AMOUNT_MODEL.BY_PRICE ==> AMOUNT_MODEL.BY_MONEY # 按金额下单\n - AMOUNT_MODEL.BY_AMOUNT # 按数量下单\n\n 在按金额下单的时候,应给予 money参数\n 在按数量下单的时候,应给予 amount参数\n\n python code:\n Account=QA.QA_Acc... |
Please provide a description of the function:def close_positions_order(self):
order_list = []
time = '{} 15:00:00'.format(self.date)
if self.running_environment == RUNNING_ENVIRONMENT.TZERO:
for code, amount in self.hold_available.iteritems():
order = False
... | [
"平仓单\n\n Raises:\n RuntimeError -- if ACCOUNT.RUNNING_ENVIRONMENT is NOT TZERO\n\n Returns:\n list -- list with order\n "
] |
Please provide a description of the function:def settle(self, settle_data = None):
#print('FROM QUANTAXIS QA_ACCOUNT: account settle')
if self.running_environment == RUNNING_ENVIRONMENT.TZERO and self.hold_available.sum(
) != 0:
raise RuntimeError(
'QAACCOUNT... | [
"\n 股票/期货的日结算\n\n 股票的结算: 结转股票可卖额度\n T0的结算: 结转T0的额度\n\n 期货的结算: 结转静态资金\n\n\n @2019-02-25 yutiansut\n hold 在下面要进行大变化:\n\n 从 只计算数量 ==> 数量+成本+买入价 (携带更多信息)\n\n 基于history去计算hold ==> last_settle+ today_pos_change\n\n ",
"静态权益的结算\n\n 只关心开仓价/ 不做盯市制度... |
Please provide a description of the function:def on_bar(self, event):
'''
策略事件
:param event:
:return:
'''
'while updating the market data'
print(
"on_bar account {} ".format(self.account_cookie),
event.market_data.data
)
pr... | [] |
Please provide a description of the function:def from_message(self, message):
self.account_cookie = message.get('account_cookie', None)
self.portfolio_cookie = message.get('portfolio_cookie', None)
self.user_cookie = message.get('user_cookie', None)
self.broker = message.get('br... | [
"resume the account from standard message\n 这个是从数据库恢复账户时需要的"
] |
Please provide a description of the function:def from_otgdict(self, message):
self.allow_margin = True
self.allow_sellopen = True
self.allow_t0 = True
self.account_cookie = message['accounts']['user_id']
# 可用资金
self.cash_available = message['accounts']['availab... | [
"[summary]\n balance = static_balance + float_profit\n\n\n \"currency\": \"\", # \"CNY\" (币种)\n \"pre_balance\": float(\"nan\"), # 9912934.78 (昨日账户权益)\n \"static_balance\": float(\"nan\"), # (静态权益)\n \"balance\": float(\"nan\"), # 9963216.55 (账户权益)\n ... |
Please provide a description of the function:def table(self):
return pd.DataFrame([
self.message,
]).set_index(
'account_cookie',
drop=False
).T | [
"\n 打印出account的内容\n "
] |
Please provide a description of the function:def run(self, event):
'''
这个方法是被 QA_ThreadEngine 处理队列时候调用的, QA_Task 中 do 方法调用 run (在其它线程中)
'QA_WORKER method 重载'
:param event: 事件类型 QA_Event
:return:
'''
'QA_WORKER method'
if event.event_type is ACCOUNT_EVENT.SE... | [
"generate order\n if callback callback the order\n if not return back the order\n ",
"update the market_data\n 1. update the inside market_data struct\n 2. tell the on_bar methods\n\n # 这样有点慢\n\n\n "
] |
Please provide a description of the function:def sync_account(self, sync_message):
self.init_hold = sync_message['hold_available']
self.init_cash = sync_message['cash_available']
self.sell_available = copy.deepcopy(self.init_hold)
self.history = []
self.cash = [self.in... | [
"同步账户\n\n Arguments:\n sync_message {[type]} -- [description]\n "
] |
Please provide a description of the function:def change_cash(self, money):
res = self.cash[-1] + money
if res >= 0:
# 高危操作
self.cash[-1] = res | [
"\n 外部操作|高危|\n "
] |
Please provide a description of the function:def get_history(self, start, end):
return self.history_table.set_index(
'datetime',
drop=False
).loc[slice(pd.Timestamp(start),
pd.Timestamp(end))] | [
"返回历史成交\n\n Arguments:\n start {str} -- [description]\n end {str]} -- [description]\n "
] |
Please provide a description of the function:def QA_SU_save_order(orderlist, client=DATABASE):
if isinstance(orderlist, pd.DataFrame):
collection = client.order
collection.create_index(
[('account_cookie',
ASCENDING),
('realorder_id',
ASCEND... | [
"存储order_handler的order_status\n\n Arguments:\n orderlist {[dataframe]} -- [description]\n\n Keyword Arguments:\n client {[type]} -- [description] (default: {DATABASE})\n "
] |
Please provide a description of the function:def QA_SU_save_deal(dealist, client=DATABASE):
if isinstance(dealist, pd.DataFrame):
collection = client.deal
collection.create_index(
[('account_cookie',
ASCENDING),
('trade_id',
ASCENDING)],
... | [
"存储order_handler的deal_status\n\n Arguments:\n dealist {[dataframe]} -- [description]\n\n Keyword Arguments:\n client {[type]} -- [description] (default: {DATABASE})\n "
] |
Please provide a description of the function:def QA_SU_save_order_queue(order_queue, client=DATABASE):
collection = client.order_queue
collection.create_index(
[('account_cookie',
ASCENDING),
('order_id',
ASCENDING)],
unique=True
)
for order in order_que... | [
"增量存储order_queue\n\n Arguments:\n order_queue {[type]} -- [description]\n\n Keyword Arguments:\n client {[type]} -- [description] (default: {DATABASE})\n "
] |
Please provide a description of the function:def SMA(Series, N, M=1):
ret = []
i = 1
length = len(Series)
# 跳过X中前面几个 nan 值
while i < length:
if np.isnan(Series.iloc[i]):
i += 1
else:
break
preY = Series.iloc[i] # Y'
ret.append(preY)
while i <... | [
"\n 威廉SMA算法\n\n 本次修正主要是对于返回值的优化,现在的返回值会带上原先输入的索引index\n 2018/5/3\n @yutiansut\n "
] |
Please provide a description of the function:def CROSS(A, B):
var = np.where(A < B, 1, 0)
return (pd.Series(var, index=A.index).diff() < 0).apply(int) | [
"A<B then A>B A上穿B B下穿A\n\n Arguments:\n A {[type]} -- [description]\n B {[type]} -- [description]\n\n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def COUNT(COND, N):
return pd.Series(np.where(COND, 1, 0), index=COND.index).rolling(N).sum() | [
"\n 2018/05/23 修改\n\n 参考https://github.com/QUANTAXIS/QUANTAXIS/issues/429\n\n 现在返回的是series\n "
] |
Please provide a description of the function:def LAST(COND, N1, N2):
N2 = 1 if N2 == 0 else N2
assert N2 > 0
assert N1 > N2
return COND.iloc[-N1:-N2].all() | [
"表达持续性\n 从前N1日到前N2日一直满足COND条件\n\n Arguments:\n COND {[type]} -- [description]\n N1 {[type]} -- [description]\n N2 {[type]} -- [description]\n "
] |
Please provide a description of the function:def AVEDEV(Series, N):
return Series.rolling(N).apply(lambda x: (np.abs(x - x.mean())).mean(), raw=True) | [
"\n 平均绝对偏差 mean absolute deviation\n 修正: 2018-05-25 \n\n 之前用mad的计算模式依然返回的是单值\n "
] |
Please provide a description of the function:def MACD(Series, FAST, SLOW, MID):
EMAFAST = EMA(Series, FAST)
EMASLOW = EMA(Series, SLOW)
DIFF = EMAFAST - EMASLOW
DEA = EMA(DIFF, MID)
MACD = (DIFF - DEA) * 2
DICT = {'DIFF': DIFF, 'DEA': DEA, 'MACD': MACD}
VAR = pd.DataFrame(DICT)
retu... | [
"macd指标 仅适用于Series\n 对于DATAFRAME的应用请使用QA_indicator_macd\n "
] |
Please provide a description of the function:def BBI(Series, N1, N2, N3, N4):
'多空指标'
bbi = (MA(Series, N1) + MA(Series, N2) +
MA(Series, N3) + MA(Series, N4)) / 4
DICT = {'BBI': bbi}
VAR = pd.DataFrame(DICT)
return VAR | [] |
Please provide a description of the function:def BARLAST(cond, yes=True):
if isinstance(cond.index, pd.MultiIndex):
return len(cond)-cond.index.levels[0].tolist().index(cond[cond != yes].index[-1][0])-1
elif isinstance(cond.index, pd.DatetimeIndex):
return len(cond)-cond.index.tolist().inde... | [
"支持MultiIndex的cond和DateTimeIndex的cond\n 条件成立 yes= True 或者 yes=1 根据不同的指标自己定\n\n Arguments:\n cond {[type]} -- [description]\n "
] |
Please provide a description of the function:def get_today_all(output='pd'):
data = []
today = str(datetime.date.today())
codes = QA_fetch_get_stock_list('stock').code.tolist()
bestip = select_best_ip()['stock']
for code in codes:
try:
l = QA_fetch_get_stock_day(
... | [
"today all\n\n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def QA_SU_save_stock_day(client=DATABASE, ui_log=None, ui_progress=None):
'''
save stock_day
保存日线数据
:param client:
:param ui_log: 给GUI qt 界面使用
:param ui_progress: 给GUI qt 界面使用
:param ui_progress_int_value: 给GUI qt 界面使用
'''
stock_list = Q... | [] |
Please provide a description of the function:def QA_user_sign_in(username, password):
#user = QA_User(name= name, password=password)
cursor = DATABASE.user.find_one(
{'username': username, 'password': password})
if cursor is None:
QA_util_log_info('SOMETHING WRONG')
return False... | [
"用户登陆\n 不使用 QAUSER库\n 只返回 TRUE/FALSE\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.