def plot_risk_con(
    w,
    cov=None,
    returns=None,
    rm="MV",
    rf=0,
    alpha=0.05,
    color="tab:blue",
    height=6,
    width=10,
    ax=None,
):
    r"""
    Create a chart with the risk contribution per asset of the portfolio.

    Parameters
    ----------
    w : DataFrame of shape (n_assets, 1)
        Portfolio weights.
    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 estimate risk contribution.
        The default is 'MV'. Posible values are:

        - 'MV': Standard Deviation.
        - 'MAD': Mean Absolute Deviation.
        - 'MSV': Semi Standard Deviation.
        - 'FLPM': First Lower Partial Moment (Omega Ratio).
        - 'SLPM': Second Lower Partial Moment (Sortino Ratio).
        - 'CVaR': Conditional Value at Risk.
        - 'EVaR': Conditional Value at Risk.
        - 'WR': Worst Realization (Minimax)
        - 'MDD': Maximum Drawdown of uncompounded returns (Calmar Ratio).
        - 'ADD': Average Drawdown of uncompounded returns.
        - 'DaR': Drawdown at Risk of uncompounded returns.
        - 'CDaR': Conditional Drawdown at Risk of uncompounded returns.
        - 'UCI': Ulcer Index of uncompounded returns.

    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.05.
    color : str, optional
        Color used to plot each asset risk contribution.
        The default is 'tab:blue'.
    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 :  matplotlib axis.
        Returns the Axes object with the plot for further tweaking.

    Example
    -------
    ::

        ax = plf.plot_risk_con(w=w2, cov=cov, returns=returns, rm='MSV',
                               rf=0, alpha=0.05, color="tab:blue", height=6,
                               width=10, ax=None)

    .. image:: images/Risk_Con.png


    """

    if not isinstance(w, pd.DataFrame):
        raise ValueError("w must be a DataFrame")

    if ax is None:
        ax = plt.gca()
        fig = plt.gcf()
        fig.set_figwidth(width)
        fig.set_figheight(height)

    item = rmeasures.index(rm)
    title = "Risk (" + rm_names[item] + ") Contribution per Asset"
    ax.set_title(title)

    X = w.index.tolist()

    RC = rk.Risk_Contribution(w,
                              cov=cov,
                              returns=returns,
                              rm=rm,
                              rf=rf,
                              alpha=alpha)

    ax.bar(X, RC, alpha=0.7, color=color, edgecolor="black")

    ax.set_xlim(-0.5, len(X) - 0.5)

    ax.set_yticks(ax.get_yticks())
    ax.set_yticklabels(["{:3.5%}".format(x) for x in ax.get_yticks()])
    ax.grid(linestyle=":")

    fig = plt.gcf()
    fig.tight_layout()

    return ax
Example #2
0
def plot_risk_con(
    w,
    cov=None,
    returns=None,
    rm="MV",
    rf=0,
    alpha=0.01,
    color="tab:blue",
    height=6,
    width=10,
    ax=None,
):
    r"""
    Create a chart with the risk contribution per asset of the portfolio.
    
    Parameters
    ----------
    w : DataFrame
        Weights of a portfolio.
    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 estimate risk contribution. 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.
    color : str, optional
        Color used to plot each asset risk contribution.
        The default is 'tab:blue'.
    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 :  matplotlib axis.
        Returns the Axes object with the plot for further tweaking.
    
    Example
    -------
    ::

        ax = plf.plot_risk_con(w=w2, cov=cov, returns=returns, rm='MSV', 
                               rf=0, alpha=0.01, cmap="tab20", height=6,
                               width=10, ax=None)
        
    .. image:: images/Risk_Con.png
    
    """

    if not isinstance(w, pd.DataFrame):
        raise ValueError("w must be a DataFrame")

    if ax is None:
        ax = plt.gca()
        fig = plt.gcf()
        fig.set_figwidth(width)
        fig.set_figheight(height)

    item = rmeasures.index(rm)
    title = "Risk (" + rm_names[item] + ") Contribution per Asset"
    ax.set_title(title)

    X = w.index.tolist()

    RC = rk.Risk_Contribution(w, cov=cov, returns=returns, rm=rm, rf=rf, alpha=alpha)

    ax.bar(X, RC, alpha=0.7, color=color, edgecolor="black")

    ax.set_xlim(-0.5, len(X) - 0.5)

    ax.set_yticks(ax.get_yticks())
    ax.set_yticklabels(["{:3.5%}".format(x) for x in ax.get_yticks()])
    ax.grid(linestyle=":")

    fig = plt.gcf()
    fig.tight_layout()

    return ax