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 ffill_across_cols(df, columns, name_map): """ Forward fill values in a DataFrame with special logic to handle cases that pd.DataFrame.ffill cannot and cast c...
df.ffill(inplace=True) # Fill in missing values specified by each column. This is made # significantly more complex by the fact that we need to work around # two pandas issues: # 1) When we have sids, if there are no records for a given sid for any # dates, pandas will generate a column 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 shift_dates(dates, start_date, end_date, shift): """ Shift dates of a pipeline query back by `shift` days. load_adjusted_array is called with dates on which ...
try: start = dates.get_loc(start_date) except KeyError: if start_date < dates[0]: raise NoFurtherDataError( msg=( "Pipeline Query requested data starting on {query_start}, " "but first known date is {calendar_start}" ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format_docstring(owner_name, docstring, formatters): """ Template ``formatters`` into ``docstring``. Parameters owner_name : str The name of the function or ...
# Build a dict of parameters to a vanilla format() call by searching for # each entry in **formatters and applying any leading whitespace to each # line in the desired substitution. format_params = {} for target, doc_for_target in iteritems(formatters): # Search for '{name}', with optional ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def templated_docstring(**docs): """ Decorator allowing the use of templated docstrings. Examples -------- 'bar' """
def decorator(f): f.__doc__ = format_docstring(f.__name__, f.__doc__, docs) return f return decorator
<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(self, term, name, overwrite=False): """ Add a column. The results of computing `term` will show up as a column in the DataFrame produced by running this ...
self.validate_column(name, term) columns = self.columns if name in columns: if overwrite: self.remove(name) else: raise KeyError("Column '{}' already exists.".format(name)) if not isinstance(term, ComputableTerm): rai...
<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_screen(self, screen, overwrite=False): """ Set a screen on this Pipeline. Parameters filter : zipline.pipeline.Filter The filter to apply as a screen. ov...
if self._screen is not None and not overwrite: raise ValueError( "set_screen() called with overwrite=False and screen already " "set.\n" "If you want to apply multiple filters as a screen use " "set_screen(filter1 & filter2 & ...).\n" ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_execution_plan(self, domain, default_screen, start_date, end_date): """ Compile into an ExecutionPlan. Parameters domain : zipline.pipeline.domain.Domain ...
if self._domain is not GENERIC and self._domain is not domain: raise AssertionError( "Attempted to compile Pipeline with domain {} to execution " "plan with different domain {}.".format(self._domain, domain) ) return ExecutionPlan( do...
<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_graph_terms(self, default_screen): """Helper for to_graph and to_execution_plan."""
columns = self.columns.copy() screen = self.screen if screen is None: screen = default_screen columns[SCREEN_NAME] = screen return 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 show_graph(self, format='svg'): """ Render this Pipeline as a DAG. Parameters format : {'svg', 'png', 'jpeg'} Image format to render with. Default is 'svg'. ...
g = self.to_simple_graph(AssetExists()) if format == 'svg': return g.svg elif format == 'png': return g.png elif format == 'jpeg': return g.jpeg else: # We should never get here because of the expect_element decorator #...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _output_terms(self): """ A list of terms that are outputs of this pipeline. Includes all terms registered as data outputs of the pipeline, plus the screen, i...
terms = list(six.itervalues(self._columns)) screen = self.screen if screen is not None: terms.append(screen) return terms
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def domain(self, default): """ Get the domain for this pipeline. - If an explicit domain was provided at construction time, use it. - Otherwise, infer a domain f...
# Always compute our inferred domain to ensure that it's compatible # with our explicit domain. inferred = infer_domain(self._output_terms) if inferred is GENERIC and self._domain is GENERIC: # Both generic. Fall back to default. return default elif infe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ensure_element(tup, elem): """ Create a tuple containing all elements of tup, plus elem. Returns the new tuple and the index of elem in the new tuple. """
try: return tup, tup.index(elem) except ValueError: return tuple(chain(tup, (elem,))), len(tup)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _compute(self, arrays, dates, assets, mask): """ Compute our stored expression string with numexpr. """
out = full(mask.shape, self.missing_value, dtype=self.dtype) # This writes directly into our output buffer. numexpr.evaluate( self._expr, local_dict={ "x_%d" % idx: array for idx, array in enumerate(arrays) }, globa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _rebind_variables(self, new_inputs): """ Return self._expr with all variables rebound to the indices implied by new_inputs. """
expr = self._expr # If we have 11+ variables, some of our variable names may be # substrings of other variable names. For example, we might have x_1, # x_10, and x_100. By enumerating in reverse order, we ensure that # every variable name which is a substring of another variabl...
<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_expressions(self, other): """ Merge the inputs of two NumericalExpressions into a single input tuple, rewriting their respective string expressions to...
new_inputs = tuple(set(self.inputs).union(other.inputs)) new_self_expr = self._rebind_variables(new_inputs) new_other_expr = other._rebind_variables(new_inputs) return new_self_expr, new_other_expr, new_inputs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_binary_op(self, op, other): """ Compute new expression strings and a new inputs tuple for combining self and other with a binary operator. """
if isinstance(other, NumericalExpression): self_expr, other_expr, new_inputs = self._merge_expressions(other) elif isinstance(other, Term): self_expr = self._expr new_inputs, other_idx = _ensure_element(self.inputs, other) other_expr = "x_%d" % other_idx ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def graph_repr(self): """Short repr to use when rendering Pipeline graphs."""
# Replace any floating point numbers in the expression # with their scientific notation final = re.sub(r"[-+]?\d*\.\d+", lambda x: format(float(x.group(0)), '.2E'), self._expr) # Graphviz interprets `\l` as "divide label into lines, left-ju...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def last_modified_time(path): """ Get the last modified time of path as a Timestamp. """
return pd.Timestamp(os.path.getmtime(path), unit='s', tz='UTC')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def zipline_root(environ=None): """ Get the root directory for all zipline-managed files. For testing purposes, this accepts a dictionary to interpret as the os ...
if environ is None: environ = os.environ root = environ.get('ZIPLINE_ROOT', None) if root is None: root = expanduser('~/.zipline') return root
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format_adjustments(self, dates, assets): """ Build a dict of Adjustment objects in the format expected by AdjustedArray. Returns a dict of the form: { # Inte...
make_adjustment = partial(make_adjustment_from_labels, dates, assets) min_date, max_date = dates[[0, -1]] # TODO: Consider porting this to Cython. if len(self.adjustments) == 0: return {} # Mask for adjustments whose apply_dates are in the requested window of ...
<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_adjusted_array(self, domain, columns, dates, sids, mask): """ Load data from our stored baseline. """
if len(columns) != 1: raise ValueError( "Can't load multiple columns with DataFrameLoader" ) column = columns[0] self._validate_input_column(column) date_indexer = self.dates.get_indexer(dates) assets_indexer = self.assets.get_indexer(si...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _validate_input_column(self, column): """Make sure a passed column is our column. """
if column != self.column and column.unspecialize() != self.column: raise ValueError("Can't load unknown column %s" % column)
<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_from_directory(list_name): """ To resolve the symbol in the LEVERAGED_ETF list, the date on which the symbol was in effect is needed. Furthermore, to ma...
data = {} dir_path = os.path.join(SECURITY_LISTS_DIR, list_name) for kd_name in listdir(dir_path): kd = datetime.strptime(kd_name, DATE_FORMAT).replace( tzinfo=pytz.utc) data[kd] = {} kd_path = os.path.join(dir_path, kd_name) for ld_name in listdir(kd_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 weak_lru_cache(maxsize=100): """Weak least-recently-used cache decorator. If *maxsize* is set to None, the LRU features are disabled and the cache can grow w...
class desc(lazyval): def __get__(self, instance, owner): if instance is None: return self try: return self._cache[instance] except KeyError: inst = ref(instance) @_weak_lru_cache(maxsize) @w...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bind(self, name): """ Bind a `Column` object to its name. """
return _BoundColumnDescr( dtype=self.dtype, missing_value=self.missing_value, name=name, doc=self.doc, metadata=self.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 specialize(self, domain): """Specialize ``self`` to a concrete domain. """
if domain == self.domain: return self return type(self)( dtype=self.dtype, missing_value=self.missing_value, dataset=self._dataset.specialize(domain), name=self._name, doc=self.__doc__, metadata=self._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 get_column(cls, name): """Look up a column by name. Parameters name : str Name of the column to look up. Returns ------- column : zipline.pipeline.data.Bound...
clsdict = vars(cls) try: maybe_column = clsdict[name] if not isinstance(maybe_column, _BoundColumnDescr): raise KeyError(name) except KeyError: raise AttributeError( "{dset} has no column {colname!r}:\n\n" "Poss...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _make_dataset(cls, coords): """Construct a new dataset given the coordinates. """
class Slice(cls._SliceType): extra_coords = coords Slice.__name__ = '%s.slice(%s)' % ( cls.__name__, ', '.join('%s=%r' % item for item in coords.items()), ) return Slice
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def slice(cls, *args, **kwargs): """Take a slice of a DataSetFamily to produce a dataset indexed by asset and date. Parameters *args **kwargs The coordinates to ...
coords, hash_key = cls._canonical_key(args, kwargs) try: return cls._slice_cache[hash_key] except KeyError: pass Slice = cls._make_dataset(coords) cls._slice_cache[hash_key] = Slice return Slice
<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_adjusted_array(self, domain, columns, dates, sids, mask): """ Load by delegating to sub-loaders. """
out = {} for col in columns: try: loader = self._loaders.get(col) if loader is None: loader = self._loaders[col.unspecialize()] except KeyError: raise ValueError("Couldn't find loader for %s" % 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 _float_values(self, shape): """ Return uniformly-distributed floats between -0.0 and 100.0. """
return self.state.uniform(low=0.0, high=100.0, size=shape)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _int_values(self, shape): """ Return uniformly-distributed integers between 0 and 100. """
return (self.state.randint(low=0, high=100, size=shape) .astype('int64'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _datetime_values(self, shape): """ Return uniformly-distributed dates in 2014. """
start = Timestamp('2014', tz='UTC').asm8 offsets = self.state.randint( low=0, high=364, size=shape, ).astype('timedelta64[D]') return start + offsets
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def quantiles(data, nbins_or_partition_bounds): """ Compute rowwise array quantiles on an input. """
return apply_along_axis( qcut, 1, data, q=nbins_or_partition_bounds, labels=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 handle_minute_close(self, dt, data_portal): """ Handles the close of the given minute in minute emission. Parameters dt : Timestamp The minute that is ending...
self.sync_last_sale_prices(dt, data_portal) packet = { 'period_start': self._first_session, 'period_end': self._last_session, 'capital_base': self._capital_base, 'minute_perf': { 'period_open': self._market_open, 'period_c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_market_open(self, session_label, data_portal): """Handles the start of each session. Parameters session_label : Timestamp The label of the session tha...
ledger = self._ledger ledger.start_of_session(session_label) adjustment_reader = data_portal.adjustment_reader if adjustment_reader is not None: # this is None when running with a dataframe source ledger.process_dividends( session_label, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_market_close(self, dt, data_portal): """Handles the close of the given day. Parameters dt : Timestamp The most recently completed simulation datetime....
completed_session = self._current_session if self.emission_rate == 'daily': # this method is called for both minutely and daily emissions, but # this chunk of code here only applies for daily emissions. (since # it's done every minute, elsewhere, for minutely emissi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_simulation_end(self, data_portal): """ When the simulation is complete, run the full period risk report and send it out on the results socket. """
log.info( 'Simulated {} trading days\n' 'first open: {}\n' 'last close: {}', self._session_count, self._trading_calendar.session_open(self._first_session), self._trading_calendar.session_close(self._last_session), ) packet...
<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_args(args, root): """ Encapsulates a set of custom command line arguments in key=value or key.namespace=value form into a chain of Namespace objects, ...
extension_args = {} for arg in args: parse_extension_arg(arg, extension_args) for name in sorted(extension_args, key=len): path = name.split('.') update_namespace(root, path, extension_args[name])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_extension_arg(arg, arg_dict): """ Converts argument strings in key=value or key.namespace=value form to dictionary entries Parameters arg : str The arg...
match = re.match(r'^(([^\d\W]\w*)(\.[^\d\W]\w*)*)=(.*)$', arg) if match is None: raise ValueError( "invalid extension argument '%s', must be in key=value form" % arg ) name = match.group(1) value = match.group(4) arg_dict[name] = 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 update_namespace(namespace, path, name): """ A recursive function that takes a root element, list of namespaces, and the value being stored, and assigns name...
if len(path) == 1: setattr(namespace, path[0], name) else: if hasattr(namespace, path[0]): if isinstance(getattr(namespace, path[0]), six.string_types): raise ValueError("Conflicting assignments at namespace" " level '%s'" % path[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 create_registry(interface): """ Create a new registry for an extensible interface. Parameters interface : type The abstract data type for which to create a r...
if interface in custom_types: raise ValueError('there is already a Registry instance ' 'for the specified type') custom_types[interface] = Registry(interface) return interface
<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(self, name): """Construct an object from a registered factory. Parameters name : str Name with which the factory was registered. """
try: return self._factories[name]() except KeyError: raise ValueError( "no %s factory registered under name %r, options are: %r" % (self.interface.__name__, name, sorted(self._factories)), )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calculate(self, order, transaction): """ Pay commission based on dollar value of shares. """
cost_per_share = transaction.price * self.cost_per_dollar return abs(transaction.amount) * cost_per_share
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def risk_metric_period(cls, start_session, end_session, algorithm_returns, benchmark_returns, algorithm_leverages): """ Creates a dictionary representing the sta...
algorithm_returns = algorithm_returns[ (algorithm_returns.index >= start_session) & (algorithm_returns.index <= end_session) ] # Benchmark needs to be masked to the same dates as the algo returns benchmark_returns = benchmark_returns[ (benchmark_ret...
<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_active_contract_at_offset(self, root_symbol, dt, offset): """ For the given root symbol, find the contract that is considered active on a specific date ...
oc = self.asset_finder.get_ordered_contracts(root_symbol) session = self.trading_calendar.minute_to_session_label(dt) front = oc.contract_before_auto_close(session.value) back = oc.contract_at_offset(front, 1, dt.value) if back is None: return front primary =...
<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_rolls(self, root_symbol, start, end, offset): """ Get the rolls, i.e. the session at which to hop from contract to contract in the chain. Parameters root...
oc = self.asset_finder.get_ordered_contracts(root_symbol) front = self._get_active_contract_at_offset(root_symbol, end, 0) back = oc.contract_at_offset(front, 1, end.value) if back is not None: end_session = self.trading_calendar.minute_to_session_label(end) firs...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _active_contract(self, oc, front, back, dt): r""" Return the active contract based on the previous trading day's volume. In the rare case that a double volum...
front_contract = oc.sid_to_contract[front].contract back_contract = oc.sid_to_contract[back].contract tc = self.trading_calendar trading_day = tc.day prev = dt - trading_day get_value = self.session_reader.get_value # If the front contract is past its auto clos...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _normalize_array(data, missing_value): """ Coerce buffer data for an AdjustedArray into a standard scalar representation, returning the coerced array and a d...
if isinstance(data, LabelArray): return data, {} data_dtype = data.dtype if data_dtype in BOOL_DTYPES: return data.astype(uint8), {'dtype': dtype(bool_)} elif data_dtype in FLOAT_DTYPES: return data.astype(float64), {'dtype': dtype(float64)} elif data_dtype in INT_DTYPES: ...
<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_simple(adjustment_lists, front_idx, back_idx): """ Merge lists of new and existing adjustments for a given index by appending or prepending new adjust...
if len(adjustment_lists) == 1: return list(adjustment_lists[0]) else: return adjustment_lists[front_idx] + adjustment_lists[back_idx]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ensure_ndarray(ndarray_or_adjusted_array): """ Return the input as a numpy ndarray. This is a no-op if the input is already an ndarray. If the input is an ad...
if isinstance(ndarray_or_adjusted_array, ndarray): return ndarray_or_adjusted_array elif isinstance(ndarray_or_adjusted_array, AdjustedArray): return ndarray_or_adjusted_array.data else: raise TypeError( "Can't convert %s to ndarray" % type(ndarray_or_adjuste...
<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_window_params(data, window_length): """ Check that a window of length `window_length` is well-defined on `data`. Parameters data : np.ndarray[ndim=2] ...
if window_length < 1: raise WindowLengthNotPositive(window_length=window_length) if window_length > data.shape[0]: raise WindowLengthTooLong( nrows=data.shape[0], window_length=window_length, )
<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_adjustments(self, adjustments, method): """ Merge ``adjustments`` with existing adjustments, handling index collisions according to ``method``. Parame...
try: merge_func = _merge_methods[method] except KeyError: raise ValueError( "Invalid merge method %s\n" "Valid methods are: %s" % (method, ', '.join(_merge_methods)) ) self.adjustments = merge_with( merge_func, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _iterator_type(self): """ The iterator produced when `traverse` is called on this Array. """
if isinstance(self._data, LabelArray): return LabelWindow return CONCRETE_WINDOW_TYPES[self._data.dtype]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def traverse(self, window_length, offset=0, perspective_offset=0): """ Produce an iterator rolling windows rows over our data. Each emitted window will have `win...
data = self._data.copy() _check_window_params(data, window_length) return self._iterator_type( data, self._view_kwargs, self.adjustments, offset, window_length, perspective_offset, rounding_places=None, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inspect(self): """ Return a string representation of the data stored in this array. """
return dedent( """\ Adjusted Array ({dtype}): Data: {data!r} Adjustments: {adjustments} """ ).format( dtype=self.dtype.name, data=self.data, adjustments=self.adjustments, )
<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_labels(self, func): """ Map a function over baseline and adjustment values in place. Note that the baseline data values must be a LabelArray. """
if not isinstance(self.data, LabelArray): raise TypeError( 'update_labels only supported if data is of type LabelArray.' ) # Map the baseline values. self._data = self._data.map(func) # Map each of the adjustments. for _, row_adjustments...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_violation(self, asset, amount, datetime, metadata=None): """ Handle a TradingControlViolation, either by raising or logging and error with information...
constraint = self._constraint_msg(metadata) if self.on_error == 'fail': raise TradingControlViolation( asset=asset, amount=amount, datetime=datetime, constraint=constraint) elif self.on_error == 'log': log....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate(self, asset, amount, portfolio, algo_datetime, algo_current_data): """ Fail if we've already placed self.max_count orders today. """
algo_date = algo_datetime.date() # Reset order count if it's a new day. if self.current_date and self.current_date != algo_date: self.orders_placed = 0 self.current_date = algo_date if self.orders_placed >= self.max_count: self.handle_violation(asset, 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 validate(self, asset, amount, portfolio, algo_datetime, algo_current_data): """ Fail if the asset is in the restricted_list. """
if self.restrictions.is_restricted(asset, algo_datetime): self.handle_violation(asset, amount, algo_datetime)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate(self, asset, amount, portfolio, algo_datetime, algo_current_data): """ Fail if the magnitude of the given order exceeds either self.max_shares or se...
if self.asset is not None and self.asset != asset: return if self.max_shares is not None and abs(amount) > self.max_shares: self.handle_violation(asset, amount, algo_datetime) current_asset_price = algo_current_data.current(asset, "price") order_value = amount...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate(self, asset, amount, portfolio, algo_datetime, algo_current_data): """ Fail if the given order would cause the magnitude of our position to be great...
if self.asset is not None and self.asset != asset: return current_share_count = portfolio.positions[asset].amount shares_post_order = current_share_count + amount too_many_shares = (self.max_shares is not None and abs(shares_post_order) > self.m...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate(self, asset, amount, portfolio, algo_datetime, algo_current_data): """ Fail if we would hold negative shares of asset after completing this order. "...
if portfolio.positions[asset].amount + amount < 0: self.handle_violation(asset, amount, algo_datetime)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate(self, asset, amount, portfolio, algo_datetime, algo_current_data): """ Fail if the algo has passed this Asset's end_date, or before the Asset's star...
# If the order is for 0 shares, then silently pass through. if amount == 0: return normalized_algo_dt = pd.Timestamp(algo_datetime).normalize() # Fail if the algo is before this Asset's start_date if asset.start_date: normalized_start = pd.Timestamp(ass...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate(self, _portfolio, _account, _algo_datetime, _algo_current_data): """ Fail if the leverage is greater than the allowed leverage. """
if _account.leverage > self.max_leverage: self.fail()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate(self, _portfolio, account, algo_datetime, _algo_current_data): """ Make validation checks if we are after the deadline. Fail if the leverage is less...
if (algo_datetime > self.deadline and account.leverage < self.min_leverage): self.fail()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def alter_columns(op, name, *columns, **kwargs): """Alter columns from a table. Parameters name : str The name of the table. *columns The new columns to have. se...
selection_string = kwargs.pop('selection_string', None) if kwargs: raise TypeError( 'alter_columns received extra arguments: %r' % sorted(kwargs), ) if selection_string is None: selection_string = ', '.join(column.name for column in columns) tmp_name = '_alter_colum...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def downgrade(engine, desired_version): """Downgrades the assets db at the given engine to the desired version. Parameters engine : Engine An SQLAlchemy engine t...
# Check the version of the db at the engine with engine.begin() as conn: metadata = sa.MetaData(conn) metadata.reflect() version_info_table = metadata.tables['version_info'] starting_version = sa.select((version_info_table.c.version,)).scalar() # Check for accidental u...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def downgrades(src): """Decorator for marking that a method is a downgrade to a version to the previous version. Parameters src : int The version this downgrades...
def _(f): destination = src - 1 @do(operator.setitem(_downgrade_methods, destination)) @wraps(f) def wrapper(op, conn, version_info_table): conn.execute(version_info_table.delete()) # clear the version f(op) write_version_info(conn, version_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 _downgrade_v1(op): """ Downgrade assets db by removing the 'tick_size' column and renaming the 'multiplier' column. """
# Drop indices before batch # This is to prevent index collision when creating the temp table op.drop_index('ix_futures_contracts_root_symbol') op.drop_index('ix_futures_contracts_symbol') # Execute batch op to allow column modification in SQLite with op.batch_alter_table('futures_contracts') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _downgrade_v2(op): """ Downgrade assets db by removing the 'auto_close_date' column. """
# Drop indices before batch # This is to prevent index collision when creating the temp table op.drop_index('ix_equities_fuzzy_symbol') op.drop_index('ix_equities_company_symbol') # Execute batch op to allow column modification in SQLite with op.batch_alter_table('equities') as batch_op: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _downgrade_v3(op): """ Downgrade assets db by adding a not null constraint on ``equities.first_traded`` """
op.create_table( '_new_equities', sa.Column( 'sid', sa.Integer, unique=True, nullable=False, primary_key=True, ), sa.Column('symbol', sa.Text), sa.Column('company_symbol', sa.Text), sa.Column('share_class_sy...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _downgrade_v4(op): """ Downgrades assets db by copying the `exchange_full` column to `exchange`, then dropping the `exchange_full` column. """
op.drop_index('ix_equities_fuzzy_symbol') op.drop_index('ix_equities_company_symbol') op.execute("UPDATE equities SET exchange = exchange_full") with op.batch_alter_table('equities') as batch_op: batch_op.drop_column('exchange_full') op.create_index('ix_equities_fuzzy_symbol', ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _make_metrics_set_core(): """Create a family of metrics sets functions that read from the same metrics set mapping. Returns ------- metrics_sets : mappingpro...
_metrics_sets = {} # Expose _metrics_sets through a proxy so that users cannot mutate this # accidentally. Users may go through `register` to update this which will # warn when trampling another metrics set. metrics_sets = mappingproxy(_metrics_sets) def register(name, function=None): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_column_specs(events, columns): """ Verify that the columns of ``events`` can be used by a EarningsEstimatesLoader to serve the BoundColumns describe...
required = required_estimates_fields(columns) received = set(events.columns) missing = required - received if missing: raise ValueError( "EarningsEstimatesLoader missing required columns {missing}.\n" "Got Columns: {received}\n" "Expected Columns: {required}"...
<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_requested_quarter_data(self, zero_qtr_data, zeroth_quarter_idx, stacked_last_per_qtr, num_announcements, dates): """ Selects the requested data for each ...
zero_qtr_data_idx = zero_qtr_data.index requested_qtr_idx = pd.MultiIndex.from_arrays( [ zero_qtr_data_idx.get_level_values(0), zero_qtr_data_idx.get_level_values(1), self.get_shifted_qtrs( zeroth_quarter_idx.get_level_valu...
<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_split_adjusted_asof_idx(self, dates): """ Compute the index in `dates` where the split-adjusted-asof-date falls. This is the date up to which, and includ...
split_adjusted_asof_idx = dates.searchsorted( self._split_adjusted_asof ) # The split-asof date is after the date index. if split_adjusted_asof_idx == len(dates): split_adjusted_asof_idx = len(dates) - 1 elif self._split_adjusted_asof < dates[0].tz_locali...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def collect_overwrites_for_sid(self, group, dates, requested_qtr_data, last_per_qtr, sid_idx, columns, all_adjustments_for_sid, sid): """ Given a sid, collect al...
# If data was requested for only 1 date, there can never be any # overwrites, so skip the extra work. if len(dates) == 1: return next_qtr_start_indices = dates.searchsorted( group[EVENT_DATE_FIELD_NAME].values, side=self.searchsorted_side, ) ...
<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_into_adjustments_for_all_sids(self, all_adjustments_for_sid, col_to_all_adjustments): """ Merge adjustments for a particular sid into a dictionary cont...
for col_name in all_adjustments_for_sid: if col_name not in col_to_all_adjustments: col_to_all_adjustments[col_name] = {} for ts in all_adjustments_for_sid[col_name]: adjs = all_adjustments_for_sid[col_name][ts] add_new_adjustments(col_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 get_adjustments(self, zero_qtr_data, requested_qtr_data, last_per_qtr, dates, assets, columns, **kwargs): """ Creates an AdjustedArray from the given estimat...
zero_qtr_data.sort_index(inplace=True) # Here we want to get the LAST record from each group of records # corresponding to a single quarter. This is to ensure that we select # the most up-to-date event date in case the event date changes. quarter_shifts = zero_qtr_data.groupby(...
<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_overwrites_for_quarter(self, col_to_overwrites, next_qtr_start_idx, last_per_qtr, quarters_with_estimates_for_sid, requested_quarter, sid, sid_idx, col...
for col in columns: column_name = self.name_map[col.name] if column_name not in col_to_overwrites: col_to_overwrites[column_name] = {} # If there are estimates for the requested quarter, # overwrite all values going up to the starting index of ...
<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_last_data_per_qtr(self, assets_with_data, columns, dates, data_query_cutoff_times): """ Determine the last piece of information we know for each column o...
# Get a DataFrame indexed by date with a MultiIndex of columns of # [self.estimates.columns, normalized_quarters, sid], where each cell # contains the latest data for that day. last_per_qtr = last_in_date_group( self.estimates, data_query_cutoff_times, ...
<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_zeroth_quarter_idx(self, stacked_last_per_qtr): """ Filters for releases that are on or after each simulation date and determines the previous quarter by...
previous_releases_per_date = stacked_last_per_qtr.loc[ stacked_last_per_qtr[EVENT_DATE_FIELD_NAME] <= stacked_last_per_qtr.index.get_level_values(SIMULATION_DATES) ].groupby( level=[SIMULATION_DATES, SID_FIELD_NAME], as_index=False, # Here we ...
<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_adjustments_for_sid(self, group, dates, requested_qtr_data, last_per_qtr, sid_to_idx, columns, col_to_all_adjustments, split_adjusted_asof_idx=None, split...
all_adjustments_for_sid = {} sid = int(group.name) self.collect_overwrites_for_sid(group, dates, requested_qtr_data, last_per_qtr, sid_...
<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_adjustments(self, zero_qtr_data, requested_qtr_data, last_per_qtr, dates, assets, columns, **kwargs): """ Calculates both split adjustments and overwrite...
split_adjusted_cols_for_group = [ self.name_map[col.name] for col in columns if self.name_map[col.name] in self._split_adjusted_column_names ] # Add all splits to the adjustment dict for this sid. split_adjusted_asof_idx = self.get_split_adjusted_asof...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def determine_end_idx_for_adjustment(self, adjustment_ts, dates, upper_bound, requested_quarter, sid_estimates): """ Determines the date until which the adjustme...
end_idx = upper_bound # Find the next newest kd that happens on or after # the date of this adjustment newest_kd_for_qtr = sid_estimates[ (sid_estimates[NORMALIZED_QUARTERS] == requested_quarter) & (sid_estimates[TS_FIELD_NAME] >= adjustment_ts) ][TS_FIEL...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def collect_pre_split_asof_date_adjustments( self, split_adjusted_asof_date_idx, sid_idx, pre_adjustments, requested_split_adjusted_columns ): """ Collect split ...
col_to_split_adjustments = {} if len(pre_adjustments[0]): adjustment_values, date_indexes = pre_adjustments for column_name in requested_split_adjusted_columns: col_to_split_adjustments[column_name] = {} # We need to undo all adjustments that happ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def collect_post_asof_split_adjustments(self, post_adjustments, requested_qtr_data, sid, sid_idx, sid_estimates, requested_split_adjusted_columns): """ Collect s...
col_to_split_adjustments = {} if post_adjustments: # Get an integer index requested_qtr_timeline = requested_qtr_data[ SHIFTED_NORMALIZED_QTRS ][sid].reset_index() requested_qtr_timeline = requested_qtr_timeline[ requested_...
<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_split_adjustments_with_overwrites( self, pre, post, overwrites, requested_split_adjusted_columns ): """ Merge split adjustments with the dict containin...
for column_name in requested_split_adjusted_columns: # We can do a merge here because the timestamps in 'pre' and # 'post' are guaranteed to not overlap. if pre: # Either empty or contains all columns. for ts in pre[column_name]: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def collect_split_adjustments(self, adjustments_for_sid, requested_qtr_data, dates, sid, sid_idx, sid_estimates, split_adjusted_asof_idx, pre_adjustments, post_ad...
(pre_adjustments_dict, post_adjustments_dict) = self._collect_adjustments( requested_qtr_data, sid, sid_idx, sid_estimates, split_adjusted_asof_idx, pre_adjustments, post_adjustments, requested_split_adjust...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def collect_split_adjustments(self, adjustments_for_sid, requested_qtr_data, dates, sid, sid_idx, sid_estimates, split_adjusted_asof_idx, pre_adjustments, post_ad...
(pre_adjustments_dict, post_adjustments_dict) = self._collect_adjustments( requested_qtr_data, sid, sid_idx, sid_estimates, split_adjusted_asof_idx, pre_adjustments, post_adjustments, requested_split_adjust...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_span(cls, inputs, window_length, span, **kwargs): """ Convenience constructor for passing `decay_rate` in terms of `span`. Forwards `decay_rate` as `1 -...
if span <= 1: raise ValueError( "`span` must be a positive number. %s was passed." % span ) decay_rate = (1.0 - (2.0 / (1.0 + span))) assert 0.0 < decay_rate <= 1.0 return cls( inputs=inputs, window_length=window_length, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_halflife(cls, inputs, window_length, halflife, **kwargs): """ Convenience constructor for passing ``decay_rate`` in terms of half life. Forwards ``decay...
if halflife <= 0: raise ValueError( "`span` must be a positive number. %s was passed." % halflife ) decay_rate = exp(log(.5) / halflife) assert 0.0 < decay_rate <= 1.0 return cls( inputs=inputs, window_length=window_length...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_center_of_mass(cls, inputs, window_length, center_of_mass, **kwargs): """ Convenience constructor for passing `decay_rate` in terms of center of mass. F...
return cls( inputs=inputs, window_length=window_length, decay_rate=(1.0 - (1.0 / (1.0 + center_of_mass))), **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 tolerant_equals(a, b, atol=10e-7, rtol=10e-7, equal_nan=False): """Check if a and b are equal with some tolerance. Parameters a, b : float The floats to chec...
if equal_nan and isnan(a) and isnan(b): return True return math.fabs(a - b) <= (atol + rtol * math.fabs(b))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def round_if_near_integer(a, epsilon=1e-4): """ Round a to the nearest integer if that integer is within an epsilon of a. """
if abs(a - round(a)) <= epsilon: return round(a) else: return 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 binop_return_dtype(op, left, right): """ Compute the expected return dtype for the given binary operator. Parameters op : str left : numpy.dtype Dtype of lef...
if is_comparison(op): if left != right: raise TypeError( "Don't know how to compute {left} {op} {right}.\n" "Comparisons are only supported between Factors of equal " "dtypes.".format(left=left, op=op, right=right) ) return boo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def binary_operator(op): """ Factory function for making binary operator methods on a Factor subclass. Returns a function, "binary_operator" suitable for impleme...
# When combining a Factor with a NumericalExpression, we use this # attrgetter instance to defer to the commuted implementation of the # NumericalExpression operator. commuted_method_getter = attrgetter(method_name_for_op(op, commute=True)) @with_doc("Binary Operator: '%s'" % op) @with_name(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 reflected_binary_operator(op): """ Factory function for making binary operator methods on a Factor. Returns a function, "reflected_binary_operator" suitable ...
assert not is_comparison(op) @with_name(method_name_for_op(op, commute=True)) @coerce_numbers_to_my_dtype def reflected_binary_operator(self, other): if isinstance(self, NumericalExpression): self_expr, other_expr, new_inputs = self.build_binary_op( op, other ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unary_operator(op): """ Factory function for making unary operator methods for Factors. """
# Only negate is currently supported. valid_ops = {'-'} if op not in valid_ops: raise ValueError("Invalid unary operator %s." % op) @with_doc("Unary Operator: '%s'" % op) @with_name(unary_op_name(op)) def unary_operator(self): if self.dtype != float64_dtype: raise T...