Plotting

The plotting module houses all the functions to generate various plots.

Currently implemented:

  • plot_covariance - plot a correlation matrix
  • plot_dendrogram - plot the hierarchical clusters in a portfolio
  • plot_efficient_frontier – plot the efficient frontier, using the CLA algorithm.
  • plot_weights - bar chart of weights
pypfopt.plotting._plot_io(**kwargs)[source]

Helper method to optionally save the figure to file.

Parameters:
  • filename (str, optional) – name of the file to save to, defaults to None (doesn’t save)
  • dpi (int (between 50-500)) – dpi of figure to save or plot, defaults to 300
  • showfig (bool, optional) – whether to plt.show() the figure, defaults to True

Tip

To save the plot, pass filename="somefile.png" as a keyword argument to any of the methods below.

pypfopt.plotting.plot_covariance(cov_matrix, plot_correlation=False, show_tickers=True, **kwargs)[source]

Generate a basic plot of the covariance (or correlation) matrix, given a covariance matrix.

Parameters:
  • cov_matrix (pd.DataFrame or np.ndarray) – covariance matrix
  • plot_correlation (bool, optional) – whether to plot the correlation matrix instead, defaults to False.
  • show_tickers (bool, optional) – whether to use tickers as labels (not recommended for large portfolios), defaults to True
Returns:

matplotlib axis

Return type:

matplotlib.axes object

plot of the covariance matrix
pypfopt.plotting.plot_dendrogram(hrp, show_tickers=True, **kwargs)[source]

Plot the clusters in the form of a dendrogram.

Parameters:
  • hrp (object) – HRPpt object that has already been optimized.
  • show_tickers (bool, optional) – whether to use tickers as labels (not recommended for large portfolios), defaults to True
  • filename (str, optional) – name of the file to save to, defaults to None (doesn’t save)
  • showfig (bool, optional) – whether to plt.show() the figure, defaults to True
Returns:

matplotlib axis

Return type:

matplotlib.axes object

return clusters
pypfopt.plotting.plot_efficient_frontier(cla, points=100, show_assets=True, **kwargs)[source]

Plot the efficient frontier based on a CLA object

Parameters:
  • points (int, optional) – number of points to plot, defaults to 100
  • show_assets (bool, optional) – whether we should plot the asset risks/returns also, defaults to True
  • filename (str, optional) – name of the file to save to, defaults to None (doesn’t save)
  • showfig (bool, optional) – whether to plt.show() the figure, defaults to True
Returns:

matplotlib axis

Return type:

matplotlib.axes object

the Efficient Frontier
pypfopt.plotting.plot_weights(weights, **kwargs)[source]

Plot the portfolio weights as a horizontal bar chart

Parameters:weights ({ticker: weight} dict) – the weights outputted by any PyPortfolioOpt optimiser
Returns:matplotlib axis
Return type:matplotlib.axes object
bar chart to show weights