Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def handle_update_search_space(self, data): search_space = data cs = CS.ConfigurationSpace() for var in search_space: _type = str(search_space[var]["_type"]) if _type == 'choice': cs.add_hyperparameter(...
[ "change json format to ConfigSpace format dict<dict> -> configspace\n\n Parameters\n ----------\n data: JSON object\n search space of this experiment\n " ]
Please provide a description of the function:def handle_trial_end(self, data): logger.debug('Tuner handle trial end, result is %s', data) hyper_params = json_tricks.loads(data['hyper_params']) s, i, _ = hyper_params['parameter_id'].split('_') hyper_configs = self.brackets[int(s...
[ "receive the information of trial end and generate next configuaration.\n\n Parameters\n ----------\n data: dict()\n it has three keys: trial_job_id, event, hyper_params\n trial_job_id: the id generated by training service\n event: the job's state\n h...
Please provide a description of the function:def handle_report_metric_data(self, data): logger.debug('handle report metric data = %s', data) assert 'value' in data value = extract_scalar_reward(data['value']) if self.optimize_mode is OptimizeMode.Maximize: reward = ...
[ "reveice the metric data and update Bayesian optimization with final result\n\n Parameters\n ----------\n data:\n it is an object which has keys 'parameter_id', 'value', 'trial_job_id', 'type', 'sequence'.\n\n Raises\n ------\n ValueError\n Data type n...
Please provide a description of the function:def handle_import_data(self, data): _completed_num = 0 for trial_info in data: logger.info("Importing data, current processing progress %s / %s" %(_completed_num, len(data))) _completed_num += 1 assert "parameter" ...
[ "Import additional data for tuning\n\n Parameters\n ----------\n data:\n a list of dictionarys, each of which has at least two keys, 'parameter' and 'value'\n\n Raises\n ------\n AssertionError\n data doesn't have required key 'parameter' and 'value'\n...
Please provide a description of the function:def data_transforms_cifar10(args): cifar_mean = [0.49139968, 0.48215827, 0.44653124] cifar_std = [0.24703233, 0.24348505, 0.26158768] train_transform = transforms.Compose( [ transforms.RandomCrop(32, padding=4), transforms.R...
[ " data_transforms for cifar10 dataset\n " ]
Please provide a description of the function:def data_transforms_mnist(args, mnist_mean=None, mnist_std=None): if mnist_mean is None: mnist_mean = [0.5] if mnist_std is None: mnist_std = [0.5] train_transform = transforms.Compose( [ transforms.RandomCrop(28, paddin...
[ " data_transforms for mnist dataset\n " ]
Please provide a description of the function:def get_mean_and_std(dataset): dataloader = torch.utils.data.DataLoader( dataset, batch_size=1, shuffle=True, num_workers=2 ) mean = torch.zeros(3) std = torch.zeros(3) print("==> Computing mean and std..") for inputs, _ in dataloader: ...
[ "Compute the mean and std value of dataset." ]
Please provide a description of the function:def init_params(net): for module in net.modules(): if isinstance(module, nn.Conv2d): init.kaiming_normal(module.weight, mode="fan_out") if module.bias: init.constant(module.bias, 0) elif isinstance(module, nn.B...
[ "Init layer parameters." ]
Please provide a description of the function:def step(self, metrics): if self.best is None: self.best = metrics return False if np.isnan(metrics): return True if self.is_better(metrics, self.best): self.num_bad_epochs = 0 se...
[ " EarlyStopping step on each epoch\n Arguments:\n metrics {float} -- metric value\n " ]
Please provide a description of the function:def check_feasibility(x_bounds, lowerbound, upperbound): ''' This can have false positives. For examples, parameters can only be 0 or 5, and the summation constraint is between 6 and 7. ''' # x_bounds should be sorted, so even for "discrete_int" type, ...
[]
Please provide a description of the function:def rand(x_bounds, x_types, lowerbound, upperbound, max_retries=100): ''' Key idea is that we try to move towards upperbound, by randomly choose one value for each parameter. However, for the last parameter, we need to make sure that its value can help us get...
[]
Please provide a description of the function:def expand_path(experiment_config, key): '''Change '~' to user home directory''' if experiment_config.get(key): experiment_config[key] = os.path.expanduser(experiment_config[key])
[]
Please provide a description of the function:def parse_relative_path(root_path, experiment_config, key): '''Change relative path to absolute path''' if experiment_config.get(key) and not os.path.isabs(experiment_config.get(key)): absolute_path = os.path.join(root_path, experiment_config.get(key)) ...
[]
Please provide a description of the function:def parse_time(time): '''Change the time to seconds''' unit = time[-1] if unit not in ['s', 'm', 'h', 'd']: print_error('the unit of time could only from {s, m, h, d}') exit(1) time = time[:-1] if not time.isdigit(): print_error('t...
[]
Please provide a description of the function:def parse_path(experiment_config, config_path): '''Parse path in config file''' expand_path(experiment_config, 'searchSpacePath') if experiment_config.get('trial'): expand_path(experiment_config['trial'], 'codeDir') if experiment_config.get('tuner'): ...
[]
Please provide a description of the function:def validate_search_space_content(experiment_config): '''Validate searchspace content, if the searchspace file is not json format or its values does not contain _type and _value which must be specified, it will not be a valid searchspace file''' try: ...
[]
Please provide a description of the function:def validate_kubeflow_operators(experiment_config): '''Validate whether the kubeflow operators are valid''' if experiment_config.get('kubeflowConfig'): if experiment_config.get('kubeflowConfig').get('operator') == 'tf-operator': if experiment_conf...
[]
Please provide a description of the function:def validate_common_content(experiment_config): '''Validate whether the common values in experiment_config is valid''' if not experiment_config.get('trainingServicePlatform') or \ experiment_config.get('trainingServicePlatform') not in ['local', 'remote', 'pa...
[]
Please provide a description of the function:def validate_customized_file(experiment_config, spec_key): ''' check whether the file of customized tuner/assessor/advisor exists spec_key: 'tuner', 'assessor', 'advisor' ''' if experiment_config[spec_key].get('codeDir') and \ experiment_config[sp...
[]
Please provide a description of the function:def parse_assessor_content(experiment_config): '''Validate whether assessor in experiment_config is valid''' if experiment_config.get('assessor'): if experiment_config['assessor'].get('builtinAssessorName'): experiment_config['assessor']['classNam...
[]
Please provide a description of the function:def validate_pai_trial_conifg(experiment_config): '''validate the trial config in pai platform''' if experiment_config.get('trainingServicePlatform') == 'pai': if experiment_config.get('trial').get('shmMB') and \ experiment_config['trial']['shmMB'] > ...
[]
Please provide a description of the function:def validate_all_content(experiment_config, config_path): '''Validate whether experiment_config is valid''' parse_path(experiment_config, config_path) validate_common_content(experiment_config) validate_pai_trial_conifg(experiment_config) experiment_confi...
[]
Please provide a description of the function:def get_local_urls(port): '''get urls of local machine''' url_list = [] for name, info in psutil.net_if_addrs().items(): for addr in info: if AddressFamily.AF_INET == addr.family: url_list.append('http://{}:{}'.format(addr.addr...
[]
Please provide a description of the function:def parse_annotation(code): module = ast.parse(code) assert type(module) is ast.Module, 'internal error #1' assert len(module.body) == 1, 'Annotation contains more than one expression' assert type(module.body[0]) is ast.Expr, 'Annotation is not expressio...
[ "Parse an annotation string.\n Return an AST Expr node.\n code: annotation string (excluding '@')\n " ]
Please provide a description of the function:def parse_annotation_function(code, func_name): expr = parse_annotation(code) call = expr.value assert type(call) is ast.Call, 'Annotation is not a function call' assert type(call.func) is ast.Attribute, 'Unexpected annotation function' assert type(...
[ "Parse an annotation function.\n Return the value of `name` keyword argument and the AST Call node.\n func_name: expected function name\n " ]
Please provide a description of the function:def parse_nni_variable(code): name, call = parse_annotation_function(code, 'variable') assert len(call.args) == 1, 'nni.variable contains more than one arguments' arg = call.args[0] assert type(arg) is ast.Call, 'Value of nni.variable is not a function ...
[ "Parse `nni.variable` expression.\n Return the name argument and AST node of annotated expression.\n code: annotation string\n " ]
Please provide a description of the function:def parse_nni_function(code): name, call = parse_annotation_function(code, 'function_choice') funcs = [ast.dump(func, False) for func in call.args] convert_args_to_dict(call, with_lambda=True) name_str = astor.to_source(name).strip() call.keywords[0...
[ "Parse `nni.function_choice` expression.\n Return the AST node of annotated expression and a list of dumped function call expressions.\n code: annotation string\n " ]
Please provide a description of the function:def convert_args_to_dict(call, with_lambda=False): keys, values = list(), list() for arg in call.args: if type(arg) in [ast.Str, ast.Num]: arg_value = arg else: # if arg is not a string or a number, we use its source code as t...
[ "Convert all args to a dict such that every key and value in the dict is the same as the value of the arg.\n Return the AST Call node with only one arg that is the dictionary\n " ]
Please provide a description of the function:def make_lambda(call): empty_args = ast.arguments(args=[], vararg=None, kwarg=None, defaults=[]) return ast.Lambda(args=empty_args, body=call)
[ "Wrap an AST Call node to lambda expression node.\n call: ast.Call node\n " ]
Please provide a description of the function:def replace_variable_node(node, annotation): assert type(node) is ast.Assign, 'nni.variable is not annotating assignment expression' assert len(node.targets) == 1, 'Annotated assignment has more than one left-hand value' name, expr = parse_nni_variable(annot...
[ "Replace a node annotated by `nni.variable`.\n node: the AST node to replace\n annotation: annotation string\n " ]
Please provide a description of the function:def replace_function_node(node, annotation): target, funcs = parse_nni_function(annotation) FuncReplacer(funcs, target).visit(node) return node
[ "Replace a node annotated by `nni.function_choice`.\n node: the AST node to replace\n annotation: annotation string\n " ]
Please provide a description of the function:def parse(code): try: ast_tree = ast.parse(code) except Exception: raise RuntimeError('Bad Python code') transformer = Transformer() try: transformer.visit(ast_tree) except AssertionError as exc: raise RuntimeError('%...
[ "Annotate user code.\n Return annotated code (str) if annotation detected; return None if not.\n code: original user code (str)\n " ]
Please provide a description of the function:def main(): ''' main function. ''' args = parse_args() if args.multi_thread: enable_multi_thread() if args.advisor_class_name: # advisor is enabled and starts to run if args.multi_phase: raise AssertionError('mult...
[]
Please provide a description of the function:def get_yml_content(file_path): '''Load yaml file content''' try: with open(file_path, 'r') as file: return yaml.load(file, Loader=yaml.Loader) except yaml.scanner.ScannerError as err: print_error('yaml file format error!') exi...
[]
Please provide a description of the function:def detect_port(port): '''Detect if the port is used''' socket_test = socket.socket(socket.AF_INET,socket.SOCK_STREAM) try: socket_test.connect(('127.0.0.1', int(port))) socket_test.close() return True except: return False
[]
Please provide a description of the function:def create_model(samples_x, samples_y_aggregation, percentage_goodbatch=0.34): ''' Create the Gaussian Mixture Model ''' samples = [samples_x[i] + [samples_y_aggregation[i]] for i in range(0, len(samples_x))] # Sorts so that we can get the top samples ...
[]
Please provide a description of the function:def selection_r(acquisition_function, samples_y_aggregation, x_bounds, x_types, regressor_gp, num_starting_points=100, minimize_constraints_fun=None): ''' Selecte R value ...
[]
Please provide a description of the function:def selection(acquisition_function, samples_y_aggregation, x_bounds, x_types, regressor_gp, minimize_starting_points, minimize_constraints_fun=None): ''' selection ''' outputs = None s...
[]
Please provide a description of the function:def report_intermediate_result(metric): global _intermediate_seq assert _params is not None, 'nni.get_next_parameter() needs to be called before report_intermediate_result' metric = json_tricks.dumps({ 'parameter_id': _params['parameter_id'], ...
[ "Reports intermediate result to Assessor.\n metric: serializable object.\n " ]
Please provide a description of the function:def report_final_result(metric): assert _params is not None, 'nni.get_next_parameter() needs to be called before report_final_result' metric = json_tricks.dumps({ 'parameter_id': _params['parameter_id'], 'trial_job_id': trial_env_vars.NNI_TRIAL_J...
[ "Reports final result to tuner.\n metric: serializable object.\n " ]
Please provide a description of the function:def get_args(): parser = argparse.ArgumentParser("FashionMNIST") parser.add_argument("--batch_size", type=int, default=128, help="batch size") parser.add_argument("--optimizer", type=str, default="SGD", help="optimizer") parser.add_argument("--epochs", t...
[ " get args from command line\n " ]
Please provide a description of the function:def build_graph_from_json(ir_model_json): graph = json_to_graph(ir_model_json) logging.debug(graph.operation_history) model = graph.produce_torch_model() return model
[ "build model from json representation\n " ]
Please provide a description of the function:def parse_rev_args(receive_msg): global trainloader global testloader global net global criterion global optimizer # Loading Data logger.debug("Preparing data..") raw_train_data = torchvision.datasets.FashionMNIST( root="./data"...
[ " parse reveive msgs to global variable\n " ]
Please provide a description of the function:def train(epoch): global trainloader global testloader global net global criterion global optimizer logger.debug("Epoch: %d", epoch) net.train() train_loss = 0 correct = 0 total = 0 for batch_idx, (inputs, targets) in enume...
[ " train model on each epoch in trainset\n " ]
Please provide a description of the function:def freeze_bn(self): '''Freeze BatchNorm layers.''' for layer in self.modules(): if isinstance(layer, nn.BatchNorm2d): layer.eval()
[]
Please provide a description of the function:def parse_rev_args(receive_msg): global trainloader global testloader global net global criterion global optimizer # Loading Data logger.debug("Preparing data..") transform_train, transform_test = utils.data_transforms_cifar10(args) ...
[ " parse reveive msgs to global variable\n " ]
Please provide a description of the function:def prepare(self, config_file=None, user=None, password=None, **kwargs): if config_file is not None: self.read_config(config_file) else: self._prepare_account(user, password, **kwargs) self.autologin()
[ "登录的统一接口\n :param config_file 登录数据文件,若无则选择参数登录模式\n :param user: 各家券商的账号或者雪球的用户名\n :param password: 密码, 券商为加密后的密码,雪球为明文密码\n :param account: [雪球登录需要]雪球手机号(邮箱手机二选一)\n :param portfolio_code: [雪球登录需要]组合代码\n :param portfolio_market: [雪球登录需要]交易市场,\n 可选['cn', 'us', 'hk']...
Please provide a description of the function:def autologin(self, limit=10): for _ in range(limit): if self.login(): break else: raise exceptions.NotLoginError( "登录失败次数过多, 请检查密码是否正确 / 券商服务器是否处于维护中 / 网络连接是否正常" ) self.keep...
[ "实现自动登录\n :param limit: 登录次数限制\n " ]
Please provide a description of the function:def keepalive(self): if self.heart_thread.is_alive(): self.heart_active = True else: self.heart_thread.start()
[ "启动保持在线的进程 " ]
Please provide a description of the function:def __read_config(self): self.config = helpers.file2dict(self.config_path) self.global_config = helpers.file2dict(self.global_config_path) self.config.update(self.global_config)
[ "读取 config" ]
Please provide a description of the function:def exchangebill(self): # TODO 目前仅在 华泰子类 中实现 start_date, end_date = helpers.get_30_date() return self.get_exchangebill(start_date, end_date)
[ "\n 默认提供最近30天的交割单, 通常只能返回查询日期内最新的 90 天数据。\n :return:\n " ]
Please provide a description of the function:def do(self, params): request_params = self.create_basic_params() request_params.update(params) response_data = self.request(request_params) try: format_json_data = self.format_response_data(response_data) # pylint...
[ "发起对 api 的请求并过滤返回结果\n :param params: 交易所需的动态参数" ]
Please provide a description of the function:def format_response_data_type(self, response_data): if isinstance(response_data, list) and not isinstance( response_data, str ): return response_data int_match_str = "|".join(self.config["response_format"]["int"]) ...
[ "格式化返回的值为正确的类型\n :param response_data: 返回的数据\n " ]
Please provide a description of the function:def prepare( self, config_path=None, user=None, password=None, exe_path=None, comm_password=None, **kwargs ): params = locals().copy() params.pop("self") if config_path is not None:...
[ "\n 登陆客户端\n :param config_path: 登陆配置文件,跟参数登陆方式二选一\n :param user: 账号\n :param password: 明文密码\n :param exe_path: 客户端路径类似 r'C:\\\\htzqzyb2\\\\xiadan.exe', 默认 r'C:\\\\htzqzyb2\\\\xiadan.exe'\n :param comm_password: 通讯密码\n :return:\n " ]
Please provide a description of the function:def follow( self, users, run_id, track_interval=1, trade_cmd_expire_seconds=120, cmd_cache=True, entrust_prop="limit", send_interval=0, ): users = self.warp_list(users) run_ids = sel...
[ "跟踪ricequant对应的模拟交易,支持多用户多策略\n :param users: 支持easytrader的用户对象,支持使用 [] 指定多个用户\n :param run_id: ricequant 的模拟交易ID,支持使用 [] 指定多个模拟交易\n :param track_interval: 轮训模拟交易时间,单位为秒\n :param trade_cmd_expire_seconds: 交易指令过期时间, 单位为秒\n :param cmd_cache: 是否读取存储历史执行过的指令,防止重启时重复执行已经交易过的指令\n ...
Please provide a description of the function:def login(self, user, password, exe_path, comm_password=None, **kwargs): try: self._app = pywinauto.Application().connect( path=self._run_exe_path(exe_path), timeout=1 ) # pylint: disable=broad-except e...
[ "\n 登陆客户端\n\n :param user: 账号\n :param password: 明文密码\n :param exe_path: 客户端路径类似 'C:\\\\中国银河证券双子星3.2\\\\Binarystar.exe',\n 默认 'C:\\\\中国银河证券双子星3.2\\\\Binarystar.exe'\n :param comm_password: 通讯密码, 华泰需要,可不设\n :return:\n " ]
Please provide a description of the function:def login(self, user, password, exe_path, comm_password=None, **kwargs): if comm_password is None: raise ValueError("华泰必须设置通讯密码") try: self._app = pywinauto.Application().connect( path=self._run_exe_pat...
[ "\r\n :param user: 用户名\r\n :param password: 密码\r\n :param exe_path: 客户端路径, 类似\r\n :param comm_password:\r\n :param kwargs:\r\n :return:\r\n " ]
Please provide a description of the function:def login(self, user=None, password=None, **kwargs): cookies = kwargs.get('cookies') if cookies is None: raise TypeError('雪球登陆需要设置 cookies, 具体见' 'https://smalltool.github.io/2016/08/02/cookie/') headers...
[ "\n 雪球登陆, 需要设置 cookies\n :param cookies: 雪球登陆需要设置 cookies, 具体见\n https://smalltool.github.io/2016/08/02/cookie/\n :return:\n " ]
Please provide a description of the function:def follow( # type: ignore self, users, strategies, total_assets=10000, initial_assets=None, adjust_sell=False, track_interval=10, trade_cmd_expire_seconds=120, cmd_c...
[ "跟踪 joinquant 对应的模拟交易,支持多用户多策略\n :param users: 支持 easytrader 的用户对象,支持使用 [] 指定多个用户\n :param strategies: 雪球组合名, 类似 ZH123450\n :param total_assets: 雪球组合对应的总资产, 格式 [组合1对应资金, 组合2对应资金]\n 若 strategies=['ZH000001', 'ZH000002'],\n 设置 total_assets=[10000, 10000], 则表明每个组合对应的资产为 1...
Please provide a description of the function:def _adjust_sell_amount(self, stock_code, amount): stock_code = stock_code[-6:] user = self._users[0] position = user.position try: stock = next(s for s in position if s['证券代码'] == stock_code) except StopIteration:...
[ "\n 根据实际持仓值计算雪球卖出股数\n 因为雪球的交易指令是基于持仓百分比,在取近似值的情况下可能出现不精确的问题。\n 导致如下情况的产生,计算出的指令为买入 1049 股,取近似值买入 1000 股。\n 而卖出的指令计算出为卖出 1051 股,取近似值卖出 1100 股,超过 1000 股的买入量,\n 导致卖出失败\n :param stock_code: 证券代码\n :type stock_code: str\n :param amount: 卖出股份数\n :type amoun...
Please provide a description of the function:def _get_portfolio_info(self, portfolio_code): url = self.PORTFOLIO_URL + portfolio_code portfolio_page = self.s.get(url) match_info = re.search(r'(?<=SNB.cubeInfo = ).*(?=;\n)', portfolio_page.text) if ...
[ "\n 获取组合信息\n " ]
Please provide a description of the function:def parse_cookies_str(cookies): cookie_dict = {} for record in cookies.split(";"): key, value = record.strip().split("=", 1) cookie_dict[key] = value return cookie_dict
[ "\n parse cookies str to dict\n :param cookies: cookies str\n :type cookies: str\n :return: cookie dict\n :rtype: dict\n " ]
Please provide a description of the function:def get_stock_type(stock_code): stock_code = str(stock_code) if stock_code.startswith(("sh", "sz")): return stock_code[:2] if stock_code.startswith( ("50", "51", "60", "73", "90", "110", "113", "132", "204", "78") ): return "sh" ...
[ "判断股票ID对应的证券市场\n 匹配规则\n ['50', '51', '60', '90', '110'] 为 sh\n ['00', '13', '18', '15', '16', '18', '20', '30', '39', '115'] 为 sz\n ['5', '6', '9'] 开头的为 sh, 其余为 sz\n :param stock_code:股票ID, 若以 'sz', 'sh' 开头直接返回对应类型,否则使用内置规则判断\n :return 'sh' or 'sz'" ]
Please provide a description of the function:def recognize_verify_code(image_path, broker="ht"): if broker == "gf": return detect_gf_result(image_path) if broker in ["yh_client", "gj_client"]: return detect_yh_client_result(image_path) # 调用 tesseract 识别 return default_verify_code_d...
[ "识别验证码,返回识别后的字符串,使用 tesseract 实现\n :param image_path: 图片路径\n :param broker: 券商 ['ht', 'yjb', 'gf', 'yh']\n :return recognized: verify code string" ]
Please provide a description of the function:def detect_yh_client_result(image_path): api = "http://yh.ez.shidenggui.com:5000/yh_client" with open(image_path, "rb") as f: rep = requests.post(api, files={"image": f}) if rep.status_code != 201: error = rep.json()["message"] raise ...
[ "封装了tesseract的识别,部署在阿里云上,服务端源码地址为: https://github.com/shidenggui/yh_verify_code_docker" ]
Please provide a description of the function:def get_30_date(): now = datetime.datetime.now() end_date = now.date() start_date = end_date - datetime.timedelta(days=30) return start_date.strftime("%Y%m%d"), end_date.strftime("%Y%m%d")
[ "\n 获得用于查询的默认日期, 今天的日期, 以及30天前的日期\n 用于查询的日期格式通常为 20160211\n :return:\n " ]
Please provide a description of the function:def get_today_ipo_data(): agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:43.0) Gecko/20100101 Firefox/43.0" send_headers = { "Host": "xueqiu.com", "User-Agent": agent, "Accept": "application/json, text/javascript, */*; q=0.01"...
[ "\n 查询今天可以申购的新股信息\n :return: 今日可申购新股列表 apply_code申购代码 price发行价格\n " ]
Please provide a description of the function:def login(self, user=None, password=None, **kwargs): headers = self._generate_headers() self.s.headers.update(headers) # init cookie self.s.get(self.LOGIN_PAGE) # post for login params = self.create_login_params(user...
[ "\n 登陆接口\n :param user: 用户名\n :param password: 密码\n :param kwargs: 其他参数\n :return:\n " ]
Please provide a description of the function:def follow( self, users, strategies, track_interval=1, trade_cmd_expire_seconds=120, cmd_cache=True, slippage: float = 0.0, **kwargs ): self.slippage = slippage
[ "跟踪平台对应的模拟交易,支持多用户多策略\n\n :param users: 支持easytrader的用户对象,支持使用 [] 指定多个用户\n :param strategies: 雪球组合名, 类似 ZH123450\n :param total_assets: 雪球组合对应的总资产, 格式 [ 组合1对应资金, 组合2对应资金 ]\n 若 strategies=['ZH000001', 'ZH000002'] 设置 total_assets=[10000, 10000], 则表明每个组合对应的资产为 1w 元,\n 假设组合 ZH...
Please provide a description of the function:def _calculate_price_by_slippage(self, action: str, price: float) -> float: if action == "buy": return price * (1 + self.slippage) if action == "sell": return price * (1 - self.slippage) return price
[ "\n 计算考虑滑点之后的价格\n :param action: 交易动作, 支持 ['buy', 'sell']\n :param price: 原始交易价格\n :return: 考虑滑点后的交易价格\n " ]
Please provide a description of the function:def track_strategy_worker(self, strategy, name, interval=10, **kwargs): while True: try: transactions = self.query_strategy_transaction( strategy, **kwargs ) # pylint: disable=broad-...
[ "跟踪下单worker\n :param strategy: 策略id\n :param name: 策略名字\n :param interval: 轮询策略的时间间隔,单位为秒" ]
Please provide a description of the function:def _execute_trade_cmd( self, trade_cmd, users, expire_seconds, entrust_prop, send_interval ): for user in users: # check expire now = datetime.datetime.now() expire = (now - trade_cmd["datetime"]).total_second...
[ "分发交易指令到对应的 user 并执行\n :param trade_cmd:\n :param users:\n :param expire_seconds:\n :param entrust_prop:\n :param send_interval:\n :return:\n " ]
Please provide a description of the function:def trade_worker( self, users, expire_seconds=120, entrust_prop="limit", send_interval=0 ): while True: trade_cmd = self.trade_queue.get() self._execute_trade_cmd( trade_cmd, users, expire_seconds, entrust_...
[ "\n :param send_interval: 交易发送间隔, 默认为0s。调大可防止卖出买入时买出单没有及时成交导致的买入金额不足\n " ]
Please provide a description of the function:def _set_cookies(self, cookies): cookie_dict = helpers.parse_cookies_str(cookies) self.s.cookies.update(cookie_dict)
[ "设置雪球 cookies,代码来自于\n https://github.com/shidenggui/easytrader/issues/269\n :param cookies: 雪球 cookies\n :type cookies: str\n " ]
Please provide a description of the function:def _prepare_account(self, user="", password="", **kwargs): if "portfolio_code" not in kwargs: raise TypeError("雪球登录需要设置 portfolio_code(组合代码) 参数") if "portfolio_market" not in kwargs: kwargs["portfolio_market"] = "cn" ...
[ "\n 转换参数到登录所需的字典格式\n :param cookies: 雪球登陆需要设置 cookies, 具体见\n https://smalltool.github.io/2016/08/02/cookie/\n :param portfolio_code: 组合代码\n :param portfolio_market: 交易市场, 可选['cn', 'us', 'hk'] 默认 'cn'\n :return:\n " ]
Please provide a description of the function:def _search_stock_info(self, code): data = { "code": str(code), "size": "300", "key": "47bce5c74f", "market": self.account_config["portfolio_market"], } r = self.s.get(self.config["search_stock_...
[ "\n 通过雪球的接口获取股票详细信息\n :param code: 股票代码 000001\n :return: 查询到的股票 {u'stock_id': 1000279, u'code': u'SH600325',\n u'name': u'华发股份', u'ind_color': u'#d9633b', u'chg': -1.09,\n u'ind_id': 100014, u'percent': -9.31, u'current': 10.62,\n u'hasexist': None, u'flag': 1,...
Please provide a description of the function:def _get_portfolio_info(self, portfolio_code): url = self.config["portfolio_url"] + portfolio_code html = self._get_html(url) match_info = re.search(r"(?<=SNB.cubeInfo = ).*(?=;\n)", html) if match_info is None: raise Exce...
[ "\n 获取组合信息\n :return: 字典\n " ]
Please provide a description of the function:def get_balance(self): portfolio_code = self.account_config.get("portfolio_code", "ch") portfolio_info = self._get_portfolio_info(portfolio_code) asset_balance = self._virtual_to_balance( float(portfolio_info["net_value"]) ...
[ "\n 获取账户资金状况\n :return:\n " ]
Please provide a description of the function:def _get_position(self): portfolio_code = self.account_config["portfolio_code"] portfolio_info = self._get_portfolio_info(portfolio_code) position = portfolio_info["view_rebalancing"] # 仓位结构 stocks = position["holdings"] # 持仓股票 ...
[ "\n 获取雪球持仓\n :return:\n " ]
Please provide a description of the function:def get_position(self): xq_positions = self._get_position() balance = self.get_balance()[0] position_list = [] for pos in xq_positions: volume = pos["weight"] * balance["asset_balance"] / 100 position_list.appe...
[ "\n 获取持仓\n :return:\n " ]
Please provide a description of the function:def _get_xq_history(self): data = { "cube_symbol": str(self.account_config["portfolio_code"]), "count": 20, "page": 1, } resp = self.s.get(self.config["history_url"], params=data) res = json.loads(r...
[ "\n 获取雪球调仓历史\n :param instance:\n :param owner:\n :return:\n " ]
Please provide a description of the function:def get_entrust(self): xq_entrust_list = self._get_xq_history() entrust_list = [] replace_none = lambda s: s or 0 for xq_entrusts in xq_entrust_list: status = xq_entrusts["status"] # 调仓状态 if status == "pending...
[ "\n 获取委托单(目前返回20次调仓的结果)\n 操作数量都按1手模拟换算的\n :return:\n " ]
Please provide a description of the function:def cancel_entrust(self, entrust_no): xq_entrust_list = self._get_xq_history() is_have = False for xq_entrusts in xq_entrust_list: status = xq_entrusts["status"] # 调仓状态 for entrust in xq_entrusts["rebalancing_historie...
[ "\n 对未成交的调仓进行伪撤单\n :param entrust_no:\n :return:\n " ]
Please provide a description of the function:def adjust_weight(self, stock_code, weight): stock = self._search_stock_info(stock_code) if stock is None: raise exceptions.TradeError(u"没有查询要操作的股票信息") if stock["flag"] != 1: raise exceptions.TradeError(u"未上市、停牌、涨跌停、退...
[ "\n 雪球组合调仓, weight 为调整后的仓位比例\n :param stock_code: str 股票代码\n :param weight: float 调整之后的持仓百分比, 0 - 100 之间的浮点数\n " ]
Please provide a description of the function:def _trade(self, security, price=0, amount=0, volume=0, entrust_bs="buy"): stock = self._search_stock_info(security) balance = self.get_balance()[0] if stock is None: raise exceptions.TradeError(u"没有查询要操作的股票信息") if not vol...
[ "\n 调仓\n :param security:\n :param price:\n :param amount:\n :param volume:\n :param entrust_bs:\n :return:\n " ]
Please provide a description of the function:def buy(self, security, price=0, amount=0, volume=0, entrust_prop=0): return self._trade(security, price, amount, volume, "buy")
[ "买入卖出股票\n :param security: 股票代码\n :param price: 买入价格\n :param amount: 买入股数\n :param volume: 买入总金额 由 volume / price 取整, 若指定 price 则此参数无效\n :param entrust_prop:\n " ]
Please provide a description of the function:def sell(self, security, price=0, amount=0, volume=0, entrust_prop=0): return self._trade(security, price, amount, volume, "sell")
[ "卖出股票\n :param security: 股票代码\n :param price: 卖出价格\n :param amount: 卖出股数\n :param volume: 卖出总金额 由 volume / price 取整, 若指定 price 则此参数无效\n :param entrust_prop:\n " ]
Please provide a description of the function:def follow( self, users, strategies, track_interval=1, trade_cmd_expire_seconds=120, cmd_cache=True, entrust_prop="limit", send_interval=0, ): users = self.warp_list(users) strategie...
[ "跟踪joinquant对应的模拟交易,支持多用户多策略\n :param users: 支持easytrader的用户对象,支持使用 [] 指定多个用户\n :param strategies: joinquant 的模拟交易地址,支持使用 [] 指定多个模拟交易,\n 地址类似 https://www.joinquant.com/algorithm/live/index?backtestId=xxx\n :param track_interval: 轮训模拟交易时间,单位为秒\n :param trade_cmd_expire_seconds:...
Please provide a description of the function:def connect(self, exe_path=None, **kwargs): connect_path = exe_path or self._config.DEFAULT_EXE_PATH if connect_path is None: raise ValueError( "参数 exe_path 未设置,请设置客户端对应的 exe 地址,类似 C:\\客户端安装目录\\xiadan.exe" ) ...
[ "\n 直接连接登陆后的客户端\n :param exe_path: 客户端路径类似 r'C:\\\\htzqzyb2\\\\xiadan.exe', 默认 r'C:\\\\htzqzyb2\\\\xiadan.exe'\n :return:\n " ]
Please provide a description of the function:def market_buy(self, security, amount, ttype=None, **kwargs): self._switch_left_menus(["市价委托", "买入"]) return self.market_trade(security, amount, ttype)
[ "\n 市价买入\n :param security: 六位证券代码\n :param amount: 交易数量\n :param ttype: 市价委托类型,默认客户端默认选择,\n 深市可选 ['对手方最优价格', '本方最优价格', '即时成交剩余撤销', '最优五档即时成交剩余 '全额成交或撤销']\n 沪市可选 ['最优五档成交剩余撤销', '最优五档成交剩余转限价']\n\n :return: {'entrust_no': '委托单号'}\n " ]
Please provide a description of the function:def market_sell(self, security, amount, ttype=None, **kwargs): self._switch_left_menus(["市价委托", "卖出"]) return self.market_trade(security, amount, ttype)
[ "\n 市价卖出\n :param security: 六位证券代码\n :param amount: 交易数量\n :param ttype: 市价委托类型,默认客户端默认选择,\n 深市可选 ['对手方最优价格', '本方最优价格', '即时成交剩余撤销', '最优五档即时成交剩余 '全额成交或撤销']\n 沪市可选 ['最优五档成交剩余撤销', '最优五档成交剩余转限价']\n\n :return: {'entrust_no': '委托单号'}\n " ]
Please provide a description of the function:def market_trade(self, security, amount, ttype=None, **kwargs): self._set_market_trade_params(security, amount) if ttype is not None: self._set_market_trade_type(ttype) self._submit_trade() return self._handle_pop_dialogs...
[ "\n 市价交易\n :param security: 六位证券代码\n :param amount: 交易数量\n :param ttype: 市价委托类型,默认客户端默认选择,\n 深市可选 ['对手方最优价格', '本方最优价格', '即时成交剩余撤销', '最优五档即时成交剩余 '全额成交或撤销']\n 沪市可选 ['最优五档成交剩余撤销', '最优五档成交剩余转限价']\n\n :return: {'entrust_no': '委托单号'}\n " ]
Please provide a description of the function:def _set_market_trade_type(self, ttype): selects = self._main.child_window( control_id=self._config.TRADE_MARKET_TYPE_CONTROL_ID, class_name="ComboBox", ) for i, text in selects.texts(): # skip 0 index, bec...
[ "根据选择的市价交易类型选择对应的下拉选项" ]
Please provide a description of the function:def prepare( self, config_path=None, user=None, password=None, exe_path=None, comm_password=None, **kwargs ): if config_path is not None: account = helpers.file2dict(config_path) ...
[ "\n 登陆客户端\n :param config_path: 登陆配置文件,跟参数登陆方式二选一\n :param user: 账号\n :param password: 明文密码\n :param exe_path: 客户端路径类似 r'C:\\\\htzqzyb2\\\\xiadan.exe', 默认 r'C:\\\\htzqzyb2\\\\xiadan.exe'\n :param comm_password: 通讯密码\n :return:\n " ]
Please provide a description of the function:def login(self, user, password, exe_path, comm_password=None, **kwargs): try: self._app = pywinauto.Application().connect( path=self._run_exe_path(exe_path), timeout=1 ) # pylint: disable=broad-except e...
[ "\n 登陆客户端\n :param user: 账号\n :param password: 明文密码\n :param exe_path: 客户端路径类似 'C:\\\\中国银河证券双子星3.2\\\\Binarystar.exe',\n 默认 'C:\\\\中国银河证券双子星3.2\\\\Binarystar.exe'\n :param comm_password: 通讯密码, 华泰需要,可不设\n :return:\n " ]
Please provide a description of the function:def use(broker, debug=True, **kwargs): if not debug: log.setLevel(logging.INFO) if broker.lower() in ["xq", "雪球"]: return XueQiuTrader(**kwargs) if broker.lower() in ["yh_client", "银河客户端"]: from .yh_clienttrader import YHClientTrader ...
[ "用于生成特定的券商对象\n :param broker:券商名支持 ['yh_client', '银河客户端'] ['ht_client', '华泰客户端']\n :param debug: 控制 debug 日志的显示, 默认为 True\n :param initial_assets: [雪球参数] 控制雪球初始资金,默认为一百万\n :return the class of trader\n\n Usage::\n\n >>> import easytrader\n >>> user = easytrader.use('xq')\n >>> us...
Please provide a description of the function:def follower(platform, **kwargs): if platform.lower() in ["rq", "ricequant", "米筐"]: return RiceQuantFollower() if platform.lower() in ["jq", "joinquant", "聚宽"]: return JoinQuantFollower() if platform.lower() in ["xq", "xueqiu", "雪球"]: ...
[ "用于生成特定的券商对象\n :param platform:平台支持 ['jq', 'joinquant', '聚宽’]\n :param initial_assets: [雪球参数] 控制雪球初始资金,默认为一万,\n 总资金由 initial_assets * 组合当前净值 得出\n :param total_assets: [雪球参数] 控制雪球总资金,无默认值,\n 若设置则覆盖 initial_assets\n :return the class of follower\n\n Usage::\n\n >>> import easytrade...
Please provide a description of the function:def CaffeLMDB(lmdb_path, shuffle=True, keys=None): cpb = get_caffe_pb() lmdb_data = LMDBData(lmdb_path, shuffle, keys) def decoder(k, v): try: datum = cpb.Datum() datum.ParseFromString(v) img = np.fromstring(datu...
[ "\n Read a Caffe LMDB file where each value contains a ``caffe.Datum`` protobuf.\n Produces datapoints of the format: [HWC image, label].\n\n Note that Caffe LMDB format is not efficient: it stores serialized raw\n arrays rather than JPEG images.\n\n Args:\n lmdb_path, shuffle, keys: same as :...
Please provide a description of the function:def memory(self): class GpuMemoryInfo(Structure): _fields_ = [ ('total', c_ulonglong), ('free', c_ulonglong), ('used', c_ulonglong), ] c_memory = GpuMemoryInfo() _check_...
[ "Memory information in bytes\n\n Example:\n\n >>> print(ctx.device(0).memory())\n {'total': 4238016512L, 'used': 434831360L, 'free': 3803185152L}\n\n Returns:\n total/used/free memory in bytes\n " ]
Please provide a description of the function:def utilization(self): class GpuUtilizationInfo(Structure): _fields_ = [ ('gpu', c_uint), ('memory', c_uint), ] c_util = GpuUtilizationInfo() _check_return(_NVML.get_function( ...
[ "Percent of time over the past second was utilized.\n\n Details:\n Percent of time over the past second during which one or more kernels was executing on the GPU.\n Percent of time over the past second during which global (device) memory was being read or written\n\n Example:\n\n ...