Plot Functions

This section containts some functions that allows us to create charts that helps us to analyze quickly the properties of our optimum portfolios.

The following example construct the portfolios and the efficient frontier that will be plot using the functions of this module.

Example

import numpy as np
import pandas as pd
import yfinance as yf
import riskfolio.Portfolio as pf
import riskfolio.PlotFunctions as plf

yf.pdr_override()

# Date range
start = '2017-01-01'
end = '2019-12-30'

# List of assets
tickers = ['JCI', 'TGT', 'CMCSA', 'CPB', 'MO', 'NBL', 'APA', 'MMC', 'JPM',
          'ZION', 'PSA', 'AGN', 'BAX', 'BMY', 'LUV', 'PCAR', 'TXT', 'DHR',
          'DE', 'MSFT', 'HPQ', 'SEE', 'VZ', 'CNP', 'NI']
tickers.sort()

# Downloading the data
data = yf.download(tickers, start = start, end = end)
data = data.loc[:,('Adj Close', slice(None))]
data.columns = tickers
assets = data.pct_change().dropna()

Y = assets

# Creating the Portfolio Object
port = pf.Portfolio(returns=Y)

# To display dataframes values in percentage format
pd.options.display.float_format = '{:.4%}'.format

# Choose the risk measure
rm = 'MSV'  # Semi Standard Deviation

# Estimate inputs of the model (historical estimates)
port.assets_stats(method='hist')

# Estimate the portfolio that maximizes the risk adjusted return ratio
w1 = port.optimization(model='Classic', rm=rm, obj='Sharpe', rf=0.0, l=0, hist=True)

# Estimate points in the efficient frontier mean - semi standard deviation
ws = port.efficient_frontier(model='Classic', rm=rm, points=20, rf=0, hist=True)

Module Functions

PlotFunctions.plot_series(returns, w, cmap='tab20', height=6, width=10, ax=None)[source]

Create a chart with the compound cumulated of the portfolios.

Parameters
  • returns (DataFrame) – Assets returns.

  • w (DataFrame) – Portfolio weights.

  • cmap (cmap, optional) – Colorscale, represente the risk adjusted return ratio. The default is ‘tab20’.

  • height (float, optional) – Height of the image in inches. The default is 6.

  • width (float, optional) – Width of the image in inches. The default is 10.

  • ax (matplotlib axis, optional) – If provided, plot on this axis. The default is None.

Raises

ValueError – When the value cannot be calculated.

Returns

ax – Returns the Axes object with the plot for further tweaking.

Return type

matplotlib axis

Example

ax = plf.plot_series(data=Y, w=ws, cmap='tab20', height=6, width=10, ax=None)
_images/Port_Series.png
PlotFunctions.plot_frontier(w_frontier, mu, cov=None, returns=None, rm='MV', rf=0, alpha=0.01, cmap='viridis', w=None, label='Portfolio', marker='*', s=16, c='r', height=6, width=10, ax=None)[source]

Creates a plot of the efficient frontier for a risk measure specified by the user.

Parameters
  • w_frontier (DataFrame) – Portfolio weights of some points in the efficient frontier.

  • mu (DataFrame of shape (1, n_assets)) – Vector of expected returns, where n_assets is the number of assets.

  • cov (DataFrame of shape (n_features, n_features)) – Covariance matrix, where n_features is the number of features.

  • returns (DataFrame of shape (n_samples, n_features)) – Features matrix, where n_samples is the number of samples and n_features is the number of features.

  • rm (str, optional) – Risk measure used to create the frontier. The default is ‘MV’.

  • rf (float, optional) – Risk free rate or minimum aceptable return. The default is 0.

  • alpha (float, optional) – Significante level of VaR, CVaR and CDaR. The default is 0.01.

  • cmap (cmap, optional) – Colorscale, represente the risk adjusted return ratio. The default is ‘viridis’.

  • w (DataFrame, optional) – A portfolio specified by the user. The default is None.

  • label (str, optional) – Name of portfolio that appear on plot legend. The default is ‘Portfolio’.

  • marker (str, optional) – Marker of w_. The default is ‘*’.

  • s (float, optional) – Size of marker. The default is 16.

  • c (str, optional) – Color of marker. The default is ‘r’.

  • height (float, optional) – Height of the image in inches. The default is 6.

  • width (float, optional) – Width of the image in inches. The default is 10.

  • ax (matplotlib axis, optional) – If provided, plot on this axis. The default is None.

Raises

ValueError – When the value cannot be calculated.

Returns

ax – Returns the Axes object with the plot for further tweaking.

Return type

matplotlib Axes

