INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Simply returns the score of the underlying CV model
def score(self, X, y, **kwargs): """ Simply returns the score of the underlying CV model """ return self.estimator.score(X, y, **kwargs)
Draws the alpha plot based on the values on the estimator.
def draw(self): """ Draws the alpha plot based on the values on the estimator. """ # Search for the correct parameters on the estimator. alphas = self._find_alphas_param() errors = self._find_errors_param() alpha = self.estimator.alpha_ # Get decision from the e...
Searches for the parameter on the estimator that contains the array of alphas that was used to produce the error selection. If it cannot find the parameter then a YellowbrickValueError is raised.
def _find_alphas_param(self): """ Searches for the parameter on the estimator that contains the array of alphas that was used to produce the error selection. If it cannot find the parameter then a YellowbrickValueError is raised. """ # NOTE: The order of the search is ve...
Searches for the parameter on the estimator that contains the array of errors that was used to determine the optimal alpha. If it cannot find the parameter then a YellowbrickValueError is raised.
def _find_errors_param(self): """ Searches for the parameter on the estimator that contains the array of errors that was used to determine the optimal alpha. If it cannot find the parameter then a YellowbrickValueError is raised. """ # NOTE: The order of the search is ve...
The fit method is the primary entry point for the manual alpha selection visualizer. It sets the alpha param for each alpha in the alphas list on the wrapped estimator, then scores the model using the passed in X and y data set. Those scores are then aggregated and drawn using matplotlib...
def fit(self, X, y, **args): """ The fit method is the primary entry point for the manual alpha selection visualizer. It sets the alpha param for each alpha in the alphas list on the wrapped estimator, then scores the model using the passed in X and y data set. Those scores are t...
Draws the alphas values against their associated error in a similar fashion to the AlphaSelection visualizer.
def draw(self): """ Draws the alphas values against their associated error in a similar fashion to the AlphaSelection visualizer. """ # Plot the alpha against the error self.ax.plot(self.alphas, self.errors, label=self.name.lower()) # Draw a dashed vline at the a...
Display a barchart with the counts of different parts of speech in X, which consists of a part-of-speech-tagged corpus, which the visualizer expects to be a list of lists of lists of (token, tag) tuples. Parameters ---------- X : list or generator Should be provided as a list of documen...
def postag( X, ax=None, tagset="penn_treebank", colormap=None, colors=None, frequency=False, **kwargs ): """ Display a barchart with the counts of different parts of speech in X, which consists of a part-of-speech-tagged corpus, which the visualizer expects to be a list of li...
Fits the corpus to the appropriate tag map. Text documents must be tokenized & tagged before passing to fit. Parameters ---------- X : list or generator Should be provided as a list of documents or a generator that yields a list of documents that contain a list o...
def fit(self, X, y=None, **kwargs): """ Fits the corpus to the appropriate tag map. Text documents must be tokenized & tagged before passing to fit. Parameters ---------- X : list or generator Should be provided as a list of documents or a generator ...
Scan through the corpus to compute counts of each Universal Dependencies part-of-speech. Parameters ---------- X : list or generator Should be provided as a list of documents or a generator that yields a list of documents that contain a list of senten...
def _handle_universal(self, X): """ Scan through the corpus to compute counts of each Universal Dependencies part-of-speech. Parameters ---------- X : list or generator Should be provided as a list of documents or a generator that yields a list of...
Create a part-of-speech tag mapping using the Penn Treebank tags Parameters ---------- X : list or generator Should be provided as a list of documents or a generator that yields a list of documents that contain a list of sentences that contain (token, tag) tu...
def _handle_treebank(self, X): """ Create a part-of-speech tag mapping using the Penn Treebank tags Parameters ---------- X : list or generator Should be provided as a list of documents or a generator that yields a list of documents that contain a list of...
Finalize the plot with ticks, labels, and title Parameters ---------- kwargs: dict generic keyword arguments.
def finalize(self, **kwargs): """ Finalize the plot with ticks, labels, and title Parameters ---------- kwargs: dict generic keyword arguments. """ # NOTE: not deduping here, so this is total, not unique self.set_title( "PosTag plo...
Display a projection of a vectorized corpus in two dimensions using TSNE, a nonlinear dimensionality reduction method that is particularly well suited to embedding in two or three dimensions for visualization as a scatter plot. TSNE is widely used in text analysis to show clusters or groups of documents...
def tsne(X, y=None, ax=None, decompose='svd', decompose_by=50, classes=None, colors=None, colormap=None, alpha=0.7, **kwargs): """ Display a projection of a vectorized corpus in two dimensions using TSNE, a nonlinear dimensionality reduction method that is particularly well suited to embeddin...
Creates an internal transformer pipeline to project the data set into 2D space using TSNE, applying an pre-decomposition technique ahead of embedding if necessary. This method will reset the transformer on the class, and can be used to explore different decompositions. Parameters ...
def make_transformer(self, decompose='svd', decompose_by=50, tsne_kwargs={}): """ Creates an internal transformer pipeline to project the data set into 2D space using TSNE, applying an pre-decomposition technique ahead of embedding if necessary. This method will reset the transformer on ...
Finalize the drawing by adding a title and legend, and removing the axes objects that do not convey information about TNSE.
def finalize(self, **kwargs): """ Finalize the drawing by adding a title and legend, and removing the axes objects that do not convey information about TNSE. """ self.set_title( "TSNE Projection of {} Documents".format(self.n_instances_) ) # Remove th...
Reads the python file defined in the VERSION_PATH to find the get_version function, and executes it to ensure that it is loaded correctly. Separating the version in this way ensures no additional code is executed.
def get_version(path=VERSION_PATH): """ Reads the python file defined in the VERSION_PATH to find the get_version function, and executes it to ensure that it is loaded correctly. Separating the version in this way ensures no additional code is executed. """ namespace = {} exec(read(path), na...
Yields a generator of requirements as defined by the REQUIRE_PATH which should point to a requirements.txt output by `pip freeze`.
def get_requires(path=REQUIRE_PATH): """ Yields a generator of requirements as defined by the REQUIRE_PATH which should point to a requirements.txt output by `pip freeze`. """ for line in read(path).splitlines(): line = line.strip() if line and not line.startswith('#'): y...
Returns the long_description_content_type based on the extension of the package describe path (e.g. .txt, .rst, or .md).
def get_description_type(path=PKG_DESCRIBE): """ Returns the long_description_content_type based on the extension of the package describe path (e.g. .txt, .rst, or .md). """ _, ext = os.path.splitext(path) return { ".rst": "text/x-rst", ".txt": "text/plain", ".md": "text/...
Displays a learning curve based on number of samples vs training and cross validation scores. The learning curve aims to show how a model learns and improves with experience. This helper function is a quick wrapper to utilize the LearningCurve for one-off analysis. Parameters ---------- mo...
def learning_curve(model, X, y, ax=None, groups=None, train_sizes=DEFAULT_TRAIN_SIZES, cv=None, scoring=None, exploit_incremental_learning=False, n_jobs=1, pre_dispatch="all", shuffle=False, random_state=None, **kwargs): """ Displays a learning curve b...
Fits the learning curve with the wrapped model to the specified data. Draws training and test score curves and saves the scores to the estimator. Parameters ---------- X : array-like, shape (n_samples, n_features) Training vector, where n_samples is the number of sam...
def fit(self, X, y=None): """ Fits the learning curve with the wrapped model to the specified data. Draws training and test score curves and saves the scores to the estimator. Parameters ---------- X : array-like, shape (n_samples, n_features) Trainin...
Renders the training and test learning curves.
def draw(self, **kwargs): """ Renders the training and test learning curves. """ # Specify the curves to draw and their labels labels = ("Training Score", "Cross Validation Score") curves = ( (self.train_scores_mean_, self.train_scores_std_), (self...
Displays each feature as a vertical axis and each instance as a line. This helper function is a quick wrapper to utilize the ParallelCoordinates Visualizer (Transformer) for one-off analysis. Parameters ---------- X : ndarray or DataFrame of shape n x m A matrix of n instances with m feat...
def parallel_coordinates(X, y, ax=None, features=None, classes=None, normalize=None, sample=1.0, color=None, colormap=None, alpha=None, fast=False, vlines=True, vlines_kwds=None, **kwargs): """Displays each feature as a vertical axis and eac...
The fit method is the primary drawing input for the visualization since it has both the X and y data required for the viz and the transform method does not. Parameters ---------- X : ndarray or DataFrame of shape n x m A matrix of n instances with m features ...
def fit(self, X, y=None, **kwargs): """ The fit method is the primary drawing input for the visualization since it has both the X and y data required for the viz and the transform method does not. Parameters ---------- X : ndarray or DataFrame of shape n x m ...
Called from the fit method, this method creates the parallel coordinates canvas and draws each instance and vertical lines on it. Parameters ---------- X : ndarray of shape n x m A matrix of n instances with m features y : ndarray of length n An array or...
def draw(self, X, y, **kwargs): """ Called from the fit method, this method creates the parallel coordinates canvas and draws each instance and vertical lines on it. Parameters ---------- X : ndarray of shape n x m A matrix of n instances with m features ...
Draw the instances colored by the target y such that each line is a single instance. This is the "slow" mode of drawing, since each instance has to be drawn individually. However, in so doing, the density of instances in braids is more apparent since lines have an independent alpha that ...
def draw_instances(self, X, y, **kwargs): """ Draw the instances colored by the target y such that each line is a single instance. This is the "slow" mode of drawing, since each instance has to be drawn individually. However, in so doing, the density of instances in braids is mor...
Draw the instances colored by the target y such that each line is a single class. This is the "fast" mode of drawing, since the number of lines drawn equals the number of classes, rather than the number of instances. However, this drawing method sacrifices inter-class density of points u...
def draw_classes(self, X, y, **kwargs): """ Draw the instances colored by the target y such that each line is a single class. This is the "fast" mode of drawing, since the number of lines drawn equals the number of classes, rather than the number of instances. However, this drawi...
Finalize executes any subclass-specific axes finalization steps. The user calls poof and poof calls finalize. Parameters ---------- kwargs: generic keyword arguments.
def finalize(self, **kwargs): """ Finalize executes any subclass-specific axes finalization steps. The user calls poof and poof calls finalize. Parameters ---------- kwargs: generic keyword arguments. """ # Set the title self.set_title( ...
Displays a validation curve for the specified param and values, plotting both the train and cross-validated test scores. The validation curve is a visual, single-parameter grid search used to tune a model to find the best balance between error due to bias and error due to variance. This helper function...
def validation_curve(model, X, y, param_name, param_range, ax=None, logx=False, groups=None, cv=None, scoring=None, n_jobs=1, pre_dispatch="all", **kwargs): """ Displays a validation curve for the specified param and values, plotting both the train and cross-validat...
Fits the validation curve with the wrapped estimator and parameter array to the specified data. Draws training and test score curves and saves the scores to the visualizer. Parameters ---------- X : array-like, shape (n_samples, n_features) Training vector, where n_s...
def fit(self, X, y=None): """ Fits the validation curve with the wrapped estimator and parameter array to the specified data. Draws training and test score curves and saves the scores to the visualizer. Parameters ---------- X : array-like, shape (n_samples, n_fe...
Proxy property to smartly access the classes from the estimator or stored locally on the score visualizer for visualization.
def classes_(self): """ Proxy property to smartly access the classes from the estimator or stored locally on the score visualizer for visualization. """ if self.__classes is None: try: return self.estimator.classes_ except AttributeError: ...
Parameters ---------- X : ndarray or DataFrame of shape n x m A matrix of n instances with m features y : ndarray or Series of length n An array or series of target or class values kwargs: keyword arguments passed to Scikit-Learn API. Returns -...
def fit(self, X, y=None, **kwargs): """ Parameters ---------- X : ndarray or DataFrame of shape n x m A matrix of n instances with m features y : ndarray or Series of length n An array or series of target or class values kwargs: keyword argument...
Load a dataset by name and return specified format.
def _load_dataset(name, data_home=None, return_dataset=False): """ Load a dataset by name and return specified format. """ info = DATASETS[name] data = Dataset(name, data_home=data_home, **info) if return_dataset: return data return data.to_data()
Load a corpus object by name.
def _load_corpus(name, data_home=None): """ Load a corpus object by name. """ info = DATASETS[name] return Corpus(name, data_home=data_home, **info)
Converts color strings into a color listing.
def colors(self, value): """ Converts color strings into a color listing. """ if isinstance(value, str): # Must import here to avoid recursive import from .palettes import PALETTES if value not in PALETTES: raise YellowbrickValueError(...
Return a property attribute for new-style classes that only calls its getter on the first access. The result is stored and on subsequent accesses is returned, preventing the need to call the getter any more. Parameters ---------- fget: function The getter method to memoize for subsequent ac...
def memoized(fget): """ Return a property attribute for new-style classes that only calls its getter on the first access. The result is stored and on subsequent accesses is returned, preventing the need to call the getter any more. Parameters ---------- fget: function The getter met...
Creates 2x2 grid plot of the 4 anscombe datasets for illustration.
def anscombe(): """ Creates 2x2 grid plot of the 4 anscombe datasets for illustration. """ _, ((axa, axb), (axc, axd)) = plt.subplots(2, 2, sharex='col', sharey='row') colors = get_color_cycle() for arr, ax, color in zip(ANSCOMBE, (axa, axb, axc, axd), colors): x = arr[0] y = a...
Displays each feature as an axis around a circle surrounding a scatter plot whose points are each individual instance. This helper function is a quick wrapper to utilize the RadialVisualizer (Transformer) for one-off analysis. Parameters ---------- X : ndarray or DataFrame of shape n x m ...
def radviz(X, y=None, ax=None, features=None, classes=None, color=None, colormap=None, alpha=1.0, **kwargs): """ Displays each feature as an axis around a circle surrounding a scatter plot whose points are each individual instance. This helper function is a quick wrapper to utilize the Radia...
MinMax normalization to fit a matrix in the space [0,1] by column.
def normalize(X): """ MinMax normalization to fit a matrix in the space [0,1] by column. """ a = X.min(axis=0) b = X.max(axis=0) return (X - a[np.newaxis, :]) / ((b - a)[np.newaxis, :])
Called from the fit method, this method creates the radviz canvas and draws each instance as a class or target colored point, whose location is determined by the feature data set.
def draw(self, X, y, **kwargs): """ Called from the fit method, this method creates the radviz canvas and draws each instance as a class or target colored point, whose location is determined by the feature data set. """ # Convert from dataframe if is_dataframe(X):...
Finalize executes any subclass-specific axes finalization steps. The user calls poof and poof calls finalize. Parameters ---------- kwargs: generic keyword arguments.
def finalize(self, **kwargs): """ Finalize executes any subclass-specific axes finalization steps. The user calls poof and poof calls finalize. Parameters ---------- kwargs: generic keyword arguments. """ # Set the title self.set_title( ...
Returns the index of the value at the Qth percentile in array a.
def percentile_index(a, q): """ Returns the index of the value at the Qth percentile in array a. """ return np.where( a==np.percentile(a, q, interpolation='nearest') )[0][0]
Raises a well formatted exception if s is not in valid, otherwise does not raise an exception. Uses ``param_name`` to identify the parameter.
def validate_string_param(s, valid, param_name="param"): """ Raises a well formatted exception if s is not in valid, otherwise does not raise an exception. Uses ``param_name`` to identify the parameter. """ if s.lower() not in valid: raise YellowbrickValueError( "unknown {} '{}',...
Quick Method: Intercluster distance maps display an embedding of the cluster centers in 2 dimensions with the distance to other centers preserved. E.g. the closer to centers are in the visualization, the closer they are in the original feature space. The clusters are sized according to a scoring metric...
def intercluster_distance(model, X, y=None, ax=None, min_size=400, max_size=25000, embedding='mds', scoring='membership', legend=True, legend_loc="lower left", legend_size=1.5, random_state=None, **kwargs): """Qu...
Returns the legend axes, creating it only on demand by creating a 2" by 2" inset axes that has no grid, ticks, spines or face frame (e.g is mostly invisible). The legend can then be drawn on this axes.
def lax(self): """ Returns the legend axes, creating it only on demand by creating a 2" by 2" inset axes that has no grid, ticks, spines or face frame (e.g is mostly invisible). The legend can then be drawn on this axes. """ if inset_locator is None: raise Yel...
Creates the internal transformer that maps the cluster center's high dimensional space to its two dimensional space.
def transformer(self): """ Creates the internal transformer that maps the cluster center's high dimensional space to its two dimensional space. """ ttype = self.embedding.lower() # transformer method type if ttype == 'mds': return MDS(n_components=2, random_s...
Searches for or creates cluster centers for the specified clustering algorithm. This algorithm ensures that that the centers are appropriately drawn and scaled so that distance between clusters are maintained.
def cluster_centers_(self): """ Searches for or creates cluster centers for the specified clustering algorithm. This algorithm ensures that that the centers are appropriately drawn and scaled so that distance between clusters are maintained. """ # TODO: Handle agg...
Fit the clustering model, computing the centers then embeds the centers into 2D space using the embedding method specified.
def fit(self, X, y=None): """ Fit the clustering model, computing the centers then embeds the centers into 2D space using the embedding method specified. """ with Timer() as self.fit_time_: # Fit the underlying estimator self.estimator.fit(X, y) ...
Draw the embedded centers with their sizes on the visualization.
def draw(self): """ Draw the embedded centers with their sizes on the visualization. """ # Compute the sizes of the markers from their score sizes = self._get_cluster_sizes() # Draw the scatter plots with associated sizes on the graph self.ax.scatter( ...
Finalize the visualization to create an "origin grid" feel instead of the default matplotlib feel. Set the title, remove spines, and label the grid with components. This function also adds a legend from the sizes if required.
def finalize(self): """ Finalize the visualization to create an "origin grid" feel instead of the default matplotlib feel. Set the title, remove spines, and label the grid with components. This function also adds a legend from the sizes if required. """ # Set the ...
Determines the "scores" of the cluster, the metric that determines the size of the cluster visualized on the visualization.
def _score_clusters(self, X, y=None): """ Determines the "scores" of the cluster, the metric that determines the size of the cluster visualized on the visualization. """ stype = self.scoring.lower() # scoring method name if stype == "membership": return np.bi...
Returns the marker size (in points, e.g. area of the circle) based on the scores, using the prop_to_size scaling mechanism.
def _get_cluster_sizes(self): """ Returns the marker size (in points, e.g. area of the circle) based on the scores, using the prop_to_size scaling mechanism. """ # NOTE: log and power are hardcoded, should we allow the user to specify? return prop_to_size( sel...
Draw a legend that shows relative sizes of the clusters at the 25th, 50th, and 75th percentile based on the current scoring metric.
def _make_size_legend(self): """ Draw a legend that shows relative sizes of the clusters at the 25th, 50th, and 75th percentile based on the current scoring metric. """ # Compute the size of the markers and scale them to our figure size # NOTE: the marker size is the area...
Adds a manual legend for a scatter plot to the visualizer where the labels and associated colors are drawn with circle patches instead of determining them from the labels of the artist objects on the axes. This helper is used either when there are a lot of duplicate labels, no labeled artists, or when t...
def manual_legend(g, labels, colors, **legend_kwargs): """ Adds a manual legend for a scatter plot to the visualizer where the labels and associated colors are drawn with circle patches instead of determining them from the labels of the artist objects on the axes. This helper is used either when the...
Displays frequency distribution plot for text. This helper function is a quick wrapper to utilize the FreqDist Visualizer (Transformer) for one-off analysis. Parameters ---------- X: ndarray or DataFrame of shape n x m A matrix of n instances with m features. In the case of text, ...
def freqdist(X, y=None, ax=None, color=None, N=50, **kwargs): """Displays frequency distribution plot for text. This helper function is a quick wrapper to utilize the FreqDist Visualizer (Transformer) for one-off analysis. Parameters ---------- X: ndarray or DataFrame of shape n x m A...
Called from the fit method, this method gets all the words from the corpus and their corresponding frequency counts. Parameters ---------- X : ndarray or masked ndarray Pass in the matrix of vectorized documents, can be masked in order to sum the word fr...
def count(self, X): """ Called from the fit method, this method gets all the words from the corpus and their corresponding frequency counts. Parameters ---------- X : ndarray or masked ndarray Pass in the matrix of vectorized documents, can be masked...
Called from the fit method, this method creates the canvas and draws the distribution plot on it. Parameters ---------- kwargs: generic keyword arguments.
def draw(self, **kwargs): """ Called from the fit method, this method creates the canvas and draws the distribution plot on it. Parameters ---------- kwargs: generic keyword arguments. """ # Prepare the data bins = np.arange(self.N) word...
The fit method is the primary drawing input for the frequency distribution visualization. It requires vectorized lists of documents and a list of features, which are the actual words from the original corpus (needed to label the x-axis ticks). Parameters ---------- X : n...
def fit(self, X, y=None): """ The fit method is the primary drawing input for the frequency distribution visualization. It requires vectorized lists of documents and a list of features, which are the actual words from the original corpus (needed to label the x-axis ticks). ...
The finalize method executes any subclass-specific axes finalization steps. The user calls poof & poof calls finalize. Parameters ---------- kwargs: generic keyword arguments.
def finalize(self, **kwargs): """ The finalize method executes any subclass-specific axes finalization steps. The user calls poof & poof calls finalize. Parameters ---------- kwargs: generic keyword arguments. """ # Set the title self.set_title( ...
Quick method: Displays precision, recall, F1, and support scores for the model. Integrates numerical scores as well as color-coded heatmap. This helper function is a quick wrapper to utilize the ClassificationReport ScoreVisualizer for one-off analysis. Parameters ---------- X : ndarray ...
def classification_report(model, X, y=None, ax=None, classes=None, random_state=None,**kwargs): """Quick method: Displays precision, recall, F1, and support scores for the model. Integrates numerical scores as well as color-coded heatmap. This helper function is a quick wrapp...
Generates the Scikit-Learn classification report. Parameters ---------- X : ndarray or DataFrame of shape n x m A matrix of n instances with m features y : ndarray or Series of length n An array or series of target or class values Returns ------...
def score(self, X, y=None, **kwargs): """ Generates the Scikit-Learn classification report. Parameters ---------- X : ndarray or DataFrame of shape n x m A matrix of n instances with m features y : ndarray or Series of length n An array or series...
Renders the classification report across each axis.
def draw(self): """ Renders the classification report across each axis. """ # Create display grid cr_display = np.zeros((len(self.classes_), len(self._displayed_scores))) # For each class row, append columns for precision, recall, f1, and support for idx, cls in...
Finalize executes any subclass-specific axes finalization steps. The user calls poof and poof calls finalize. Parameters ---------- kwargs: generic keyword arguments.
def finalize(self, **kwargs): """ Finalize executes any subclass-specific axes finalization steps. The user calls poof and poof calls finalize. Parameters ---------- kwargs: generic keyword arguments. """ # Set the title of the classifiation report ...
Create a deprecated ``__getitem__`` method that tells users to use getattr instead. Parameters ---------- name : str The name of the object in the warning message. attrs : iterable[str] The set of allowed attributes. Returns ------- __getitem__ : callable[any, str] ...
def _deprecated_getitem_method(name, attrs): """Create a deprecated ``__getitem__`` method that tells users to use getattr instead. Parameters ---------- name : str The name of the object in the warning message. attrs : iterable[str] The set of allowed attributes. Returns ...
A decorator to wrap with try..except to swallow specific HTTP errors. @skip_http_error((404, 503)) def fetch(): ...
def skip_http_error(statuses): ''' A decorator to wrap with try..except to swallow specific HTTP errors. @skip_http_error((404, 503)) def fetch(): ... ''' assert isinstance(statuses, tuple) def decorator(func): def wrapper(*args, **kwargs): try: ...
Utility for debug/testing
def _symbols2assets(self, symbols): ''' Utility for debug/testing ''' assets = {a.symbol: a for a in self.get_equities()} return [assets[symbol] for symbol in symbols if symbol in assets]
Interface method. Return: pd.Dataframe() with columns MultiIndex [asset -> OHLCV]
def get_bars(self, assets, data_frequency, bar_count=500): ''' Interface method. Return: pd.Dataframe() with columns MultiIndex [asset -> OHLCV] ''' assets_is_scalar = not isinstance(assets, (list, set, tuple)) is_daily = 'd' in data_frequency # 'daily' or '1d' ...
Query historic_agg either minute or day in parallel for multiple symbols, and return in dict. symbols: list[str] size: str ('day', 'minute') _from: str or pd.Timestamp to: str or pd.Timestamp limit: str or int return: dict[str -> pd.DataFrame]
def _symbol_bars( self, symbols, size, _from=None, to=None, limit=None): ''' Query historic_agg either minute or day in parallel for multiple symbols, and return in dict. symbols: list[str] size: str ('da...
Query last_trade in parallel for multiple symbols and return in dict. symbols: list[str] return: dict[str -> polygon.Trade]
def _symbol_trades(self, symbols): ''' Query last_trade in parallel for multiple symbols and return in dict. symbols: list[str] return: dict[str -> polygon.Trade] ''' @skip_http_error((404, 504)) def fetch(symbol): return self._api.polygon.l...
Track and record values each day. Parameters ---------- **kwargs The names and values to record. Notes ----- These values will appear in the performance packets and the performance dataframe passed to ``analyze`` and returned from :func:`~zip...
def record(self, *args, **kwargs): """Track and record values each day. Parameters ---------- **kwargs The names and values to record. Notes ----- These values will appear in the performance packets and the performance dataframe passed to ``a...
Lookup equities by symbol. Parameters: args (iterable[str]): List of ticker symbols for the asset. Returns: equities (List[Equity]): The equity lookuped by the ``symbol``. Raises: AssetNotFound: When could not resolve the ``Asset`` by ``symbol``.
def symbols(self, *args, **kwargs): '''Lookup equities by symbol. Parameters: args (iterable[str]): List of ticker symbols for the asset. Returns: equities (List[Equity]): The equity lookuped by the ``symbol``. Raises: AssetNotFound: When could not ...
If asset is unspecified or None, returns a dictionary keyed by asset ID. The dictionary contains a list of orders for each ID, oldest first. If an asset is specified, returns a list of open orders for that asset, oldest first. Orders submitted after before will not be returned. If provid...
def get_all_orders( self, asset=None, before=None, status='all', days_back=None): ''' If asset is unspecified or None, returns a dictionary keyed by asset ID. The dictionary contains a list of orders for each ID, oldest first. I...
DEPRECATED: use ``data.history`` instead.
def history(self, bar_count, frequency, field, ffill=True): """DEPRECATED: use ``data.history`` instead. """ return self.get_history_window( bar_count, frequency, self._calculate_universe(), field, ffill, )
Calculates how many shares/contracts to order based on the type of asset being ordered.
def _calculate_order_value_amount(self, asset, value): """ Calculates how many shares/contracts to order based on the type of asset being ordered. """ if not self.executor.current_data.can_trade(asset): raise CannotOrderDelistedAsset( msg="Cannot order...
Set a restriction on which assets can be ordered. Parameters ---------- restricted_list : container[Asset], SecurityList The assets that cannot be ordered.
def set_do_not_order_list(self, restricted_list, on_error='fail'): """Set a restriction on which assets can be ordered. Parameters ---------- restricted_list : container[Asset], SecurityList The assets that cannot be ordered. """ if isinstance(restricted_list...
translate zipline script into pylivetrader script.
def translate(script): '''translate zipline script into pylivetrader script. ''' tree = ast.parse(script) ZiplineImportVisitor().visit(tree) return astor.to_source(tree)
Constructs an event rule from the factory api.
def make_eventrule(date_rule, time_rule, cal, half_days=True): """ Constructs an event rule from the factory api. """ # Insert the calendar in to the individual rules date_rule.cal = cal time_rule.cal = cal if half_days: inner_rule = date_rule & time_rule else: nhd_rule...
In this method, for the given sector, we'll get the data we need for each stock in the sector from IEX. Once we have the data, we'll check that the earnings reports meet our criteria with `eps_good()`. We'll put stocks that meet those requirements into a dataframe along with all the data about them we'll ne...
def build_sector_fundamentals(sector): ''' In this method, for the given sector, we'll get the data we need for each stock in the sector from IEX. Once we have the data, we'll check that the earnings reports meet our criteria with `eps_good()`. We'll put stocks that meet those requirements into a da...
Create our pipeline.
def make_pipeline(context): """ Create our pipeline. """ # Filter for primary share equities. IsPrimaryShare is a built-in filter. primary_share = IsPrimaryShare() # Not when-issued equities. not_wi = ~IEXCompany.symbol.latest.endswith('.WI') # Equities without LP in their name, .matc...
Record variables at the end of each day.
def my_record_vars(context, data): """ Record variables at the end of each day. """ # Record our variables. record(leverage=context.account.leverage) record(positions=len(context.portfolio.positions)) if 0 < len(context.age): MaxAge = context.age[max( list(context.age.ke...
Retrieve all assets in `sids`. Parameters ---------- sids : iterable of string Assets to retrieve. default_none : bool If True, return None for failed lookups. If False, raise `SidsNotFound`. Returns ------- assets : list[Asse...
def retrieve_all(self, sids, default_none=False): """ Retrieve all assets in `sids`. Parameters ---------- sids : iterable of string Assets to retrieve. default_none : bool If True, return None for failed lookups. If False, raise `Sids...
Retrieve the Asset for a given sid.
def retrieve_asset(self, sid, default_none=False): """ Retrieve the Asset for a given sid. """ try: asset = self._asset_cache[sid] if asset is None and not default_none: raise SidsNotFound(sids=[sid]) return asset except KeyErro...
Retrieve Equity objects for a list of sids. Users generally shouldn't need to this method (instead, they should prefer the more general/friendly `retrieve_assets`), but it has a documented interface and tests because it's used upstream. Parameters ---------- sids : iter...
def retrieve_equities(self, sids): """ Retrieve Equity objects for a list of sids. Users generally shouldn't need to this method (instead, they should prefer the more general/friendly `retrieve_assets`), but it has a documented interface and tests because it's used upstream. ...
Asymmetric rounding function for adjusting prices to two places in a way that "improves" the price. For limit prices, this means preferring to round down on buys and preferring to round up on sells. For stop prices, it means the reverse. If prefer_round_down == True: When .05 below to .95 abo...
def asymmetric_round_price_to_penny(price, prefer_round_down, diff=(0.0095 - .005)): """ Asymmetric rounding function for adjusting prices to two places in a way that "improves" the price. For limit prices, this means preferring to round down on buys and preferring t...
For the given asset or iterable of assets, returns true if all of the following are true: 1) the asset is alive for the session of the current simulation time (if current simulation time is not a market minute, we use the next session) 2) (if we are in minute mode) the asset'...
def can_trade(self, assets): """ For the given asset or iterable of assets, returns true if all of the following are true: 1) the asset is alive for the session of the current simulation time (if current simulation time is not a market minute, we use the next session)...
For the given asset or iterable of assets, returns true if the asset is alive and there is no trade data for the current simulation time. If the asset has never traded, returns False. If the current simulation time is not a valid market time, we use the current time to check if the ass...
def is_stale(self, assets): """ For the given asset or iterable of assets, returns true if the asset is alive and there is no trade data for the current simulation time. If the asset has never traded, returns False. If the current simulation time is not a valid market time, we ...
Internal utility method to get the current simulation time. Possible answers are: - whatever the algorithm's get_datetime() method returns (this is what `self.simulation_dt_func()` points to) - sometimes we're knowingly not in a market minute, like if we're in before_tra...
def _get_current_minute(self): """ Internal utility method to get the current simulation time. Possible answers are: - whatever the algorithm's get_datetime() method returns (this is what `self.simulation_dt_func()` points to) - sometimes we're knowingly not in a mar...
Redirect pylivetrader.api.* operations to the algorithm in the local context.
def api_method(f): ''' Redirect pylivetrader.api.* operations to the algorithm in the local context. ''' @wraps(f) def wrapped(*args, **kwargs): # Get the instance and call the method algorithm = get_context() if algorithm is None: raise RuntimeError( ...
Create our pipeline.
def make_pipeline(context): """ Create our pipeline. """ # Filter for primary share equities. IsPrimaryShare is a built-in filter. primary_share = IsPrimaryShare() # Equities listed as common stock (as opposed to, say, preferred stock). # 'ST00000001' indicates common stock. common_sto...
Parallelize the mapfunc with multithreading. mapfunc calls will be partitioned by the provided list of arguments. Each item in the list will represent one call's arguments. They can be tuples if the function takes multiple arguments, but one-tupling is not necessary. If workers argument is not provided...
def parallelize(mapfunc, workers=None): ''' Parallelize the mapfunc with multithreading. mapfunc calls will be partitioned by the provided list of arguments. Each item in the list will represent one call's arguments. They can be tuples if the function takes multiple arguments, but one-tupling is not...
TODO: for external data (fetch_csv) support, need to update logic here.
def get_adjusted_value( self, assets, field, dt, perspective_dt, data_frequency): ''' TODO: for external data (fetch_csv) support, need to update logic here. ''' return self.backend.get_spot_value( ...
Wrapper around pandas' read_csv.
def load_df_from_file(file_path, sep=",", header=0): """Wrapper around pandas' read_csv.""" with tf.gfile.Open(file_path) as infile: df = pd.read_csv(infile, sep=sep, header=header) return df
Pickle obj to file_name.
def serialize_to_file(obj, file_name, append=False): """Pickle obj to file_name.""" logging.info("Serializing to file %s.", file_name) with tf.gfile.Open(file_name, "a+" if append else "wb") as output_file: pickle.dump(obj, output_file) logging.info("Done serializing to file %s.", file_name)
Savez_compressed obj to file_name.
def savez_two_column(matrix, row_offset, file_name, append=False): """Savez_compressed obj to file_name.""" logging.info("Saving obj to file in two column .npz format %s.", file_name) tc = [] for u, items in enumerate(matrix): user = row_offset + u for item in items: tc.append([user, item]) n...
Compute the product set of array_a and array_b and sort it.
def sorted_product_set(array_a, array_b): """Compute the product set of array_a and array_b and sort it.""" return np.sort( np.concatenate( [array_a[i] * array_b for i in xrange(len(array_a))], axis=0) )[::-1]
Produce additional matches for predictions that have only low-quality matches. Specifically, for each ground-truth find the set of predictions that have maximum overlap with it (including ties); for each prediction in that set, if it is unmatched, then match it to the ground-truth with which it ...
def set_low_quality_matches_(self, matches, all_matches, match_quality_matrix): """ Produce additional matches for predictions that have only low-quality matches. Specifically, for each ground-truth find the set of predictions that have maximum overlap with it (including ties); for each ...
Evaluate on voc dataset. Args: pred_boxlists(list[BoxList]): pred boxlist, has labels and scores fields. gt_boxlists(list[BoxList]): ground truth boxlist, has labels field. iou_thresh: iou thresh use_07_metric: boolean Returns: dict represents the results
def eval_detection_voc(pred_boxlists, gt_boxlists, iou_thresh=0.5, use_07_metric=False): """Evaluate on voc dataset. Args: pred_boxlists(list[BoxList]): pred boxlist, has labels and scores fields. gt_boxlists(list[BoxList]): ground truth boxlist, has labels field. iou_thresh: iou thresh ...
Calculate precision and recall based on evaluation code of PASCAL VOC. This function calculates precision and recall of predicted bounding boxes obtained from a dataset which has :math:`N` images. The code is based on the evaluation code used in PASCAL VOC Challenge.
def calc_detection_voc_prec_rec(gt_boxlists, pred_boxlists, iou_thresh=0.5): """Calculate precision and recall based on evaluation code of PASCAL VOC. This function calculates precision and recall of predicted bounding boxes obtained from a dataset which has :math:`N` images. The code is based on th...
Calculate average precisions based on evaluation code of PASCAL VOC. This function calculates average precisions from given precisions and recalls. The code is based on the evaluation code used in PASCAL VOC Challenge. Args: prec (list of numpy.array): A list of arrays. :obj:`prec[l]...
def calc_detection_voc_ap(prec, rec, use_07_metric=False): """Calculate average precisions based on evaluation code of PASCAL VOC. This function calculates average precisions from given precisions and recalls. The code is based on the evaluation code used in PASCAL VOC Challenge. Args: prec ...
Arguments: proposals: list[BoxList] targets: list[BoxList]
def add_gt_proposals(self, proposals, targets): """ Arguments: proposals: list[BoxList] targets: list[BoxList] """ # Get the device we're operating on device = proposals[0].bbox.device gt_boxes = [target.copy_with_fields([]) for target in targets]...
Arguments: anchors: list[BoxList] objectness: tensor of size N, A, H, W box_regression: tensor of size N, A * 4, H, W
def forward_for_single_feature_map(self, anchors, objectness, box_regression): """ Arguments: anchors: list[BoxList] objectness: tensor of size N, A, H, W box_regression: tensor of size N, A * 4, H, W """ device = objectness.device N, A, H, W =...
Arguments: anchors: list[list[BoxList]] objectness: list[tensor] box_regression: list[tensor] Returns: boxlists (list[BoxList]): the post-processed anchors, after applying box decoding and NMS
def forward(self, anchors, objectness, box_regression, targets=None): """ Arguments: anchors: list[list[BoxList]] objectness: list[tensor] box_regression: list[tensor] Returns: boxlists (list[BoxList]): the post-processed anchors, after ...