text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pip_search(self, search_string=None): """Search for pip packages in PyPI matching `search_string`."""
extra_args = ['search', search_string] return self._call_pip(name='root', extra_args=extra_args, callback=self._pip_search)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pip_search(stdout, stderr): """Callback for pip search."""
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() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _timer_update(self): """Add some moving points to the dependency resolution text."""
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_counter > 150:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create_worker(self, method, *args, **kwargs): """Create a worker for this client to be run in a separate thread."""
# 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._queue.a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _load_repodata(filepaths, extra_data=None, metadata=None): """Load all the available pacakges information. For downloaded repodata files (repo.continuum.io),...
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): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def login(self, username, password, application, application_url): """Login to anaconda cloud."""
logger.debug(str((username, application, application_url))) method = self._anaconda_client_api.authenticate return self._create_worker(method, username, password, application, application_url)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def logout(self): """Logout from anaconda cloud."""
logger.debug('Logout') method = self._anaconda_client_api.remove_authentication return self._create_worker(method)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_repodata(self, filepaths, extra_data=None, metadata=None): """ Load all the available pacakges information for downloaded repodata. Files include repo.c...
logger.debug(str((filepaths))) method = self._load_repodata return self._create_worker(method, filepaths, extra_data=extra_data, metadata=metadata)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare_model_data(self, packages, linked, pip=None, private_packages=None): """Prepare downloaded package info along with pip pacakges info."""
logger.debug('') return self._prepare_model_data(packages, linked, pip=pip, private_packages=private_packages)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_domain(self, domain='https://api.anaconda.org'): """Reset current api domain."""
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.user()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
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 return th...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_cities(self): """Get a dictionary of cities keyed by geonameid."""
if self.cities is None: self.cities = self._load_data(self.cities, 'cities.json') return self.cities
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
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.cities_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _set_repo_urls_from_channels(self, channels): """ Convert a channel into a normalized repo name including. Channels are assumed in normalized url form. """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_repos(self, repos): """Check if repodata urls are valid."""
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _repos_checked(self, worker, output, error): """Callback for _check_repos."""
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _repo_url_to_path(self, repo): """Convert a `repo` url to a file path for local storage."""
repo = repo.replace('http://', '') repo = repo.replace('https://', '') repo = repo.replace('/', '_') return os.sep.join([self._data_directory, repo])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _download_repodata(self, checked_repos): """Dowload repodata."""
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(path) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_repodata_from_meta(self): """Generate repodata from local meta files."""
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: data = js...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _repodata_downloaded(self, worker=None, output=None, error=None): """Callback for _download_repodata."""
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)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def repodata_files(self, channels=None): """ Return the repodata paths based on `channels` and the `data_directory`. There is no check for validity here. """
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.append(fu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_repodata(self, channels=None): """Update repodata from channels or use condarc channels if None."""
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_metadata(self): """ Update the metadata available for packages in repo.continuum.io. Returns a download worker. """
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_url, filep...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_valid_channel(self, channel, conda_url='https://conda.anaconda.org'): """Check if channel is valid."""
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, plat, '...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _aws_get_instance_by_tag(region, name, tag, raw): """Get all instances matching a tag."""
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 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def aws_get_instances_by_id(region, instance_id, raw=True): """Returns instances mathing an id."""
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 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_instances_by_name(name, sort_by_order=('cloud', 'name'), projects=None, raw=True, regions=None, gcp_credentials=None, clouds=SUPPORTED_CLOUDS): """Get in...
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(instance...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_os_version(instance): """Get OS Version for instances."""
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.04' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_volumes(instance): """Returns all the volumes of an instance."""
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'] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_persistent_address(instance): """Returns the public ip address of an instance."""
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') !=...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(): """Use pip to find pip installed packages in a given prefix."""
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _save(file, data, mode='w+'): """ Write all data to created file. Also overwrite previous file. """
with open(file, mode) as fh: fh.write(data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge(obj): """ Merge contents. It does a simply merge of all files defined under 'static' key. function will render them and append to the merged output. To...
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: print 'L...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
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)) print...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 .origin...
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': {'file...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process(obj): """ Process each block of the merger object. """
#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(len(me...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def optimize(exp_rets, covs): """ Return parameters for portfolio optimization. Parameters exp_rets : ndarray Vector of expected returns for each investment.. co...
_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] = _re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def growthfromrange(rangegrowth, startdate, enddate): """ Annual growth given growth from start date to end date. """
_yrs = (pd.Timestamp(enddate) - pd.Timestamp(startdate)).total_seconds() /\ dt.timedelta(365.25).total_seconds() return yrlygrowth(rangegrowth, _yrs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def equities(country='US'): """ Return a DataFrame of current US equities. .. versionadded:: 0.4.0 .. versionchanged:: 0.5.0 Return a DataFrame Parameters countr...
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, in...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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'...
_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]) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(equity): """ Retrieve all current options chains for given equity. .. versionchanged:: 0.5.0 Eliminate special exception handling. Parameters equity : st...
_optmeta = pdr.data.Options(equity, 'yahoo') _optdata = _optmeta.get_all_data() return Options(_optdata)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transform(data_frame, **kwargs): """ Return a transformed DataFrame. Transform data_frame along the given axis. By default, each row will be normalized (axis...
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: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_norms_of_rows(data_frame, method): """ return a column vector containing the norm of each row """
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.iloc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, opttype, strike, expiry): """ Price as midpoint between bid and ask. Parameters opttype : str 'call' or 'put'. strike : numeric Strike price. expir...
_optrow = _relevant_rows(self.data, (strike, expiry, opttype,), "No key for {} strike {} {}".format(expiry, strike, opttype)) return _getprice(_optrow)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def metrics(self, opttype, strike, expiry): """ Basic metrics for a specific option. Parameters opttype : str ('call' or 'put') strike : numeric Strike price. ex...
_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, columns=[...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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'...
_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(index=_inde...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exps(self, opttype, strike): """ Prices for given strike on all available dates. Parameters opttype : str ('call' or 'put') strike : numeric Returns df : :cl...
_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(index=_inde...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def labeledfeatures(eqdata, featurefunc, labelfunc): """ Return features and labels for the given equity data. Each row of the features returned contains `2 * n_...
_size = len(eqdata.index) _labels, _skipatend = labelfunc(eqdata) _features, _skipatstart = featurefunc(eqdata.iloc[:(_size - _skipatend), :]) return _features, _labels.iloc[_skipatstart:, :]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def growth(interval, pricecol, eqdata): """ Retrieve growth labels. Parameters interval : int Number of sessions over which growth is measured. For example, if t...
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sma(eqdata, **kwargs): """ simple moving average Parameters eqdata : DataFrame window : int, optional Lookback period for sma. Defaults to 20. outputcol : st...
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.ind...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ema(eqdata, **kwargs): """ Exponential moving average with the given span. Parameters eqdata : DataFrame Must have exactly 1 column on which to calculate EMA...
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, col...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ema_growth(eqdata, **kwargs): """ Growth of exponential moving average. Parameters eqdata : DataFrame span : int, optional Span for exponential moving averag...
_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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def growth_volatility(eqdata, **kwargs): """ Return the volatility of growth. Note that, like :func:`pynance.tech.simple.growth` but in contrast to :func:`volati...
_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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ratio_to_ave(window, eqdata, **kwargs): """ Return values expressed as ratios to the average over some number of prior sessions. Parameters eqdata : DataFram...
_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 - _skipendro...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(features, labels, regularization=0., constfeat=True): """ Run linear regression on the given data. .. versionadded:: 0.5.0 If a regularization parameter ...
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.dot...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 c...
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 {} {}".format(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ndar...
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) r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
if isinstance(eqdata, pd.DataFrame): _values = eqdata.values else: _values = eqdata return len(_values[pd.isnull(_values)]) > 0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_const(features): """ Prepend the constant feature 1 as first feature and return the modified feature set. Parameters features : ndarray or DataFrame """
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 pd....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fromcols(selection, n_sessions, eqdata, **kwargs): """ Generate features from selected columns of a dataframe. Parameters selection : list or tuple of str Co...
_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:], columns=_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fromfuncs(funcs, n_sessions, eqdata, **kwargs): """ Generate features using a list of functions to apply to input data Parameters funcs : list of function Fu...
_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=' ' + ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ln_growth(eqdata, **kwargs): """ Return the natural log of growth. See also -------- :func:`growth` """
if 'outputcol' not in kwargs: kwargs['outputcol'] = 'LnGrowth' return np.log(growth(eqdata, **kwargs))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mse(predicted, actual): """ Mean squared error of predictions. .. versionadded:: 0.5.0 Parameters predicted : ndarray Predictions on which to measure error. ...
diff = predicted - actual return np.average(diff * diff, axis=0)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(eqprice, callprice, strike, shares=1, buycomm=0., excomm=0., dividend=0.): """ Metrics for covered calls. Parameters eqprice : float Price at which stock...
_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']) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 t...
_date = Timestamp(date) if bday is None: bday = CustomBusinessDay(calendar=USFederalHolidayCalendar()) return _date == (_date + bday) - bday
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compare(eq_dfs, columns=None, selection='Adj Close'): """ Get the relative performance of multiple equities. .. versionadded:: 0.5.0 Parameters eq_dfs : list...
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def diagbtrfly(self, lowstrike, midstrike, highstrike, expiry1, expiry2): """ Metrics for evaluating a diagonal butterfly spread. Parameters opttype : str ('call...
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', 'Far To...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def info(self): """ Show expiration dates, equity price, quote time. Returns ------- self : :class:`~pynance.opt.core.Options` Returns a reference to the calling...
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 time: {}".f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 Ret...
return [_todict(key, self.data.loc[key, :]) for key in self.data.index]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _generate_username(self): """ Generate a unique username """
while True: # Generate a UUID username, removing dashes and the last 2 chars # to make it fit into the 30 char User.username field. Gracefully # handle any unlikely, but possible duplicate usernames. username = str(uuid.uuid4()) username = username.re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_model_cache(table_name): """ Updates model cache by generating a new key for the model """
model_cache_info = ModelCacheInfo(table_name, uuid.uuid4().hex) model_cache_backend.share_model_cache_info(model_cache_info)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def invalidate_model_cache(sender, instance, **kwargs): """ Signal receiver for models to invalidate model cache of sender and related models. Model cache is inv...
logger.debug('Received post_save/post_delete signal from sender {0}'.format(sender)) if django.VERSION >= (1, 8): related_tables = set( [f.related_model._meta.db_table for f in sender._meta.get_fields() if f.related_model is not None and (((f.one_to_many or f.one_t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def invalidate_m2m_cache(sender, instance, model, **kwargs): """ Signal receiver for models to invalidate model cache for many-to-many relationship. Parameters ~...
logger.debug('Received m2m_changed signals from sender {0}'.format(sender)) update_model_cache(instance._meta.db_table) update_model_cache(model._meta.db_table)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_key(self): """ Generate cache key for the current query. If a new key is created for the model it is then shared with other consumers. """
sql = self.sql() key, created = self.get_or_create_model_key() if created: db_table = self.model._meta.db_table logger.debug('created new key {0} for model {1}'.format(key, db_table)) model_cache_info = ModelCacheInfo(db_table, key) model_cache_ba...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sql(self): """ Get sql for the current query. """
clone = self.query.clone() sql, params = clone.get_compiler(using=self.db).as_sql() return sql % params
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_or_create_model_key(self): """ Get or create key for the model. Returns ~~~~~~~ (model_key, boolean) tuple """
model_cache_info = model_cache_backend.retrieve_model_cache_info(self.model._meta.db_table) if not model_cache_info: return uuid.uuid4().hex, True return model_cache_info.table_key, False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def invalidate_model_cache(self): """ Invalidate model cache by generating new key for the model. """
logger.info('Invalidating cache for table {0}'.format(self.model._meta.db_table)) if django.VERSION >= (1, 8): related_tables = set( [f.related_model._meta.db_table for f in self.model._meta.get_fields() if ((f.one_to_many or f.one_to_one) and f.auto_created...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cache_backend(self): """ Get the cache backend Returns ~~~~~~~ Django cache backend """
if not hasattr(self, '_cache_backend'): if hasattr(django.core.cache, 'caches'): self._cache_backend = django.core.cache.caches[_cache_name] else: self._cache_backend = django.core.cache.get_cache(_cache_name) return self._cache_backend
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_file(filename): """ Import a file that will trigger the population of Orca. Parameters filename : str """
pathname, filename = os.path.split(filename) modname = re.match( r'(?P<modname>\w+)\.py', filename).group('modname') file, path, desc = imp.find_module(modname, [pathname]) try: imp.load_module(modname, file, path, desc) finally: file.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_is_table(func): """ Decorator that will check whether the "table_name" keyword argument to the wrapped function matches a registered Orca table. """
@wraps(func) def wrapper(**kwargs): if not orca.is_table(kwargs['table_name']): abort(404) return func(**kwargs) return wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_is_column(func): """ Decorator that will check whether the "table_name" and "col_name" keyword arguments to the wrapped function match a registered Orc...
@wraps(func) def wrapper(**kwargs): table_name = kwargs['table_name'] col_name = kwargs['col_name'] if not orca.is_table(table_name): abort(404) if col_name not in orca.get_table(table_name).columns: abort(404) return func(**kwargs) return wr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_is_injectable(func): """ Decorator that will check whether the "inj_name" keyword argument to the wrapped function matches a registered Orca injectable...
@wraps(func) def wrapper(**kwargs): name = kwargs['inj_name'] if not orca.is_injectable(name): abort(404) return func(**kwargs) return wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def schema(): """ All tables, columns, steps, injectables and broadcasts registered with Orca. Includes local columns on tables. """
tables = orca.list_tables() cols = {t: orca.get_table(t).columns for t in tables} steps = orca.list_steps() injectables = orca.list_injectables() broadcasts = orca.list_broadcasts() return jsonify( tables=tables, columns=cols, steps=steps, injectables=injectables, broadcasts=br...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def table_preview(table_name): """ Returns the first five rows of a table as JSON. Inlcudes all columns. Uses Pandas' "split" JSON format. """
preview = orca.get_table(table_name).to_frame().head() return ( preview.to_json(orient='split', date_format='iso'), 200, {'Content-Type': 'application/json'})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def table_describe(table_name): """ Return summary statistics of a table as JSON. Includes all columns. Uses Pandas' "split" JSON format. """
desc = orca.get_table(table_name).to_frame().describe() return ( desc.to_json(orient='split', date_format='iso'), 200, {'Content-Type': 'application/json'})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def table_definition(table_name): """ Get the source of a table function. If a table is registered DataFrame and not a function then all that is returned is {'ty...
if orca.table_type(table_name) == 'dataframe': return jsonify(type='dataframe') filename, lineno, source = \ orca.get_raw_table(table_name).func_source_data() html = highlight(source, PythonLexer(), HtmlFormatter()) return jsonify( type='function', filename=filename, lineno=l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def table_groupbyagg(table_name): """ Perform a groupby on a table and return an aggregation on a single column. This depends on some request parameters in the U...
table = orca.get_table(table_name) # column to aggregate column = request.args.get('column', None) if not column or column not in table.columns: abort(400) # column or index level to group by by = request.args.get('by', None) level = request.args.get('level', None) if (not by ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def column_preview(table_name, col_name): """ Return the first ten elements of a column as JSON in Pandas' "split" format. """
col = orca.get_table(table_name).get_column(col_name).head(10) return ( col.to_json(orient='split', date_format='iso'), 200, {'Content-Type': 'application/json'})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def column_definition(table_name, col_name): """ Get the source of a column function. If a column is a registered Series and not a function then all that is retu...
col_type = orca.get_table(table_name).column_type(col_name) if col_type != 'function': return jsonify(type=col_type) filename, lineno, source = \ orca.get_raw_column(table_name, col_name).func_source_data() html = highlight(source, PythonLexer(), HtmlFormatter()) return jsonify(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def column_describe(table_name, col_name): """ Return summary statistics of a column as JSON. Uses Pandas' "split" JSON format. """
col_desc = orca.get_table(table_name).get_column(col_name).describe() return ( col_desc.to_json(orient='split'), 200, {'Content-Type': 'application/json'})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def column_csv(table_name, col_name): """ Return a column as CSV using Pandas' default CSV output. """
csv = orca.get_table(table_name).get_column(col_name).to_csv(path=None) return csv, 200, {'Content-Type': 'text/csv'}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def injectable_repr(inj_name): """ Returns the type and repr of an injectable. JSON response has "type" and "repr" keys. """
i = orca.get_injectable(inj_name) return jsonify(type=str(type(i)), repr=repr(i))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def injectable_definition(inj_name): """ Get the source of an injectable function. If an injectable is a registered Python variable and not a function then all t...
inj_type = orca.injectable_type(inj_name) if inj_type == 'variable': return jsonify(type='variable') else: filename, lineno, source = \ orca.get_injectable_func_source_data(inj_name) html = highlight(source, PythonLexer(), HtmlFormatter()) return jsonify( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_broadcasts(): """ List all registered broadcasts as a list of objects with keys "cast" and "onto". """
casts = [{'cast': b[0], 'onto': b[1]} for b in orca.list_broadcasts()] return jsonify(broadcasts=casts)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def broadcast_definition(cast_name, onto_name): """ Return the definition of a broadcast as an object with keys "cast", "onto", "cast_on", "onto_on", "cast_index...
if not orca.is_broadcast(cast_name, onto_name): abort(404) b = orca.get_broadcast(cast_name, onto_name) return jsonify( cast=b.cast, onto=b.onto, cast_on=b.cast_on, onto_on=b.onto_on, cast_index=b.cast_index, onto_index=b.onto_index)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def step_definition(step_name): """ Get the source of a step function. Returned object has keys "filename", "lineno", "text" and "html". "text" is the raw text o...
if not orca.is_step(step_name): abort(404) filename, lineno, source = \ orca.get_step(step_name).func_source_data() html = highlight(source, PythonLexer(), HtmlFormatter()) return jsonify(filename=filename, lineno=lineno, text=source, html=html)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _add_log_handler( handler, level=None, fmt=None, datefmt=None, propagate=None): """ Add a logging handler to Orca. Parameters handler : logging.Handler subcl...
if not fmt: fmt = US_LOG_FMT if not datefmt: datefmt = US_LOG_DATE_FMT handler.setFormatter(logging.Formatter(fmt=fmt, datefmt=datefmt)) if level is not None: handler.setLevel(level) logger = logging.getLogger('orca') logger.addHandler(handler) if propagate is no...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log_to_stream(level=None, fmt=None, datefmt=None): """ Send log messages to the console. Parameters level : int, optional An optional logging level that will...
_add_log_handler( logging.StreamHandler(), fmt=fmt, datefmt=datefmt, propagate=False)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear_all(): """ Clear any and all stored state from Orca. """
_TABLES.clear() _COLUMNS.clear() _STEPS.clear() _BROADCASTS.clear() _INJECTABLES.clear() _TABLE_CACHE.clear() _COLUMN_CACHE.clear() _INJECTABLE_CACHE.clear() for m in _MEMOIZED.values(): m.value.clear_cached() _MEMOIZED.clear() logger.debug('pipeline state cleared')