code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
cmd_list = ['create', '--json']
if (name and prefix) or not (name or prefix):
raise TypeError("conda clone_environment: exactly one of `name` "
"or `path` required")
if name:
cmd_list.extend(['--name', name])
if prefix:
... | def clone_environment(self, clone, name=None, prefix=None, **kwargs) | Clone the environment `clone` into `name` or `prefix`. | 4.269341 | 4.246098 | 1.005474 |
cmd_list = ['--json', '--force']
if 'file' in kwargs:
cmd_list.extend(['--file', kwargs['file']])
if 'system' in kwargs:
cmd_list.append('--system')
return cmd_list | def _setup_config_from_kwargs(kwargs) | Setup config commands for conda. | 4.082415 | 3.510984 | 1.162755 |
cmd_list = ['config', '--add', key, value]
cmd_list.extend(self._setup_config_from_kwargs(kwargs))
return self._call_and_parse(
cmd_list,
abspath=kwargs.get('abspath', True),
callback=lambda o, e: o.get('warnings', [])) | def config_add(self, key, value, **kwargs) | Add a value to a key.
Returns a list of warnings Conda may have emitted. | 5.81047 | 5.240398 | 1.108784 |
if not pkgs or not isinstance(pkgs, (list, tuple)):
raise TypeError('must specify a list of one or more packages to '
'install into existing environment')
cmd_list = ['install', '--dry-run', '--json', '--force-pscheck']
if not dep:
c... | def dependencies(self, name=None, prefix=None, pkgs=None, channels=None,
dep=True) | Get dependenciy list for packages to be installed in an env. | 3.298255 | 3.166567 | 1.041587 |
if log:
logger.debug(str((name, prefix)))
if name and prefix:
raise TypeError("Exactly one of 'name' or 'prefix' is required.")
if name:
prefix = self.get_prefix_envname(name, log=log)
if prefix is None:
prefix = self.ROOT_PREFI... | def environment_exists(self, name=None, prefix=None, abspath=True,
log=True) | Check if an environment exists by 'name' or by 'prefix'.
If query is by 'name' only the default conda environments directory is
searched. | 3.533507 | 3.12845 | 1.129475 |
cmd_list = ['clean', '--lock', '--json']
return self._call_and_parse(cmd_list, abspath=abspath) | def clear_lock(self, abspath=True) | Clean any conda lock in the system. | 7.400096 | 7.022844 | 1.053718 |
package_versions = {}
if name and prefix:
raise TypeError("Exactly one of 'name' or 'prefix' is required.")
if name:
prefix = self.get_prefix_envname(name)
if self.environment_exists(prefix=prefix):
for package in self.linked(prefix):
... | def package_version(self, prefix=None, name=None, pkg=None, build=False) | Get installed package version in a given env. | 3.843477 | 3.655492 | 1.051425 |
_sys_map = {'linux2': 'linux', 'linux': 'linux',
'darwin': 'osx', 'win32': 'win', 'openbsd5': 'openbsd'}
non_x86_linux_machines = {'armv6l', 'armv7l', 'ppc64le'}
sys_platform = _sys_map.get(sys.platform, 'unknown')
bits = 8 * tuple.__itemsize__
if (... | def get_platform() | Get platform of current system (system and bitness). | 2.875468 | 2.764766 | 1.04004 |
if os.path.isfile(self.user_rc_path) and not system:
path = self.user_rc_path
elif os.path.isfile(self.sys_rc_path):
path = self.sys_rc_path
if not path or not os.path.isfile(path):
return {}
with open(path) as f:
return yaml.loa... | def load_rc(self, path=None, system=False) | Load the conda configuration file.
If both user and system configuration exists, user will be used. | 2.238574 | 2.031342 | 1.102017 |
# https://docs.continuum.io/anaconda-repository/configuration
# They can only exist on a system condarc
default_channels = self.load_rc(system=True).get('default_channels',
self.DEFAULT_CHANNELS)
normalized_channels = []
... | def get_condarc_channels(self,
normalize=False,
conda_url='https://conda.anaconda.org',
channels=None) | Return all the channel urls defined in .condarc.
If no condarc file is found, use the default channels.
the `default_channel_alias` key is ignored and only the anaconda client
`url` key is used. | 4.720896 | 4.07955 | 1.15721 |
cmd_list = self._pip_cmd(name=name, prefix=prefix)
cmd_list.extend(extra_args)
process_worker = ProcessWorker(cmd_list, pip=True, callback=callback)
process_worker.sig_finished.connect(self._start)
self._queue.append(process_worker)
self._start()
return... | def _call_pip(self, name=None, prefix=None, extra_args=None,
callback=None) | Call pip in QProcess worker. | 3.76468 | 3.507965 | 1.073181 |
if (name and prefix) or not (name or prefix):
raise TypeError("conda pip: exactly one of 'name' ""or 'prefix' "
"required.")
if name and self.environment_exists(name=name):
prefix = self.get_prefix_envname(name)
if sys.platform == 'w... | def _pip_cmd(self, name=None, prefix=None) | Get pip location based on environment `name` or `prefix`. | 3.493628 | 3.453036 | 1.011755 |
if (name and prefix) or not (name or prefix):
raise TypeError("conda pip: exactly one of 'name' ""or 'prefix' "
"required.")
if name:
prefix = self.get_prefix_envname(name)
pip_command = os.sep.join([prefix, 'bin', 'python'])
... | def pip_list(self, name=None, prefix=None, abspath=True) | Get list of pip installed packages. | 5.087629 | 5.075056 | 1.002478 |
result = stdout # A dict
linked = self.linked(prefix)
pip_only = []
linked_names = [self.split_canonical_name(l)[0] for l in linked]
for pkg in result:
name = self.split_canonical_name(pkg)[0]
if name not in linked_names:
pip_o... | def _pip_list(self, stdout, stderr, prefix=None) | Callback for `pip_list`. | 4.353161 | 4.379139 | 0.994068 |
logger.debug(str((prefix, pkgs)))
if isinstance(pkgs, (list, tuple)):
pkg = ' '.join(pkgs)
else:
pkg = pkgs
extra_args = ['uninstall', '--yes', pkg]
return self._call_pip(name=name, prefix=prefix, extra_args=extra_args) | def pip_remove(self, name=None, prefix=None, pkgs=None) | Remove a pip package in given environment by `name` or `prefix`. | 3.26052 | 3.354946 | 0.971855 |
extra_args = ['search', search_string]
return self._call_pip(name='root', extra_args=extra_args,
callback=self._pip_search) | def pip_search(self, search_string=None) | Search for pip packages in PyPI matching `search_string`. | 6.61567 | 6.317498 | 1.047198 |
result = {}
lines = to_text_string(stdout).split('\n')
while '' in lines:
lines.remove('')
for line in lines:
if ' - ' in line:
parts = line.split(' - ')
name = parts[0].strip()
description = parts[1].strip... | def _pip_search(stdout, stderr) | Callback for pip search. | 2.689933 | 2.691587 | 0.999385 |
self._timer_counter += 1
dot = self._timer_dots.pop(0)
self._timer_dots = self._timer_dots + [dot]
self._rows = [[_(u'Resolving dependencies') + dot, u'', u'', u'']]
index = self.createIndex(0, 0)
self.dataChanged.emit(index, index)
if self._timer_counte... | def _timer_update(self) | Add some moving points to the dependency resolution text. | 4.499979 | 3.756293 | 1.197984 |
if not index.isValid():
return Qt.ItemIsEnabled
column = index.column()
if column in [0, 1, 2, 3]:
return Qt.ItemFlags(Qt.ItemIsEnabled)
else:
return Qt.ItemFlags(Qt.NoItemFlags) | def flags(self, index) | Override Qt method | 2.226973 | 2.148031 | 1.036751 |
if not index.isValid() or not 0 <= index.row() < len(self._rows):
return to_qvariant()
row = index.row()
column = index.column()
# Carefull here with the order, this has to be adjusted manually
if self._rows[row] == row:
name, unlink, link, fetch... | def data(self, index, role=Qt.DisplayRole) | Override Qt method | 2.020037 | 2.006694 | 1.006649 |
error, output = None, None
try:
time.sleep(0.1)
output = self.method(*self.args, **self.kwargs)
except Exception as err:
logger.debug(str((self.method.__module__, self.method.__name__,
err)))
error = str(err)
... | def start(self) | Start the worker process. | 3.376899 | 3.281599 | 1.029041 |
# FIXME: this might be heavy...
thread = QThread()
worker = ClientWorker(method, args, kwargs)
worker.moveToThread(thread)
worker.sig_finished.connect(self._start)
worker.sig_finished.connect(thread.quit)
thread.started.connect(worker.start)
self.... | def _create_worker(self, method, *args, **kwargs) | Create a worker for this client to be run in a separate thread. | 3.306937 | 3.144921 | 1.051517 |
extra_data = extra_data if extra_data else {}
metadata = metadata if metadata else {}
repodata = []
for filepath in filepaths:
compressed = filepath.endswith('.bz2')
mode = 'rb' if filepath.endswith('.bz2') else 'r'
if os.path.isfile(filepath... | def _load_repodata(filepaths, extra_data=None, metadata=None) | Load all the available pacakges information.
For downloaded repodata files (repo.continuum.io), additional
data provided (anaconda cloud), and additional metadata and merge into
a single set of packages and apps. | 2.474232 | 2.451965 | 1.009082 |
pip = pip if pip else []
private_packages = private_packages if private_packages else {}
data = []
if private_packages is not None:
for pkg in private_packages:
if pkg in packages:
p_data = packages.get(pkg)
v... | def _prepare_model_data(packages, linked, pip=None,
private_packages=None) | Prepare model data for the packages table model. | 2.160108 | 2.159622 | 1.000225 |
logger.debug(str((username, application, application_url)))
method = self._anaconda_client_api.authenticate
return self._create_worker(method, username, password, application,
application_url) | def login(self, username, password, application, application_url) | Login to anaconda cloud. | 7.733205 | 7.02688 | 1.100518 |
logger.debug('Logout')
method = self._anaconda_client_api.remove_authentication
return self._create_worker(method) | def logout(self) | Logout from anaconda cloud. | 22.228416 | 16.688175 | 1.331986 |
logger.debug(str((filepaths)))
method = self._load_repodata
return self._create_worker(method, filepaths, extra_data=extra_data,
metadata=metadata) | def load_repodata(self, filepaths, extra_data=None, metadata=None) | Load all the available pacakges information for downloaded repodata.
Files include repo.continuum.io, additional data provided (anaconda
cloud), and additional metadata and merge into a single set of packages
and apps. | 5.746275 | 6.379881 | 0.900687 |
logger.debug('')
return self._prepare_model_data(packages, linked, pip=pip,
private_packages=private_packages) | def prepare_model_data(self, packages, linked, pip=None,
private_packages=None) | Prepare downloaded package info along with pip pacakges info. | 3.603146 | 3.484817 | 1.033955 |
logger.debug(str((domain)))
config = binstar_client.utils.get_config()
config['url'] = domain
binstar_client.utils.set_config(config)
self._anaconda_client_api = binstar_client.utils.get_server_api(
token=None, log_level=logging.NOTSET)
return self.... | def set_domain(self, domain='https://api.anaconda.org') | Reset current api domain. | 5.741488 | 5.454131 | 1.052686 |
logger.debug('')
method = self._anaconda_client_api.user_packages
return self._create_worker(method, login=login, platform=platform,
package_type=package_type,
type_=type_, access=access) | def packages(self, login=None, platform=None, package_type=None,
type_=None, access=None) | Return all the available packages for a given user.
Parameters
----------
type_: Optional[str]
Only find packages that have this conda `type`, (i.e. 'app').
access : Optional[str]
Only find packages that have this access level (e.g. 'private',
'authen... | 5.735546 | 6.118492 | 0.937412 |
private_packages = {}
if not new_client:
time.sleep(0.3)
return private_packages
for login in logins:
data = self._anaconda_client_api.user_packages(
login=login,
platform=platform,
package_type=packag... | def _multi_packages(self, logins=None, platform=None, package_type=None,
type_=None, access=None, new_client=True) | Return the private packages for a given set of usernames/logins. | 3.048091 | 2.973299 | 1.025155 |
logger.debug('')
method = self._multi_packages
new_client = True
try:
# Only the newer versions have extra keywords like `access`
self._anaconda_client_api.user_packages(access='private')
except Exception:
new_client = False
... | def multi_packages(self, logins=None, platform=None, package_type=None,
type_=None, access=None) | Return the private packages for a given set of usernames/logins. | 6.46167 | 6.480448 | 0.997102 |
gc = GeonamesCache()
dataset = gc.get_dataset_by_key(gc.get_countries(), from_key)
def mapper(input):
# For country name inputs take the names mapping into account.
if 'name' == from_key:
input = mappings.country_names.get(input, input)
# If there is a record retur... | def country(from_key='name', to_key='iso') | Creates and returns a mapper function to access country data.
The mapper function that is returned must be called with one argument. In
the default case you call it with a name and it returns a 3-letter
ISO_3166-1 code, e. g. called with ``Spain`` it would return ``ESP``.
:param from_key: (optional) t... | 6.795725 | 6.877576 | 0.988099 |
if self.cities is None:
self.cities = self._load_data(self.cities, 'cities.json')
return self.cities | def get_cities(self) | Get a dictionary of cities keyed by geonameid. | 5.175664 | 4.366331 | 1.185358 |
if name not in self.cities_by_names:
if self.cities_items is None:
self.cities_items = list(self.get_cities().items())
self.cities_by_names[name] = [dict({gid: city})
for gid, city in self.cities_items if city['name'] == name]
return self... | def get_cities_by_name(self, name) | Get a list of city dictionaries with the given name.
City names cannot be used as keys, as they are not unique. | 3.234654 | 3.152261 | 1.026138 |
repos = []
sys_platform = self._conda_api.get_platform()
for channel in channels:
url = '{0}/{1}/repodata.json.bz2'.format(channel, sys_platform)
repos.append(url)
return repos | def _set_repo_urls_from_channels(self, channels) | Convert a channel into a normalized repo name including.
Channels are assumed in normalized url form. | 5.03077 | 4.862895 | 1.034521 |
self._checking_repos = []
self._valid_repos = []
for repo in repos:
worker = self.download_is_valid_url(repo)
worker.sig_finished.connect(self._repos_checked)
worker.repo = repo
self._checking_repos.append(repo) | def _check_repos(self, repos) | Check if repodata urls are valid. | 5.738648 | 5.124694 | 1.119803 |
if worker.repo in self._checking_repos:
self._checking_repos.remove(worker.repo)
if output:
self._valid_repos.append(worker.repo)
if len(self._checking_repos) == 0:
self._download_repodata(self._valid_repos) | def _repos_checked(self, worker, output, error) | Callback for _check_repos. | 3.174783 | 3.122065 | 1.016886 |
repo = repo.replace('http://', '')
repo = repo.replace('https://', '')
repo = repo.replace('/', '_')
return os.sep.join([self._data_directory, repo]) | def _repo_url_to_path(self, repo) | Convert a `repo` url to a file path for local storage. | 3.143652 | 2.74167 | 1.14662 |
self._files_downloaded = []
self._repodata_files = []
self.__counter = -1
if checked_repos:
for repo in checked_repos:
path = self._repo_url_to_path(repo)
self._files_downloaded.append(path)
self._repodata_files.append... | def _download_repodata(self, checked_repos) | Dowload repodata. | 4.348424 | 4.266712 | 1.019151 |
path = os.sep.join([self.ROOT_PREFIX, 'conda-meta'])
packages = os.listdir(path)
meta_repodata = {}
for pkg in packages:
if pkg.endswith('.json'):
filepath = os.sep.join([path, pkg])
with open(filepath, 'r') as f:
d... | def _get_repodata_from_meta(self) | Generate repodata from local meta files. | 2.641183 | 2.512801 | 1.051091 |
if worker:
self._files_downloaded.remove(worker.path)
if worker.path in self._files_downloaded:
self._files_downloaded.remove(worker.path)
if len(self._files_downloaded) == 0:
self.sig_repodata_updated.emit(list(set(self._repodata_files))) | def _repodata_downloaded(self, worker=None, output=None, error=None) | Callback for _download_repodata. | 3.150442 | 3.06426 | 1.028125 |
if channels is None:
channels = self.conda_get_condarc_channels()
repodata_urls = self._set_repo_urls_from_channels(channels)
repopaths = []
for repourl in repodata_urls:
fullpath = os.sep.join([self._repo_url_to_path(repourl)])
repopaths.a... | def repodata_files(self, channels=None) | Return the repodata paths based on `channels` and the `data_directory`.
There is no check for validity here. | 3.884076 | 3.716061 | 1.045213 |
norm_channels = self.conda_get_condarc_channels(channels=channels,
normalize=True)
repodata_urls = self._set_repo_urls_from_channels(norm_channels)
self._check_repos(repodata_urls) | def update_repodata(self, channels=None) | Update repodata from channels or use condarc channels if None. | 6.894526 | 5.65239 | 1.219754 |
if self._data_directory is None:
raise Exception('Need to call `api.set_data_directory` first.')
metadata_url = 'https://repo.continuum.io/pkgs/metadata.json'
filepath = os.sep.join([self._data_directory, 'metadata.json'])
worker = self.download_requests(metadata_ur... | def update_metadata(self) | Update the metadata available for packages in repo.continuum.io.
Returns a download worker. | 5.886307 | 4.195317 | 1.403066 |
if channel.startswith('https://') or channel.startswith('http://'):
url = channel
else:
url = "{0}/{1}".format(conda_url, channel)
if url[-1] == '/':
url = url[:-1]
plat = self.conda_platform()
repodata_url = "{0}/{1}/{2}".format(url,... | def check_valid_channel(self,
channel,
conda_url='https://conda.anaconda.org') | Check if channel is valid. | 3.138301 | 3.169611 | 0.990122 |
client = boto3.session.Session().client('ec2', region)
matching_reservations = client.describe_instances(Filters=[{'Name': tag, 'Values': [name]}]).get('Reservations', [])
instances = []
[[instances.append(_aws_instance_from_dict(region, instance, raw)) # pylint: disable=expression-not-assigned
... | def _aws_get_instance_by_tag(region, name, tag, raw) | Get all instances matching a tag. | 2.879188 | 2.826283 | 1.018719 |
client = boto3.session.Session().client('ec2', region)
try:
matching_reservations = client.describe_instances(InstanceIds=[instance_id]).get('Reservations', [])
except ClientError as exc:
if exc.response.get('Error', {}).get('Code') != 'InvalidInstanceID.NotFound':
raise
... | def aws_get_instances_by_id(region, instance_id, raw=True) | Returns instances mathing an id. | 2.598401 | 2.594011 | 1.001692 |
matching_instances = all_clouds_get_instances_by_name(
name, projects, raw, credentials=gcp_credentials, clouds=clouds)
if regions:
matching_instances = [instance for instance in matching_instances if instance.region in regions]
matching_instances.sort(key=lambda instance: [getattr(inst... | def get_instances_by_name(name, sort_by_order=('cloud', 'name'), projects=None, raw=True, regions=None, gcp_credentials=None, clouds=SUPPORTED_CLOUDS) | Get intsances from GCP and AWS by name. | 2.606095 | 2.631646 | 0.990291 |
if instance.cloud == 'aws':
client = boto3.client('ec2', instance.region)
image_id = client.describe_instances(InstanceIds=[instance.id])['Reservations'][0]['Instances'][0]['ImageId']
return '16.04' if '16.04' in client.describe_images(ImageIds=[image_id])['Images'][0]['Name'] else '14.... | def get_os_version(instance) | Get OS Version for instances. | 2.016201 | 2.002509 | 1.006837 |
if instance.cloud == 'aws':
client = boto3.client('ec2', instance.region)
devices = client.describe_instance_attribute(
InstanceId=instance.id, Attribute='blockDeviceMapping').get('BlockDeviceMappings', [])
volumes = client.describe_volumes(VolumeIds=[device['Ebs']['VolumeId... | def get_volumes(instance) | Returns all the volumes of an instance. | 2.255414 | 2.25407 | 1.000596 |
if instance.cloud == 'aws':
client = boto3.client('ec2', instance.region)
try:
client.describe_addresses(PublicIps=[instance.ip_address])
return instance.ip_address
except botocore.client.ClientError as exc:
if exc.response.get('Error', {}).get('Code'... | def get_persistent_address(instance) | Returns the public ip address of an instance. | 2.340518 | 2.283539 | 1.024952 |
pip_packages = {}
for package in pip.get_installed_distributions():
name = package.project_name
version = package.version
full_name = "{0}-{1}-pip".format(name.lower(), version)
pip_packages[full_name] = {'version': version}
data = json.dumps(pip_packages)
print(data... | def main() | Use pip to find pip installed packages in a given prefix. | 3.136747 | 2.715067 | 1.155311 |
with open(file, mode) as fh:
fh.write(data) | def _save(file, data, mode='w+') | Write all data to created file. Also overwrite previous file. | 2.942798 | 3.61846 | 0.813274 |
merge = ''
for f in obj.get('static', []):
print 'Merging: {}'. format(f)
merge += _read(f)
def doless(f):
print 'Compiling LESS: {}'.format(f)
ret, tmp = commands.getstatusoutput('lesscpy '+f)
if ret == 0:
return tmp
else:
prin... | def merge(obj) | Merge contents.
It does a simply merge of all files defined under 'static' key.
If you have JS or CSS file with embeded django tags like {% url ... %} or
{% static ... %} you should declare them under 'template' key. This
function will render them and append to the merged output.
To use the rende... | 4.397793 | 3.945421 | 1.114657 |
print 'Minifying JS... ',
url = 'http://javascript-minifier.com/raw' #POST
req = urllib2.Request(url, urllib.urlencode({'input': data}))
try:
f = urllib2.urlopen(req)
response = f.read()
f.close()
print 'Final: {:.1f}%'.format(100.0*len(response)/len(data))
p... | def jsMin(data, file) | Minify JS data and saves to file.
Data should be a string will whole JS content, and file will be
overwrited if exists. | 3.428528 | 3.575267 | 0.958957 |
if not os.path.isfile(file+'.original') or force:
data = _read(file, 'rb')
_save(file+'.original', data, 'w+b')
print 'Optmising JPG {} - {:.2f}kB'.format(file, len(data)/1024.0),
url = 'http://jpgoptimiser.com/optimise'
parts, headers = encode_multipart({}, {'input': {'... | def jpgMin(file, force=False) | Try to optimise a JPG file.
The original will be saved at the same place with '.original' appended to its name.
Once a .original exists the function will ignore this file unless force is True. | 3.796687 | 3.560762 | 1.066257 |
r
def escape_quote(s):
return s.replace('"', '\\"')
if boundary is None:
boundary = ''.join(random.choice(string.digits + string.ascii_letters) for i in range(30))
lines = []
for name, value in fields.items():
lines.extend((
'--{0}'.format(boundary),
... | def encode_multipart(fields, files, boundary=None) | r"""Encode dict of form fields and dict of files as multipart/form-data.
Return tuple of (body_string, headers_dict). Each value in files is a dict
with required keys 'filename' and 'content', and optional 'mimetype' (if
not specified, tries to guess mime type or uses 'application/octet-stream').
>>> b... | 1.462651 | 1.505381 | 0.971615 |
#merge all static and templates and less files
merged = merge(obj)
#save the full file if name defined
if obj.get('full'):
print 'Saving: {} ({:.2f}kB)'.format(obj['full'], len(merged)/1024.0)
_save(obj['full'], merged)
else:
print 'Full merged size: {:.2f}kB'.format(le... | def process(obj) | Process each block of the merger object. | 4.056731 | 4.142638 | 0.979263 |
_cov_inv = np.linalg.inv(covs)
# unit vector
_u = np.ones((len(exp_rets)))
# compute some dot products one time only
_u_cov_inv = _u.dot(_cov_inv)
_rets_cov_inv = exp_rets.dot(_cov_inv)
# helper matrix for deriving Lagrange multipliers
_m = np.empty((2, 2))
_m[0, 0] =... | def optimize(exp_rets, covs) | Return parameters for portfolio optimization.
Parameters
----------
exp_rets : ndarray
Vector of expected returns for each investment..
covs : ndarray
Covariance matrix for the given investments.
Returns
---------
a : ndarray
The first vector (to be combined with ta... | 2.337513 | 2.192829 | 1.065981 |
_yrs = (pd.Timestamp(enddate) - pd.Timestamp(startdate)).total_seconds() /\
dt.timedelta(365.25).total_seconds()
return yrlygrowth(rangegrowth, _yrs) | def growthfromrange(rangegrowth, startdate, enddate) | Annual growth given growth from start date to end date. | 4.620478 | 4.551166 | 1.01523 |
nasdaqblob, otherblob = _getrawdata()
eq_triples = []
eq_triples.extend(_get_nas_triples(nasdaqblob))
eq_triples.extend(_get_other_triples(otherblob))
eq_triples.sort()
index = [triple[0] for triple in eq_triples]
data = [triple[1:] for triple in eq_triples]
return pd.DataFrame(data... | def equities(country='US') | Return a DataFrame of current US equities.
.. versionadded:: 0.4.0
.. versionchanged:: 0.5.0
Return a DataFrame
Parameters
----------
country : str, optional
Country code for equities to return, defaults to 'US'.
Returns
-------
eqs : :class:`pandas.DataFrame`
... | 5.013999 | 4.986677 | 1.005479 |
assert lowstrike < highstrike
_rows = {}
_prices = {}
_opttype = 'call'
for _strike in (lowstrike, highstrike):
_rows[_strike] = _relevant_rows(self.data, (_strike, expiry, _opttype,),
"No key for {} strike {} {}".format(expiry, _strike, _... | def call(self, lowstrike, highstrike, expiry) | Metrics for evaluating a bull call spread.
The metrics returned can easily be translated into bear
spread metrics. The difference is only whether one buys
the call at the lower strike and sells at the higher
(bull call spread) or sells at the lower while buying
at the hi... | 4.106446 | 4.574528 | 0.897677 |
_rows = {}
_prices = {}
for _opttype in _constants.OPTTYPES:
_rows[_opttype] = _relevant_rows(self.data, (strike, expiry, _opttype,),
"No key for {} strike {} {}".format(expiry, strike, _opttype))
_prices[_opttype] = _getprice(_rows[_opttype])... | def straddle(self, strike, expiry) | Metrics for evaluating a straddle.
Parameters
------------
strike : numeric
Strike price.
expiry : date or date str (e.g. '2015-01-01')
Expiration date.
Returns
------------
metrics : DataFrame
Metrics for evaluating straddle. | 4.279574 | 4.678574 | 0.914718 |
_optmeta = pdr.data.Options(equity, 'yahoo')
_optdata = _optmeta.get_all_data()
return Options(_optdata) | def get(equity) | Retrieve all current options chains for given equity.
.. versionchanged:: 0.5.0
Eliminate special exception handling.
Parameters
-------------
equity : str
Equity for which to retrieve options data.
Returns
-------------
optdata : :class:`~pynance.opt.core.Options`
... | 11.126022 | 20.624578 | 0.539455 |
norm = kwargs.get('norm', 1.0)
axis = kwargs.get('axis', 0)
if axis == 0:
norm_vector = _get_norms_of_rows(data_frame, kwargs.get('method', 'vector'))
else:
norm_vector = _get_norms_of_cols(data_frame, kwargs.get('method', 'first'))
if 'labels' in kwargs:
if axis == 0:
... | def transform(data_frame, **kwargs) | Return a transformed DataFrame.
Transform data_frame along the given axis. By default, each row will be normalized (axis=0).
Parameters
-----------
data_frame : DataFrame
Data to be normalized.
axis : int, optional
0 (default) to normalize each row, 1 to normalize each column.
... | 2.513131 | 2.099163 | 1.197206 |
if method == 'vector':
norm_vector = np.linalg.norm(data_frame.values, axis=1)
elif method == 'last':
norm_vector = data_frame.iloc[:, -1].values
elif method == 'mean':
norm_vector = np.mean(data_frame.values, axis=1)
elif method == 'first':
norm_vector = data_frame.... | def _get_norms_of_rows(data_frame, method) | return a column vector containing the norm of each row | 1.979042 | 1.932481 | 1.024094 |
quotes = df.reset_index()
quotes.loc[:, 'Date'] = mdates.date2num(quotes.loc[:, 'Date'].astype(dt.date))
fplt.candlestick_ohlc(ax, quotes.values) | def _candlestick_ax(df, ax) | # Alternatively: (but hard to get dates set up properly)
plt.xticks(range(len(df.index)), df.index, rotation=45)
fplt.candlestick2_ohlc(ax, df.loc[:, 'Open'].values, df.loc[:, 'High'].values,
df.loc[:, 'Low'].values, df.loc[:, 'Close'].values, width=0.2) | 4.33453 | 3.776435 | 1.147784 |
_optrow = _relevant_rows(self.data, (strike, expiry, opttype,),
"No key for {} strike {} {}".format(expiry, strike, opttype))
return _getprice(_optrow) | def get(self, opttype, strike, expiry) | Price as midpoint between bid and ask.
Parameters
----------
opttype : str
'call' or 'put'.
strike : numeric
Strike price.
expiry : date-like
Expiration date. Can be a :class:`datetime.datetime` or
a string that :mod:`pandas` can i... | 15.262062 | 29.689779 | 0.514051 |
_optrow = _relevant_rows(self.data, (strike, expiry, opttype,),
"No key for {} strike {} {}".format(expiry, strike, opttype))
_index = ['Opt_Price', 'Time_Val', 'Last', 'Bid', 'Ask', 'Vol', 'Open_Int', 'Underlying_Price', 'Quote_Time']
_out = pd.DataFrame(index=_index, c... | def metrics(self, opttype, strike, expiry) | Basic metrics for a specific option.
Parameters
----------
opttype : str ('call' or 'put')
strike : numeric
Strike price.
expiry : date-like
Expiration date. Can be a :class:`datetime.datetime` or
a string that :mod:`pandas` can interpret as s... | 3.779618 | 3.942899 | 0.958589 |
_relevant = _relevant_rows(self.data, (slice(None), expiry, opttype,),
"No key for {} {}".format(expiry, opttype))
_index = _relevant.index.get_level_values('Strike')
_columns = ['Price', 'Time_Val', 'Last', 'Bid', 'Ask', 'Vol', 'Open_Int']
_df = pd.DataFrame(ind... | def strikes(self, opttype, expiry) | Retrieve option prices for all strikes of a given type with a given expiration.
Parameters
----------
opttype : str ('call' or 'put')
expiry : date-like
Expiration date. Can be a :class:`datetime.datetime` or
a string that :mod:`pandas` can interpret as such, e.g... | 4.230016 | 4.368905 | 0.96821 |
_relevant = _relevant_rows(self.data, (strike, slice(None), opttype,),
"No key for {} {}".format(strike, opttype))
_index = _relevant.index.get_level_values('Expiry')
_columns = ['Price', 'Time_Val', 'Last', 'Bid', 'Ask', 'Vol', 'Open_Int']
_df = pd.DataFrame(ind... | def exps(self, opttype, strike) | Prices for given strike on all available dates.
Parameters
----------
opttype : str ('call' or 'put')
strike : numeric
Returns
----------
df : :class:`pandas.DataFrame`
eq : float
Price of underlying.
qt : :class:`datetime.datetime`
... | 4.56682 | 4.469864 | 1.021691 |
_size = len(eqdata.index)
_labels, _skipatend = labelfunc(eqdata)
_features, _skipatstart = featurefunc(eqdata.iloc[:(_size - _skipatend), :])
return _features, _labels.iloc[_skipatstart:, :] | def labeledfeatures(eqdata, featurefunc, labelfunc) | Return features and labels for the given equity data.
Each row of the features returned contains `2 * n_sessions + 1` columns
(or 1 less if the constant feature is excluded). After the constant feature,
if present, there will be `n_sessions` columns derived from daily growth
of the given price column, ... | 4.510326 | 3.448866 | 1.307771 |
size = len(eqdata.index)
labeldata = eqdata.loc[:, pricecol].values[interval:] /\
eqdata.loc[:, pricecol].values[:(size - interval)]
df = pd.DataFrame(data=labeldata, index=eqdata.index[:(size - interval)],
columns=['Growth'], dtype='float64')
return df | def growth(interval, pricecol, eqdata) | Retrieve growth labels.
Parameters
--------------
interval : int
Number of sessions over which growth is measured. For example, if
the value of 32 is passed for `interval`, the data returned will
show the growth 32 sessions ahead for each data point.
eqdata : DataFrame
... | 3.76385 | 4.566834 | 0.824171 |
if len(eqdata.shape) > 1 and eqdata.shape[1] != 1:
_selection = kwargs.get('selection', 'Adj Close')
_eqdata = eqdata.loc[:, _selection]
else:
_eqdata = eqdata
_window = kwargs.get('window', 20)
_outputcol = kwargs.get('outputcol', 'SMA')
ret = pd.DataFrame(index=_eqdata... | def sma(eqdata, **kwargs) | simple moving average
Parameters
----------
eqdata : DataFrame
window : int, optional
Lookback period for sma. Defaults to 20.
outputcol : str, optional
Column to use for output. Defaults to 'SMA'.
selection : str, optional
Column of eqdata on which to calculate sma. If... | 2.577312 | 2.160621 | 1.192857 |
if len(eqdata.shape) > 1 and eqdata.shape[1] != 1:
_selection = kwargs.get('selection', 'Adj Close')
_eqdata = eqdata.loc[:, _selection]
else:
_eqdata = eqdata
_span = kwargs.get('span', 20)
_col = kwargs.get('outputcol', 'EMA')
_emadf = pd.DataFrame(index=_eqdata.index,... | def ema(eqdata, **kwargs) | Exponential moving average with the given span.
Parameters
----------
eqdata : DataFrame
Must have exactly 1 column on which to calculate EMA
span : int, optional
Span for exponential moving average. Cf. `pandas.stats.moments.ewma
<http://pandas.pydata.org/pandas-docs/stable/ge... | 2.620738 | 2.131195 | 1.229703 |
_growth_outputcol = kwargs.get('outputcol', 'EMA Growth')
_ema_outputcol = 'EMA'
kwargs['outputcol'] = _ema_outputcol
_emadf = ema(eqdata, **kwargs)
return simple.growth(_emadf, selection=_ema_outputcol, outputcol=_growth_outputcol) | def ema_growth(eqdata, **kwargs) | Growth of exponential moving average.
Parameters
----------
eqdata : DataFrame
span : int, optional
Span for exponential moving average. Defaults to 20.
outputcol : str, optional.
Column to use for output. Defaults to 'EMA Growth'.
selection : str, optional
Column of eqd... | 5.561522 | 5.132318 | 1.083628 |
if len(eqdata.shape) > 1 and eqdata.shape[1] != 1:
_selection = kwargs.get('selection', 'Adj Close')
_eqdata = eqdata.loc[:, _selection]
else:
_eqdata = eqdata
_window = kwargs.get('window', 20)
_colname = kwargs.get('outputcol', 'Risk')
_risk = pd.DataFrame(index=_eqdat... | def volatility(eqdata, **kwargs) | Volatility (standard deviation) over the given window
Parameters
----------
eqdata : DataFrame
window : int, optional
Lookback period. Defaults to 20.
outputcol : str, optional
Name of column to be used in returned dataframe. Defaults to 'Risk'.
selection : str, optional
... | 2.800984 | 2.227616 | 1.257391 |
_window = kwargs.get('window', 20)
_selection = kwargs.get('selection', 'Adj Close')
_outputcol = kwargs.get('outputcol', 'Growth Risk')
_growthdata = simple.growth(eqdata, selection=_selection)
return volatility(_growthdata, outputcol=_outputcol, window=_window) | def growth_volatility(eqdata, **kwargs) | Return the volatility of growth.
Note that, like :func:`pynance.tech.simple.growth` but in contrast to
:func:`volatility`, :func:`growth_volatility`
applies directly to a dataframe like that returned by
:func:`pynance.data.retrieve.get`, not necessarily to a single-column dataframe.
Parameters
... | 4.643954 | 2.668772 | 1.740109 |
_window = kwargs.get('window', 20)
_multiple = kwargs.get('multiple', 2.)
_selection = kwargs.get('selection', 'Adj Close')
# ensures correct name for output column of sma()
kwargs['outputcol'] = 'SMA'
_smadf = sma(eqdata, **kwargs)
_sigmas = eqdata.loc[:, _selection].rolling(center=Fal... | def bollinger(eqdata, **kwargs) | Bollinger bands
Returns bolldf, smadf where bolldf is a DataFrame containing
Bollinger bands with columns 'Upper' and 'Lower' and smadf contains
the simple moving average.
Parameters
----------
eqdata : DataFrame
Must include a column specified in the `selection` parameter or,
... | 3.465214 | 2.74945 | 1.26033 |
_selection = kwargs.get('selection', 'Volume')
_skipstartrows = kwargs.get('skipstartrows', 0)
_skipendrows = kwargs.get('skipendrows', 0)
_outputcol = kwargs.get('outputcol', 'Ratio to Ave')
_size = len(eqdata.index)
_eqdata = eqdata.loc[:, _selection]
_sma = _eqdata.iloc[:-1 - _skipe... | def ratio_to_ave(window, eqdata, **kwargs) | Return values expressed as ratios to the average over some number
of prior sessions.
Parameters
----------
eqdata : DataFrame
Must contain a column with name matching `selection`, or, if
`selection` is not specified, a column named 'Volume'
window : int
Interval over which t... | 3.170855 | 2.499673 | 1.268508 |
n_col = (features.shape[1] if len(features.shape) > 1 else 1)
reg_matrix = regularization * np.identity(n_col, dtype='float64')
if constfeat:
reg_matrix[0, 0] = 0.
# http://stackoverflow.com/questions/27476933/numpy-linear-regression-with-regularization
return np.linalg.lstsq(features.T... | def run(features, labels, regularization=0., constfeat=True) | Run linear regression on the given data.
.. versionadded:: 0.5.0
If a regularization parameter is provided, this function
is a simplification and specialization of ridge
regression, as implemented in `scikit-learn
<http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.Ridge.html#sk... | 2.676921 | 3.161104 | 0.846831 |
assert pd.Timestamp(exp1) < pd.Timestamp(exp2)
_row1 = _relevant_rows(self.data, (strike, exp1, opttype,),
"No key for {} strike {} {}".format(exp1, strike, opttype))
_row2 = _relevant_rows(self.data, (strike, exp2, opttype,),
"No key for {} strike {} {}"... | def cal(self, opttype, strike, exp1, exp2) | Metrics for evaluating a calendar spread.
Parameters
------------
opttype : str ('call' or 'put')
Type of option on which to collect data.
strike : numeric
Strike price.
exp1 : date or date str (e.g. '2015-01-01')
Earlier expiration date.
... | 3.462203 | 3.690449 | 0.938152 |
#Benchmarking
#>>> s = 'from __main__ import data\nimport datetime as dt\n'
#>>> timeit.timeit('data.featurize(data.get("ge", dt.date(1960, 1, 1),
# dt.date(2014, 12, 31)), 256)', setup=s, number=1)
#1.6771750450134277
columns = kwargs.get('columns', map(str, range(-n_sessions + 1, ... | def featurize(equity_data, n_sessions, **kwargs) | Generate a raw (unnormalized) feature set from the input data.
The value at `column` on the given date is taken
as a feature, and each row contains values for n_sessions
Parameters
-----------
equity_data : DataFrame
data from which to generate features
n_sessions : int
number ... | 4.040042 | 3.849692 | 1.049446 |
def _wrapper(*_args, **kwargs):
_ret = fn(*_args, **kwargs)
if isinstance(_ret, tuple):
return _ret + args
if len(args) == 0:
return _ret
return (_ret,) + args
for key, value in kwargs.items():
_wrapper.__dict__[key] = value
return _wrappe... | def decorate(fn, *args, **kwargs) | Return a new function that replicates the behavior of the input
but also returns an additional value. Used for creating functions
of the proper type to pass to `labeledfeatures()`.
Parameters
----------
fn : function
*args : any
Additional parameters that the returned function will ret... | 2.693688 | 3.112588 | 0.865418 |
if inputtype == pd.DataFrame:
if isinstance(col, int):
def _wrapper(*args, **kwargs):
return fn(args[0].iloc[:, col], *args[1:], **kwargs)
return _wrapper
def _wrapper(*args, **kwargs):
return fn(args[0].loc[:, col], *args[1:], **kwargs)
... | def expand(fn, col, inputtype=pd.DataFrame) | Wrap a function applying to a single column to make a function
applying to a multi-dimensional dataframe or ndarray
Parameters
----------
fn : function
Function that applies to a series or vector.
col : str or int
Index of column to which to apply `fn`.
inputtype : class or ty... | 1.738576 | 1.771714 | 0.981296 |
if isinstance(eqdata, pd.DataFrame):
_values = eqdata.values
else:
_values = eqdata
return len(_values[pd.isnull(_values)]) > 0 | def has_na(eqdata) | Return false if `eqdata` contains no missing values.
Parameters
----------
eqdata : DataFrame or ndarray
Data to check for missing values (NaN, None)
Returns
----------
answer : bool
False iff `eqdata` contains no missing values. | 3.258091 | 4.00698 | 0.813104 |
content = np.empty((features.shape[0], features.shape[1] + 1), dtype='float64')
content[:, 0] = 1.
if isinstance(features, np.ndarray):
content[:, 1:] = features
return content
content[:, 1:] = features.iloc[:, :].values
cols = ['Constant'] + features.columns.tolist()
return... | def add_const(features) | Prepend the constant feature 1 as first feature and return the modified
feature set.
Parameters
----------
features : ndarray or DataFrame | 2.696011 | 2.910749 | 0.926226 |
_constfeat = kwargs.get('constfeat', True)
_outcols = ['Constant'] if _constfeat else []
_n_rows = len(eqdata.index)
for _col in selection:
_outcols += map(partial(_concat, strval=' ' + _col), range(-n_sessions + 1, 1))
_features = pd.DataFrame(index=eqdata.index[n_sessions - 1:], colum... | def fromcols(selection, n_sessions, eqdata, **kwargs) | Generate features from selected columns of a dataframe.
Parameters
----------
selection : list or tuple of str
Columns to be used as features.
n_sessions : int
Number of sessions over which to create features.
eqdata : DataFrame
Data from which to generate feature set. Mus... | 3.020145 | 2.911054 | 1.037475 |
_skipatstart = kwargs.get('skipatstart', 0)
_constfeat = kwargs.get('constfeat', True)
_outcols = ['Constant'] if _constfeat else []
_n_allrows = len(eqdata.index)
_n_featrows = _n_allrows - _skipatstart - n_sessions + 1
for _func in funcs:
_outcols += map(partial(_concat, strval=' ... | def fromfuncs(funcs, n_sessions, eqdata, **kwargs) | Generate features using a list of functions to apply to input data
Parameters
----------
funcs : list of function
Functions to apply to eqdata. Each function is expected
to output a dataframe with index identical to a slice of `eqdata`.
The slice must include at least `eqdata.index[... | 3.114664 | 2.596726 | 1.199458 |
selection = kwargs.get('selection', 'Adj Close')
n_sessions = kwargs.get('n_sessions', 1)
skipstartrows = kwargs.get('skipstartrows', 0)
skipendrows = kwargs.get('skipendrows', 0)
outputcol = kwargs.get('outputcol', 'Growth')
size = len(eqdata.index)
growthdata = eqdata.loc[:, selection... | def growth(eqdata, **kwargs) | Generate a DataFrame where the sole column, 'Growth',
is the growth for the equity over the given number of sessions.
For example, if 'XYZ' has 'Adj Close' of `100.0` on 2014-12-15 and
`90.0` 4 *sessions* later on 2014-12-19, then the 'Growth' value
for 2014-12-19 will be `0.9`.
Parameters
... | 2.844257 | 2.068366 | 1.375122 |
if 'outputcol' not in kwargs:
kwargs['outputcol'] = 'LnGrowth'
return np.log(growth(eqdata, **kwargs)) | def ln_growth(eqdata, **kwargs) | Return the natural log of growth.
See also
--------
:func:`growth` | 4.464984 | 6.345815 | 0.703611 |
if 'outputcol' not in kwargs:
kwargs['outputcol'] = 'Return'
result = growth(eqdata, **kwargs)
result.values[:, :] -= 1.
return result | def ret(eqdata, **kwargs) | Generate a DataFrame where the sole column, 'Return',
is the return for the equity over the given number of sessions.
For example, if 'XYZ' has 'Adj Close' of `100.0` on 2014-12-15 and
`90.0` 4 *sessions* later on 2014-12-19, then the 'Return' value
for 2014-12-19 will be `-0.1`.
Parameters
... | 7.634332 | 6.821393 | 1.119175 |
diff = predicted - actual
return np.average(diff * diff, axis=0) | def mse(predicted, actual) | Mean squared error of predictions.
.. versionadded:: 0.5.0
Parameters
----------
predicted : ndarray
Predictions on which to measure error. May
contain a single or multiple column but must
match `actual` in shape.
actual : ndarray
Actual values against which to mea... | 4.223835 | 8.32466 | 0.507388 |
_index = ['Eq Cost', 'Option Premium', 'Commission', 'Total Invested', 'Dividends', 'Eq if Ex',
'Comm if Ex', 'Profit if Ex', 'Ret if Ex', 'Profit if Unch', 'Ret if Unch', 'Break_Even Price',
'Protection Pts', 'Protection Pct']
_metrics = pd.DataFrame(index=_index, columns=['Value'... | def get(eqprice, callprice, strike, shares=1, buycomm=0., excomm=0., dividend=0.) | Metrics for covered calls.
Parameters
----------
eqprice : float
Price at which stock is purchased.
callprice : float
Price for which call is sold.
strike : float
Strike price of call sold.
shares : int, optional
Number of shares of stock. Defaults to 1.
buyc... | 2.540388 | 2.499856 | 1.016214 |
_date = Timestamp(date)
if bday is None:
bday = CustomBusinessDay(calendar=USFederalHolidayCalendar())
return _date == (_date + bday) - bday | def is_bday(date, bday=None) | Return true iff the given date is a business day.
Parameters
----------
date : :class:`pandas.Timestamp`
Any value that can be converted to a pandas Timestamp--e.g.,
'2012-05-01', dt.datetime(2012, 5, 1, 3)
bday : :class:`pandas.tseries.offsets.CustomBusinessDay`
Defaults to `C... | 5.992325 | 4.869594 | 1.23056 |
content = np.empty((eq_dfs[0].shape[0], len(eq_dfs)), dtype=np.float64)
rel_perf = pd.DataFrame(content, eq_dfs[0].index, columns, dtype=np.float64)
for i in range(len(eq_dfs)):
rel_perf.iloc[:, i] = eq_dfs[i].loc[:, selection] / eq_dfs[i].iloc[0].loc[selection]
return rel_perf | def compare(eq_dfs, columns=None, selection='Adj Close') | Get the relative performance of multiple equities.
.. versionadded:: 0.5.0
Parameters
----------
eq_dfs : list or tuple of DataFrame
Performance data for multiple equities over
a consistent time frame.
columns : iterable of str, default None
Labels to use for the columns of... | 2.574425 | 2.507305 | 1.02677 |
assert lowstrike < midstrike
assert midstrike < highstrike
assert pd.Timestamp(expiry1) < pd.Timestamp(expiry2)
_rows1 = {}
_rows2 = {}
_prices1 = {}
_prices2 = {}
_index = ['Straddle Call', 'Straddle Put', 'Straddle Total', 'Far Call', 'Far Put',... | def diagbtrfly(self, lowstrike, midstrike, highstrike, expiry1, expiry2) | Metrics for evaluating a diagonal butterfly spread.
Parameters
------------
opttype : str ('call' or 'put')
Type of option on which to collect data.
lowstrike : numeric
Lower strike price. To be used for far put.
midstrike : numeric
Middle str... | 2.17297 | 2.149993 | 1.010687 |
print("Expirations:")
_i = 0
for _datetime in self.data.index.levels[1].to_pydatetime():
print("{:2d} {}".format(_i, _datetime.strftime('%Y-%m-%d')))
_i += 1
print("Stock: {:.2f}".format(self.data.iloc[0].loc['Underlying_Price']))
print("Quote tim... | def info(self) | Show expiration dates, equity price, quote time.
Returns
-------
self : :class:`~pynance.opt.core.Options`
Returns a reference to the calling object to allow
chaining.
expiries : :class:`pandas.tseries.index.DatetimeIndex`
Examples
--------
... | 5.474126 | 4.28344 | 1.277974 |
return [_todict(key, self.data.loc[key, :]) for key in self.data.index] | def tolist(self) | Return the array as a list of rows.
Each row is a `dict` of values. Facilitates inserting data into a database.
.. versionadded:: 0.3.1
Returns
-------
quotes : list
A list in which each entry is a dictionary representing
a single options quote. | 7.50442 | 10.291618 | 0.729178 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.