text
stringlengths
81
112k
Finds and returns the "knee"or "elbow" value, the normalized knee value, and the x value where the knee is located. def find_knee(self, ): """ Finds and returns the "knee"or "elbow" value, the normalized knee value, and the x value where the knee is located. """ if not ...
Plots the normalized curve, the distance curve (xd, ysn) and the knee, if it exists. def plot_knee_normalized(self, ): """ Plots the normalized curve, the distance curve (xd, ysn) and the knee, if it exists. """ import matplotlib.pyplot as plt plt.figure(figsiz...
Plot the curve and the knee, if it exists def plot_knee(self, ): """ Plot the curve and the knee, if it exists """ import matplotlib.pyplot as plt plt.figure(figsize=(8, 8)) plt.plot(self.x, self.y) plt.vlines(self.knee, plt.ylim()[0], plt.ylim()[1])
A simple pass-through method; calls fit on the estimator and then draws the alpha-error plot. def fit(self, X, y, **kwargs): """ A simple pass-through method; calls fit on the estimator and then draws the alpha-error plot. """ self.estimator.fit(X, y, **kwargs) s...
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() ...
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...
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 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...
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 th...
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...
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...
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...
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...
Called from the fit method, this method creates the canvas and draws the part-of-speech tag mapping as a bar chart. Parameters ---------- kwargs: dict generic keyword arguments. Returns ------- ax : matplotlib axes Axes on which the PosTa...
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 ge...
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...
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 ...
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. ...
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...
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`. ...
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). """ ...
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...
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...
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_m...
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...
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 ...
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...
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 ...
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...
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. ...
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...
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...
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. """ ...
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 -...
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 retur...
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)
Generates a list of colors based on common color arguments, for example the name of a colormap or palette or another iterable of colors. The list is then truncated (or multiplied) to the specific number of requested colors. Parameters ---------- n_colors : int, default: None Specify the...
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...
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...
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(ANSCO...
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 ...
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 ...
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. ...
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 ...
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...
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 ...
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 ...
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 cente...
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. "...
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 ...
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...
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 visualizatio...
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. ...
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 scorin...
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...
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, ...
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...
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...
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 dist...
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 ...
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 ...
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 ------...
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 preci...
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. ...
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] ...
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(): ... ...
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(asse...
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 _...
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] ...
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...
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 symbo...
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...
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, ...
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_dat...
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...
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 = ...
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...
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 L...
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 = contex...
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...
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]) ...
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...
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...
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'...
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...
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...
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 = ...
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...
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...
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 upda...
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.", ...
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: ...
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 ...