INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
initilize batch norm layer weight. | def init_bn_weight(layer):
'''initilize batch norm layer weight.
'''
n_filters = layer.num_features
new_weights = [
add_noise(np.ones(n_filters, dtype=np.float32), np.array([0, 1])),
add_noise(np.zeros(n_filters, dtype=np.float32), np.array([0, 1])),
add_noise(np.zeros(n_filters,... |
parse log path | def parse_log_path(args, trial_content):
'''parse log path'''
path_list = []
host_list = []
for trial in trial_content:
if args.trial_id and args.trial_id != 'all' and trial.get('id') != args.trial_id:
continue
pattern = r'(?P<head>.+)://(?P<host>.+):(?P<path>.*)'
mat... |
use ssh client to copy data from remote machine to local machien | def copy_data_from_remote(args, nni_config, trial_content, path_list, host_list, temp_nni_path):
'''use ssh client to copy data from remote machine to local machien'''
machine_list = nni_config.get_config('experimentConfig').get('machineList')
machine_dict = {}
local_path_list = []
for machine in ma... |
get path list according to different platform | def get_path_list(args, nni_config, trial_content, temp_nni_path):
'''get path list according to different platform'''
path_list, host_list = parse_log_path(args, trial_content)
platform = nni_config.get_config('experimentConfig').get('trainingServicePlatform')
if platform == 'local':
print_norm... |
call cmds to start tensorboard process in local machine | def start_tensorboard_process(args, nni_config, path_list, temp_nni_path):
'''call cmds to start tensorboard process in local machine'''
if detect_port(args.port):
print_error('Port %s is used by another process, please reset port!' % str(args.port))
exit(1)
stdout_file = open(os.path.j... |
stop tensorboard | def stop_tensorboard(args):
'''stop tensorboard'''
experiment_id = check_experiment_id(args)
experiment_config = Experiments()
experiment_dict = experiment_config.get_all_experiments()
config_file_name = experiment_dict[experiment_id]['fileName']
nni_config = Config(config_file_name)
tensorb... |
start tensorboard | def start_tensorboard(args):
'''start tensorboard'''
experiment_id = check_experiment_id(args)
experiment_config = Experiments()
experiment_dict = experiment_config.get_all_experiments()
config_file_name = experiment_dict[experiment_id]['fileName']
nni_config = Config(config_file_name)
rest_... |
The ratio is smaller the better | def _ratio_scores(parameters_value, clusteringmodel_gmm_good, clusteringmodel_gmm_bad):
'''
The ratio is smaller the better
'''
ratio = clusteringmodel_gmm_good.score([parameters_value]) / clusteringmodel_gmm_bad.score([parameters_value])
sigma = 0
return ratio, sigma |
Call selection | def selection_r(x_bounds,
x_types,
clusteringmodel_gmm_good,
clusteringmodel_gmm_bad,
num_starting_points=100,
minimize_constraints_fun=None):
'''
Call selection
'''
minimize_starting_points = [lib_data.rand(x_bounds, x_type... |
Select the lowest mu value | def selection(x_bounds,
x_types,
clusteringmodel_gmm_good,
clusteringmodel_gmm_bad,
minimize_starting_points,
minimize_constraints_fun=None):
'''
Select the lowest mu value
'''
results = lib_acquisition_function.next_hyperparameter_lo... |
Minimize constraints fun summation | def _minimize_constraints_fun_summation(x):
'''
Minimize constraints fun summation
'''
summation = sum([x[i] for i in CONSTRAINT_PARAMS_IDX])
return CONSTRAINT_UPPERBOUND >= summation >= CONSTRAINT_LOWERBOUND |
Load dataset use 20newsgroups dataset | def load_data():
'''Load dataset, use 20newsgroups dataset'''
digits = load_digits()
X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target, random_state=99, test_size=0.25)
ss = StandardScaler()
X_train = ss.fit_transform(X_train)
X_test = ss.transform(X_test)
retu... |
Get model according to parameters | def get_model(PARAMS):
'''Get model according to parameters'''
model = SVC()
model.C = PARAMS.get('C')
model.keral = PARAMS.get('keral')
model.degree = PARAMS.get('degree')
model.gamma = PARAMS.get('gamma')
model.coef0 = PARAMS.get('coef0')
return model |
generate num hyperparameter configurations from search space using Bayesian optimization | def get_hyperparameter_configurations(self, num, r, config_generator):
"""generate num hyperparameter configurations from search space using Bayesian optimization
Parameters
----------
num: int
the number of hyperparameter configurations
Returns
-------
... |
Initialize Tuner including creating Bayesian optimization - based parametric models and search space formations | def handle_initialize(self, data):
"""Initialize Tuner, including creating Bayesian optimization-based parametric models
and search space formations
Parameters
----------
data: search space
search space of this experiment
Raises
------
Value... |
generate a new bracket | def generate_new_bracket(self):
"""generate a new bracket"""
logger.debug(
'start to create a new SuccessiveHalving iteration, self.curr_s=%d', self.curr_s)
if self.curr_s < 0:
logger.info("s < 0, Finish this round of Hyperband in BOHB. Generate new round")
se... |
recerive the number of request and generate trials | def handle_request_trial_jobs(self, data):
"""recerive the number of request and generate trials
Parameters
----------
data: int
number of trial jobs that nni manager ask to generate
"""
# Receive new request
self.credit += data
for _ in rang... |
get one trial job i. e. one hyperparameter configuration. | def _request_one_trial_job(self):
"""get one trial job, i.e., one hyperparameter configuration.
If this function is called, Command will be sent by BOHB:
a. If there is a parameter need to run, will return "NewTrialJob" with a dict:
{
'parameter_id': id of new hyperparamete... |
change json format to ConfigSpace format dict<dict > - > configspace | def handle_update_search_space(self, data):
"""change json format to ConfigSpace format dict<dict> -> configspace
Parameters
----------
data: JSON object
search space of this experiment
"""
search_space = data
cs = CS.ConfigurationSpace()
for ... |
receive the information of trial end and generate next configuaration. | def handle_trial_end(self, data):
"""receive the information of trial end and generate next configuaration.
Parameters
----------
data: dict()
it has three keys: trial_job_id, event, hyper_params
trial_job_id: the id generated by training service
even... |
reveice the metric data and update Bayesian optimization with final result | def handle_report_metric_data(self, data):
"""reveice the metric data and update Bayesian optimization with final result
Parameters
----------
data:
it is an object which has keys 'parameter_id', 'value', 'trial_job_id', 'type', 'sequence'.
Raises
------
... |
Import additional data for tuning | def handle_import_data(self, data):
"""Import additional data for tuning
Parameters
----------
data:
a list of dictionarys, each of which has at least two keys, 'parameter' and 'value'
Raises
------
AssertionError
data doesn't have requir... |
data_transforms for cifar10 dataset | def data_transforms_cifar10(args):
""" data_transforms for cifar10 dataset
"""
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... |
data_transforms for mnist dataset | def data_transforms_mnist(args, mnist_mean=None, mnist_std=None):
""" data_transforms for mnist dataset
"""
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... |
Compute the mean and std value of dataset. | def get_mean_and_std(dataset):
"""Compute the mean and std value of 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:... |
Init layer parameters. | def init_params(net):
"""Init layer parameters."""
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.BatchNorm2d):
... |
EarlyStopping step on each epoch Arguments: metrics { float } -- metric value | def step(self, metrics):
""" EarlyStopping step on each epoch
Arguments:
metrics {float} -- metric value
"""
if self.best is None:
self.best = metrics
return False
if np.isnan(metrics):
return True
if self.is_better(metri... |
This can have false positives. For examples parameters can only be 0 or 5 and the summation constraint is between 6 and 7. | 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,
# the smallest and the largest number should... |
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 above lowerbound | 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 above lowerbound
'''
outputs = None
... |
Change ~ to user home directory | 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]) |
Change relative path to absolute path | 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))
print_normal('expand %s: %s to %s ' % (key,... |
Change the time to seconds | 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('time format error!')
exit(1)
parse... |
Parse path in config file | 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'):
expand_path(experiment_config['tuner'... |
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 | 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:
search_space_content = json.load(open... |
Validate whether the kubeflow operators are valid | 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_config.get('trial').get('master') is not None:
... |
Validate whether the common values in experiment_config is valid | 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', 'pai', 'kubeflow', 'frameworkcontroller']:
... |
check whether the file of customized tuner/ assessor/ advisor exists spec_key: tuner assessor advisor | 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[spec_key].get('classFileName') and \
ex... |
Validate whether assessor in experiment_config is valid | 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']['className'] = experiment_config['assessor']['builtinA... |
Valid whether useAnnotation and searchSpacePath is coexist spec_key: advisor or tuner builtin_name: builtinAdvisorName or builtinTunerName | def validate_annotation_content(experiment_config, spec_key, builtin_name):
'''
Valid whether useAnnotation and searchSpacePath is coexist
spec_key: 'advisor' or 'tuner'
builtin_name: 'builtinAdvisorName' or 'builtinTunerName'
'''
if experiment_config.get('useAnnotation'):
if experiment_... |
validate the trial config in pai platform | 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'] > experiment_config['trial']['memoryMB']:
... |
Validate whether experiment_config is valid | 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_config['maxExecDuration'] = parse_time(experiment_... |
get urls of local machine | 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.address, port))
return url_list |
Parse an annotation string. Return an AST Expr node. code: annotation string ( excluding | def parse_annotation(code):
"""Parse an annotation string.
Return an AST Expr node.
code: annotation string (excluding '@')
"""
module = ast.parse(code)
assert type(module) is ast.Module, 'internal error #1'
assert len(module.body) == 1, 'Annotation contains more than one expression'
ass... |
Parse an annotation function. Return the value of name keyword argument and the AST Call node. func_name: expected function name | def parse_annotation_function(code, func_name):
"""Parse an annotation function.
Return the value of `name` keyword argument and the AST Call node.
func_name: expected function name
"""
expr = parse_annotation(code)
call = expr.value
assert type(call) is ast.Call, 'Annotation is not a functi... |
Parse nni. variable expression. Return the name argument and AST node of annotated expression. code: annotation string | def parse_nni_variable(code):
"""Parse `nni.variable` expression.
Return the name argument and AST node of annotated expression.
code: annotation string
"""
name, call = parse_annotation_function(code, 'variable')
assert len(call.args) == 1, 'nni.variable contains more than one arguments'
a... |
Parse nni. function_choice expression. Return the AST node of annotated expression and a list of dumped function call expressions. code: annotation string | def parse_nni_function(code):
"""Parse `nni.function_choice` expression.
Return the AST node of annotated expression and a list of dumped function call expressions.
code: annotation string
"""
name, call = parse_annotation_function(code, 'function_choice')
funcs = [ast.dump(func, False) for func... |
Convert all args to a dict such that every key and value in the dict is the same as the value of the arg. Return the AST Call node with only one arg that is the dictionary | def convert_args_to_dict(call, with_lambda=False):
"""Convert all args to a dict such that every key and value in the dict is the same as the value of the arg.
Return the AST Call node with only one arg that is the dictionary
"""
keys, values = list(), list()
for arg in call.args:
if type(ar... |
Wrap an AST Call node to lambda expression node. call: ast. Call node | def make_lambda(call):
"""Wrap an AST Call node to lambda expression node.
call: ast.Call node
"""
empty_args = ast.arguments(args=[], vararg=None, kwarg=None, defaults=[])
return ast.Lambda(args=empty_args, body=call) |
Replace a node annotated by nni. variable. node: the AST node to replace annotation: annotation string | def replace_variable_node(node, annotation):
"""Replace a node annotated by `nni.variable`.
node: the AST node to replace
annotation: annotation string
"""
assert type(node) is ast.Assign, 'nni.variable is not annotating assignment expression'
assert len(node.targets) == 1, 'Annotated assignment... |
Replace a node annotated by nni. function_choice. node: the AST node to replace annotation: annotation string | def replace_function_node(node, annotation):
"""Replace a node annotated by `nni.function_choice`.
node: the AST node to replace
annotation: annotation string
"""
target, funcs = parse_nni_function(annotation)
FuncReplacer(funcs, target).visit(node)
return node |
Annotate user code. Return annotated code ( str ) if annotation detected ; return None if not. code: original user code ( str ) | def parse(code):
"""Annotate user code.
Return annotated code (str) if annotation detected; return None if not.
code: original user code (str)
"""
try:
ast_tree = ast.parse(code)
except Exception:
raise RuntimeError('Bad Python code')
transformer = Transformer()
try:
... |
main 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('multi_phase has not been supported in advisor')
... |
Load yaml file content | 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!')
exit(1)
except Exception as exception:
... |
Detect if the port is used | 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 |
Create the Gaussian Mixture Model | 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
samples = sorted(samples, key=itemgetter(-1... |
Selecte R value | 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
'''
minimize_starting_points = [lib_d... |
selection | def selection(acquisition_function,
samples_y_aggregation,
x_bounds, x_types,
regressor_gp,
minimize_starting_points,
minimize_constraints_fun=None):
'''
selection
'''
outputs = None
sys.stderr.write("[%s] Exercise \"%s\" acquisi... |
Reports intermediate result to Assessor. metric: serializable object. | def report_intermediate_result(metric):
"""Reports intermediate result to Assessor.
metric: serializable object.
"""
global _intermediate_seq
assert _params is not None, 'nni.get_next_parameter() needs to be called before report_intermediate_result'
metric = json_tricks.dumps({
'paramete... |
Reports final result to tuner. metric: serializable object. | def report_final_result(metric):
"""Reports final result to tuner.
metric: serializable object.
"""
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... |
get args from command line | def get_args():
""" get args from command line
"""
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", type=int... |
build model from json representation | def build_graph_from_json(ir_model_json):
"""build model from json representation
"""
graph = json_to_graph(ir_model_json)
logging.debug(graph.operation_history)
model = graph.produce_torch_model()
return model |
parse reveive msgs to global variable | def parse_rev_args(receive_msg):
""" parse reveive msgs to global variable
"""
global trainloader
global testloader
global net
global criterion
global optimizer
# Loading Data
logger.debug("Preparing data..")
raw_train_data = torchvision.datasets.FashionMNIST(
root="./d... |
train model on each epoch in trainset | def train(epoch):
""" train model on each epoch in trainset
"""
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 e... |
Freeze BatchNorm layers. | def freeze_bn(self):
'''Freeze BatchNorm layers.'''
for layer in self.modules():
if isinstance(layer, nn.BatchNorm2d):
layer.eval() |
parse reveive msgs to global variable | def parse_rev_args(receive_msg):
""" parse reveive msgs to global variable
"""
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)... |
登录的统一接口: param config_file 登录数据文件,若无则选择参数登录模式: param user: 各家券商的账号或者雪球的用户名: param password: 密码 券商为加密后的密码,雪球为明文密码: param account: [ 雪球登录需要 ] 雪球手机号 ( 邮箱手机二选一 ): param portfolio_code: [ 雪球登录需要 ] 组合代码: param portfolio_market: [ 雪球登录需要 ] 交易市场, 可选 [ cn us hk ] 默认 cn | def prepare(self, config_file=None, user=None, password=None, **kwargs):
"""登录的统一接口
:param config_file 登录数据文件,若无则选择参数登录模式
:param user: 各家券商的账号或者雪球的用户名
:param password: 密码, 券商为加密后的密码,雪球为明文密码
:param account: [雪球登录需要]雪球手机号(邮箱手机二选一)
:param portfolio_code: [雪球登录需要]组合代码
... |
实现自动登录: param limit: 登录次数限制 | def autologin(self, limit=10):
"""实现自动登录
:param limit: 登录次数限制
"""
for _ in range(limit):
if self.login():
break
else:
raise exceptions.NotLoginError(
"登录失败次数过多, 请检查密码是否正确 / 券商服务器是否处于维护中 / 网络连接是否正常"
)
self... |
启动保持在线的进程 | def keepalive(self):
"""启动保持在线的进程 """
if self.heart_thread.is_alive():
self.heart_active = True
else:
self.heart_thread.start() |
读取 config | def __read_config(self):
"""读取 config"""
self.config = helpers.file2dict(self.config_path)
self.global_config = helpers.file2dict(self.global_config_path)
self.config.update(self.global_config) |
默认提供最近30天的交割单 通常只能返回查询日期内最新的 90 天数据。: return: | def exchangebill(self):
"""
默认提供最近30天的交割单, 通常只能返回查询日期内最新的 90 天数据。
:return:
"""
# TODO 目前仅在 华泰子类 中实现
start_date, end_date = helpers.get_30_date()
return self.get_exchangebill(start_date, end_date) |
发起对 api 的请求并过滤返回结果: param params: 交易所需的动态参数 | def do(self, params):
"""发起对 api 的请求并过滤返回结果
:param 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)
... |
格式化返回的值为正确的类型: param response_data: 返回的数据 | def format_response_data_type(self, response_data):
"""格式化返回的值为正确的类型
:param response_data: 返回的数据
"""
if isinstance(response_data, list) and not isinstance(
response_data, str
):
return response_data
int_match_str = "|".join(self.config["response_f... |
登陆客户端: param config_path: 登陆配置文件,跟参数登陆方式二选一: param user: 账号: param password: 明文密码: param exe_path: 客户端路径类似 r C: \\ htzqzyb2 \\ xiadan. exe 默认 r C: \\ htzqzyb2 \\ xiadan. exe: param comm_password: 通讯密码: return: | def prepare(
self,
config_path=None,
user=None,
password=None,
exe_path=None,
comm_password=None,
**kwargs
):
"""
登陆客户端
:param config_path: 登陆配置文件,跟参数登陆方式二选一
:param user: 账号
:param password: 明文密码
:param exe_path:... |
跟踪ricequant对应的模拟交易,支持多用户多策略: param users: 支持easytrader的用户对象,支持使用 [] 指定多个用户: param run_id: ricequant 的模拟交易ID,支持使用 [] 指定多个模拟交易: param track_interval: 轮训模拟交易时间,单位为秒: param trade_cmd_expire_seconds: 交易指令过期时间 单位为秒: param cmd_cache: 是否读取存储历史执行过的指令,防止重启时重复执行已经交易过的指令: param entrust_prop: 委托方式 limit 为限价, market 为市价 仅在银河实现: para... | def follow(
self,
users,
run_id,
track_interval=1,
trade_cmd_expire_seconds=120,
cmd_cache=True,
entrust_prop="limit",
send_interval=0,
):
"""跟踪ricequant对应的模拟交易,支持多用户多策略
:param users: 支持easytrader的用户对象,支持使用 [] 指定多个用户
:param run_... |
登陆客户端 | def login(self, user, password, exe_path, comm_password=None, **kwargs):
"""
登陆客户端
:param user: 账号
:param password: 明文密码
:param exe_path: 客户端路径类似 'C:\\中国银河证券双子星3.2\\Binarystar.exe',
默认 'C:\\中国银河证券双子星3.2\\Binarystar.exe'
:param comm_password: 通讯密码, 华泰需要,可不设
... |
: param user: 用户名: param password: 密码: param exe_path: 客户端路径 类似: param comm_password:: param kwargs:: return: | def login(self, user, password, exe_path, comm_password=None, **kwargs):
"""
:param user: 用户名
:param password: 密码
:param exe_path: 客户端路径, 类似
:param comm_password:
:param kwargs:
:return:
"""
if comm_password is None:
raise Val... |
雪球登陆, 需要设置 cookies: param cookies: 雪球登陆需要设置 cookies, 具体见 https:// smalltool. github. io/ 2016/ 08/ 02/ cookie/: return: | def login(self, user=None, password=None, **kwargs):
"""
雪球登陆, 需要设置 cookies
:param cookies: 雪球登陆需要设置 cookies, 具体见
https://smalltool.github.io/2016/08/02/cookie/
:return:
"""
cookies = kwargs.get('cookies')
if cookies is None:
raise TypeErro... |
跟踪 joinquant 对应的模拟交易,支持多用户多策略: param users: 支持 easytrader 的用户对象,支持使用 [] 指定多个用户: param strategies: 雪球组合名 类似 ZH123450: param total_assets: 雪球组合对应的总资产, 格式 [ 组合1对应资金 组合2对应资金 ] 若 strategies = [ ZH000001 ZH000002 ] 设置 total_assets = [ 10000 10000 ] 则表明每个组合对应的资产为 1w 元 假设组合 ZH000001 加仓 价格为 p 股票 A 10% 则对应的交易指令为 买入 股票 A 价格 P 股数 ... | 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_cache=True,
slippage: float = 0.0)... |
根据实际持仓值计算雪球卖出股数 因为雪球的交易指令是基于持仓百分比,在取近似值的情况下可能出现不精确的问题。 导致如下情况的产生,计算出的指令为买入 1049 股,取近似值买入 1000 股。 而卖出的指令计算出为卖出 1051 股,取近似值卖出 1100 股,超过 1000 股的买入量, 导致卖出失败: param stock_code: 证券代码: type stock_code: str: param amount: 卖出股份数: type amount: int: return: 考虑实际持仓之后的卖出股份数: rtype: int | def _adjust_sell_amount(self, stock_code, amount):
"""
根据实际持仓值计算雪球卖出股数
因为雪球的交易指令是基于持仓百分比,在取近似值的情况下可能出现不精确的问题。
导致如下情况的产生,计算出的指令为买入 1049 股,取近似值买入 1000 股。
而卖出的指令计算出为卖出 1051 股,取近似值卖出 1100 股,超过 1000 股的买入量,
导致卖出失败
:param stock_code: 证券代码
:type stock_code: str
... |
获取组合信息 | 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 match_info is N... |
parse cookies str to dict: param cookies: cookies str: type cookies: str: return: cookie dict: rtype: dict | def parse_cookies_str(cookies):
"""
parse cookies str to dict
:param cookies: cookies str
:type cookies: str
:return: cookie dict
:rtype: dict
"""
cookie_dict = {}
for record in cookies.split(";"):
key, value = record.strip().split("=", 1)
cookie_dict[key] = value
... |
判断股票ID对应的证券市场 匹配规则 [ 50 51 60 90 110 ] 为 sh [ 00 13 18 15 16 18 20 30 39 115 ] 为 sz [ 5 6 9 ] 开头的为 sh, 其余为 sz: param stock_code: 股票ID 若以 sz sh 开头直接返回对应类型,否则使用内置规则判断: return sh or sz | def get_stock_type(stock_code):
"""判断股票ID对应的证券市场
匹配规则
['50', '51', '60', '90', '110'] 为 sh
['00', '13', '18', '15', '16', '18', '20', '30', '39', '115'] 为 sz
['5', '6', '9'] 开头的为 sh, 其余为 sz
:param stock_code:股票ID, 若以 'sz', 'sh' 开头直接返回对应类型,否则使用内置规则判断
:return 'sh' or 'sz'"""
stock_code = s... |
识别验证码,返回识别后的字符串,使用 tesseract 实现: param image_path: 图片路径: param broker: 券商 [ ht yjb gf yh ]: return recognized: verify code string | def recognize_verify_code(image_path, broker="ht"):
"""识别验证码,返回识别后的字符串,使用 tesseract 实现
:param image_path: 图片路径
:param broker: 券商 ['ht', 'yjb', 'gf', 'yh']
:return recognized: verify code string"""
if broker == "gf":
return detect_gf_result(image_path)
if broker in ["yh_client", "gj_clie... |
封装了tesseract的识别,部署在阿里云上,服务端源码地址为: https:// github. com/ shidenggui/ yh_verify_code_docker | def detect_yh_client_result(image_path):
"""封装了tesseract的识别,部署在阿里云上,服务端源码地址为: https://github.com/shidenggui/yh_verify_code_docker"""
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:
... |
获得用于查询的默认日期 今天的日期 以及30天前的日期 用于查询的日期格式通常为 20160211: return: | def get_30_date():
"""
获得用于查询的默认日期, 今天的日期, 以及30天前的日期
用于查询的日期格式通常为 20160211
:return:
"""
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") |
查询今天可以申购的新股信息: return: 今日可申购新股列表 apply_code申购代码 price发行价格 | def get_today_ipo_data():
"""
查询今天可以申购的新股信息
:return: 今日可申购新股列表 apply_code申购代码 price发行价格
"""
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/jso... |
登陆接口: param user: 用户名: param password: 密码: param kwargs: 其他参数: return: | def login(self, user=None, password=None, **kwargs):
"""
登陆接口
:param user: 用户名
:param password: 密码
:param kwargs: 其他参数
:return:
"""
headers = self._generate_headers()
self.s.headers.update(headers)
# init cookie
self.s.get(self.LOG... |
跟踪平台对应的模拟交易,支持多用户多策略 | def follow(
self,
users,
strategies,
track_interval=1,
trade_cmd_expire_seconds=120,
cmd_cache=True,
slippage: float = 0.0,
**kwargs
):
"""跟踪平台对应的模拟交易,支持多用户多策略
:param users: 支持easytrader的用户对象,支持使用 [] 指定多个用户
:param strategies: 雪... |
计算考虑滑点之后的价格: param action: 交易动作, 支持 [ buy sell ]: param price: 原始交易价格: return: 考虑滑点后的交易价格 | def _calculate_price_by_slippage(self, action: str, price: float) -> float:
"""
计算考虑滑点之后的价格
:param action: 交易动作, 支持 ['buy', 'sell']
:param price: 原始交易价格
:return: 考虑滑点后的交易价格
"""
if action == "buy":
return price * (1 + self.slippage)
if action ==... |
跟踪下单worker: param strategy: 策略id: param name: 策略名字: param interval: 轮询策略的时间间隔,单位为秒 | def track_strategy_worker(self, strategy, name, interval=10, **kwargs):
"""跟踪下单worker
:param strategy: 策略id
:param name: 策略名字
:param interval: 轮询策略的时间间隔,单位为秒"""
while True:
try:
transactions = self.query_strategy_transaction(
strate... |
分发交易指令到对应的 user 并执行: param trade_cmd:: param users:: param expire_seconds:: param entrust_prop:: param send_interval:: return: | def _execute_trade_cmd(
self, trade_cmd, users, expire_seconds, entrust_prop, send_interval
):
"""分发交易指令到对应的 user 并执行
:param trade_cmd:
:param users:
:param expire_seconds:
:param entrust_prop:
:param send_interval:
:return:
"""
for use... |
: param send_interval: 交易发送间隔, 默认为0s。调大可防止卖出买入时买出单没有及时成交导致的买入金额不足 | def trade_worker(
self, users, expire_seconds=120, entrust_prop="limit", send_interval=0
):
"""
:param send_interval: 交易发送间隔, 默认为0s。调大可防止卖出买入时买出单没有及时成交导致的买入金额不足
"""
while True:
trade_cmd = self.trade_queue.get()
self._execute_trade_cmd(
... |
设置雪球 cookies,代码来自于 https:// github. com/ shidenggui/ easytrader/ issues/ 269: param cookies: 雪球 cookies: type cookies: str | def _set_cookies(self, cookies):
"""设置雪球 cookies,代码来自于
https://github.com/shidenggui/easytrader/issues/269
:param cookies: 雪球 cookies
:type cookies: str
"""
cookie_dict = helpers.parse_cookies_str(cookies)
self.s.cookies.update(cookie_dict) |
转换参数到登录所需的字典格式: param cookies: 雪球登陆需要设置 cookies, 具体见 https:// smalltool. github. io/ 2016/ 08/ 02/ cookie/: param portfolio_code: 组合代码: param portfolio_market: 交易市场, 可选 [ cn us hk ] 默认 cn: return: | def _prepare_account(self, user="", password="", **kwargs):
"""
转换参数到登录所需的字典格式
:param cookies: 雪球登陆需要设置 cookies, 具体见
https://smalltool.github.io/2016/08/02/cookie/
:param portfolio_code: 组合代码
:param portfolio_market: 交易市场, 可选['cn', 'us', 'hk'] 默认 'cn'
:return:... |
通过雪球的接口获取股票详细信息: param code: 股票代码 000001: return: 查询到的股票 { u stock_id: 1000279 u code: u SH600325 u name: u 华发股份 u ind_color: u #d9633b u chg: - 1. 09 u ind_id: 100014 u percent: - 9. 31 u current: 10. 62 u hasexist: None u flag: 1 u ind_name: u 房地产 u type: None u enName: None } ** flag: 未上市 ( 0 ) 、正常 ( 1 ) 、停牌 ( 2 ) 、... | def _search_stock_info(self, code):
"""
通过雪球的接口获取股票详细信息
:param code: 股票代码 000001
:return: 查询到的股票 {u'stock_id': 1000279, u'code': u'SH600325',
u'name': u'华发股份', u'ind_color': u'#d9633b', u'chg': -1.09,
u'ind_id': 100014, u'percent': -9.31, u'current': 10.62,
... |
获取组合信息: return: 字典 | def _get_portfolio_info(self, portfolio_code):
"""
获取组合信息
:return: 字典
"""
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... |
获取账户资金状况: return: | def get_balance(self):
"""
获取账户资金状况
:return:
"""
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"])
... |
获取雪球持仓: return: | def _get_position(self):
"""
获取雪球持仓
:return:
"""
portfolio_code = self.account_config["portfolio_code"]
portfolio_info = self._get_portfolio_info(portfolio_code)
position = portfolio_info["view_rebalancing"] # 仓位结构
stocks = position["holdings"] # 持仓股票
... |
获取持仓: return: | def get_position(self):
"""
获取持仓
:return:
"""
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... |
获取雪球调仓历史: param instance:: param owner:: return: | def _get_xq_history(self):
"""
获取雪球调仓历史
:param instance:
:param owner:
:return:
"""
data = {
"cube_symbol": str(self.account_config["portfolio_code"]),
"count": 20,
"page": 1,
}
resp = self.s.get(self.config["his... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.