Example

label = 'Max Risk Adjusted Return Portfolio'
mu = port.mu
cov = port.cov
returns = port.returns

ax = plf.plot_frontier(w_frontier=ws, mu=mu, cov=cov, returns=returns,
                       rm=rm, rf=0, alpha=0.01, cmap='viridis', w=w1,
                       label='Portfolio', marker='*', s=16, c='r',
                       height=6, width=10, ax=None)
_images/MSV_Frontier.png
PlotFunctions.plot_pie(w, title='', others=0.05, nrow=25, cmap='tab20', height=6, width=8, ax=None)[source]

Create a pie chart with portfolio weights.

Parameters
  • w (DataFrame) – Weights of the portfolio.

  • title (str, optional) – Title of the chart. The default is ‘’.

  • others (float, optional) – Percentage of others section. The default is 0.05.

  • nrow (int, optional) – Number of rows of the legend. The default is 25.

  • cmap (cmap, optional) – Color scale, represente the risk adjusted return ratio. The default is ‘tab20’.

  • height (float, optional) – Height of the image in inches. The default is 10.

  • width (float, optional) – Width of the image in inches. The default is 10.

  • ax (matplotlib axis, optional) – If provided, plot on this axis. The default is None.

Raises

ValueError – When the value cannot be calculated.

Returns

ax – Returns the Axes object with the plot for further tweaking.

Return type

matplotlib axis.

Example

ax = plf.plot_pie(w=w1, title='Portafolio', height=6, width=10, cmap="tab20", ax=None)
_images/Pie_Chart.png
PlotFunctions.plot_frontier_area(w_frontier, nrow=25, cmap='tab20', height=6, width=10, ax=None)[source]

Create a chart with te asset structure of the efficient frontier.

Parameters
  • w_frontier (DataFrame) – Weights of portfolios in the efficient frontier.

  • nrow (int, optional) – Number of rows of the legend. The default is 25.

  • cmap (cmap, optional) – Color scale, represente the risk adjusted return ratio. The default is ‘tab20’.

  • height (float, optional) – Height of the image in inches. The default is 6.

  • width (float, optional) – Width of the image in inches. The default is 10.

  • ax (matplotlib axis, optional) – If provided, plot on this axis. The default is None.

Raises

ValueError – When the value cannot be calculated.

Returns

ax – Returns the Axes object with the plot for further tweaking.

Return type

matplotlib axis.

Example

ax = plf.plot_frontier_area(w_frontier=ws, cmap="tab20", height=6, width=10, ax=None)
_images/Area_Frontier.png
PlotFunctions.plot_hist(returns, w, alpha=0.01, bins=50, height=6, width=10, ax=None)[source]

Create a histogram of portfolio returns with the risk measures.

Parameters
  • returns (DataFrame) – Assets returns.

  • w (DataFrame, optional) – A portfolio specified by the user to compare with the efficient frontier. The default is None.

  • alpha (float, optional) – Significante level of VaR, CVaR and CDaR. The default is 0.01.

  • bins (float, optional) – Number of bins of the histogram. The default is 50.

  • height (float, optional) – Height of the image in inches. The default is 6.

  • width (float, optional) – Width of the image in inches. The default is 10.

  • ax (matplotlib axis, optional) – If provided, plot on this axis. The default is None.

Raises

ValueError – When the value cannot be calculated.

Returns

ax – Returns the Axes object with the plot for further tweaking.

Return type

matplotlib axis.

Example

ax = plf.plot_hist(data=Y, w=w1, alpha=0.01, bins=50, height=6, width=10, ax=None)
_images/Histogram.png
PlotFunctions.plot_drawdown(nav, w, alpha=0.01, height=8, width=10, ax=None)[source]

Create a chart with the evolution of portfolio prices and drawdown.

Parameters
  • nav (DataFrame) – Cumulative assets returns.

  • w (DataFrame, optional) – A portfolio specified by the user to compare with the efficient frontier. The default is None.

  • alpha (float, optional) – Significante level of VaR, CVaR and CDaR. The default is 0.01.

  • height (float, optional) – Height of the image in inches. The default is 8.

  • width (float, optional) – Width of the image in inches. The default is 10.

  • ax (matplotlib axis, optional) – If provided, plot on this axis. The default is None.

Raises

ValueError – When the value cannot be calculated.

Returns

ax – Returns the Axes object with the plot for further tweaking.

Return type

matplotlib axis.

Example

::

nav=port.nav

ax = plf.plot_drawdown(nav=nav, w=w1, alpha=0.01, height=8, width=10, ax=None)

_images/Drawdown.png