def print_round_trip_stats(round_trips, hide_pos=False):
    """Print various round-trip statistics. Tries to pretty-print tables
    with HTML output if run inside IPython NB.

    Parameters
    ----------
    round_trips : pd.DataFrame
        DataFrame with one row per round trip trade.
        - See full explanation in round_trips.extract_round_trips

    See also
    --------
    round_trips.gen_round_trip_stats
    """

    stats = gen_round_trip_stats(round_trips)

    print_table(stats['summary'], float_format='{:.2f}'.format,
                name='Summary stats')
    print_table(stats['pnl'], float_format='${:.2f}'.format, name='PnL stats')
    print_table(stats['duration'], float_format='{:.2f}'.format,
                name='Duration stats')
    print_table(stats['returns'] * 100, float_format='{:.2f}%'.format,
                name='Return stats')

    if not hide_pos:
        stats['symbols'].columns = stats['symbols'].columns.map(format_asset)
        print_table(stats['symbols'] * 100,
                    float_format='{:.2f}%'.format, name='Symbol stats')

def
print_round_trip_stats
(
round_trips
,
hide_pos
=
False
)
:
stats
=
gen_round_trip_stats
(
round_trips
)
print_table
(
stats
[
'summary'
]
,
float_format
=
'{:.2f}'
.
format
,
name
=
'Summary stats'
)
print_table
(
stats
[
'pnl'
]
,
float_format
=
'${:.2f}'
.
format
,
name
=
'PnL stats'
)
print_table
(
stats
[
'duration'
]
,
float_format
=
'{:.2f}'
.
format
,
name
=
'Duration stats'
)
print_table
(
stats
[
'returns'
]
*
100
,
float_format
=
'{:.2f}%'
.
format
,
name
=
'Return stats'
)
if
not
hide_pos
:
stats
[
'symbols'
]
.
columns
=
stats
[
'symbols'
]
.
columns
.
map
(
format_asset
)
print_table
(
stats
[
'symbols'
]
*
100
,
float_format
=
'{:.2f}%'
.
format
,
name
=
'Symbol stats'
)

Print various round - trip statistics . Tries to pretty - print tables with HTML output if run inside IPython NB .


def perf_attrib(returns,
                positions,
                factor_returns,
                factor_loadings,
                transactions=None,
                pos_in_dollars=True):
    """
    Attributes the performance of a returns stream to a set of risk factors.

    Preprocesses inputs, and then calls empyrical.perf_attrib. See
    empyrical.perf_attrib for more info.

    Performance attribution determines how much each risk factor, e.g.,
    momentum, the technology sector, etc., contributed to total returns, as
    well as the daily exposure to each of the risk factors. The returns that
    can be attributed to one of the given risk factors are the
    `common_returns`, and the returns that _cannot_ be attributed to a risk
    factor are the `specific_returns`, or the alpha. The common_returns and
    specific_returns summed together will always equal the total returns.

    Parameters
    ----------
    returns : pd.Series
        Returns for each day in the date range.
        - Example:
            2017-01-01   -0.017098
            2017-01-02    0.002683
            2017-01-03   -0.008669

    positions: pd.DataFrame
        Daily holdings (in dollars or percentages), indexed by date.
        Will be converted to percentages if positions are in dollars.
        Short positions show up as cash in the 'cash' column.
        - Examples:
                        AAPL  TLT  XOM  cash
            2017-01-01    34   58   10     0
            2017-01-02    22   77   18     0
            2017-01-03   -15   27   30    15

                            AAPL       TLT       XOM  cash
            2017-01-01  0.333333  0.568627  0.098039   0.0
            2017-01-02  0.188034  0.658120  0.153846   0.0
            2017-01-03  0.208333  0.375000  0.416667   0.0

    factor_returns : pd.DataFrame
        Returns by factor, with date as index and factors as columns
        - Example:
                        momentum  reversal
            2017-01-01  0.002779 -0.005453
            2017-01-02  0.001096  0.010290

    factor_loadings : pd.DataFrame
        Factor loadings for all days in the date range, with date and ticker as
        index, and factors as columns.
        - Example:
                               momentum  reversal
            dt         ticker
            2017-01-01 AAPL   -1.592914  0.852830
                       TLT     0.184864  0.895534
                       XOM     0.993160  1.149353
            2017-01-02 AAPL   -0.140009 -0.524952
                       TLT    -1.066978  0.185435
                       XOM    -1.798401  0.761549

    transactions : pd.DataFrame, optional
        Executed trade volumes and fill prices. Used to check the turnover of
        the algorithm. Default is None, in which case the turnover check is
        skipped.

        - One row per trade.
        - Trades on different names that occur at the
          same time will have identical indicies.
        - Example:
            index                  amount   price    symbol
            2004-01-09 12:18:01    483      324.12   'AAPL'
            2004-01-09 12:18:01    122      83.10    'MSFT'
            2004-01-13 14:12:23    -75      340.43   'AAPL'

    pos_in_dollars : bool
        Flag indicating whether `positions` are in dollars or percentages
        If True, positions are in dollars.

    Returns
    -------
    tuple of (risk_exposures_portfolio, perf_attribution)

    risk_exposures_portfolio : pd.DataFrame
        df indexed by datetime, with factors as columns
        - Example:
                        momentum  reversal
            dt
            2017-01-01 -0.238655  0.077123
            2017-01-02  0.821872  1.520515

    perf_attribution : pd.DataFrame
        df with factors, common returns, and specific returns as columns,
        and datetimes as index
        - Example:
                        momentum  reversal  common_returns  specific_returns
            dt
            2017-01-01  0.249087  0.935925        1.185012          1.185012
            2017-01-02 -0.003194 -0.400786       -0.403980         -0.403980
    """
    (returns,
     positions,
     factor_returns,
     factor_loadings) = _align_and_warn(returns,
                                        positions,
                                        factor_returns,
                                        factor_loadings,
                                        transactions=transactions,
                                        pos_in_dollars=pos_in_dollars)

    # Note that we convert positions to percentages *after* the checks
    # above, since get_turnover() expects positions in dollars.
    positions = _stack_positions(positions, pos_in_dollars=pos_in_dollars)

    return ep.perf_attrib(returns, positions, factor_returns, factor_loadings)

def perf_attrib ( returns , positions , factor_returns , factor_loadings , transactions = None , pos_in_dollars = True ) : ( returns , positions , factor_returns , factor_loadings ) = _align_and_warn ( returns , positions , factor_returns , factor_loadings , transactions = transactions , pos_in_dollars = pos_in_dollars ) positions = _stack_positions ( positions , pos_in_dollars = pos_in_dollars ) return ep . perf_attrib ( returns , positions , factor_returns , factor_loadings )

Attributes the performance of a returns stream to a set of risk factors .


def compute_exposures(positions, factor_loadings, stack_positions=True,
                      pos_in_dollars=True):
    """
    Compute daily risk factor exposures.

    Normalizes positions (if necessary) and calls ep.compute_exposures.
    See empyrical.compute_exposures for more info.

    Parameters
    ----------
    positions: pd.DataFrame or pd.Series
        Daily holdings (in dollars or percentages), indexed by date, OR
        a series of holdings indexed by date and ticker.
        - Examples:
                        AAPL  TLT  XOM  cash
            2017-01-01    34   58   10     0
            2017-01-02    22   77   18     0
            2017-01-03   -15   27   30    15

                            AAPL       TLT       XOM  cash
            2017-01-01  0.333333  0.568627  0.098039   0.0
            2017-01-02  0.188034  0.658120  0.153846   0.0
            2017-01-03  0.208333  0.375000  0.416667   0.0

            dt          ticker
            2017-01-01  AAPL      0.417582
                        TLT       0.010989
                        XOM       0.571429
            2017-01-02  AAPL      0.202381
                        TLT       0.535714
                        XOM       0.261905

    factor_loadings : pd.DataFrame
        Factor loadings for all days in the date range, with date and ticker as
        index, and factors as columns.
        - Example:
                               momentum  reversal
            dt         ticker
            2017-01-01 AAPL   -1.592914  0.852830
                       TLT     0.184864  0.895534
                       XOM     0.993160  1.149353
            2017-01-02 AAPL   -0.140009 -0.524952
                       TLT    -1.066978  0.185435
                       XOM    -1.798401  0.761549

    stack_positions : bool
        Flag indicating whether `positions` should be converted to long format.

    pos_in_dollars : bool
        Flag indicating whether `positions` are in dollars or percentages
        If True, positions are in dollars.

    Returns
    -------
    risk_exposures_portfolio : pd.DataFrame
        df indexed by datetime, with factors as columns.
        - Example:
                        momentum  reversal
            dt
            2017-01-01 -0.238655  0.077123
            2017-01-02  0.821872  1.520515
    """
    if stack_positions:
        positions = _stack_positions(positions, pos_in_dollars=pos_in_dollars)

    return ep.compute_exposures(positions, factor_loadings)

def compute_exposures ( positions , factor_loadings , stack_positions = True , pos_in_dollars = True ) : if stack_positions : positions = _stack_positions ( positions , pos_in_dollars = pos_in_dollars ) return ep . compute_exposures ( positions , factor_loadings )


def create_perf_attrib_stats(perf_attrib, risk_exposures):
    """
    Takes perf attribution data over a period of time and computes annualized
    multifactor alpha, multifactor sharpe, risk exposures.
    """
    summary = OrderedDict()
    total_returns = perf_attrib['total_returns']
    specific_returns = perf_attrib['specific_returns']
    common_returns = perf_attrib['common_returns']

    summary['Annualized Specific Return'] =\
        ep.annual_return(specific_returns)
    summary['Annualized Common Return'] =\
        ep.annual_return(common_returns)
    summary['Annualized Total Return'] =\
        ep.annual_return(total_returns)

    summary['Specific Sharpe Ratio'] =\
        ep.sharpe_ratio(specific_returns)

    summary['Cumulative Specific Return'] =\
        ep.cum_returns_final(specific_returns)
    summary['Cumulative Common Return'] =\
        ep.cum_returns_final(common_returns)
    summary['Total Returns'] =\
        ep.cum_returns_final(total_returns)

    summary = pd.Series(summary, name='')

    annualized_returns_by_factor = [ep.annual_return(perf_attrib[c])
                                    for c in risk_exposures.columns]
    cumulative_returns_by_factor = [ep.cum_returns_final(perf_attrib[c])
                                    for c in risk_exposures.columns]

    risk_exposure_summary = pd.DataFrame(
        data=OrderedDict([
            (
                'Average Risk Factor Exposure',
                risk_exposures.mean(axis='rows')
            ),
            ('Annualized Return', annualized_returns_by_factor),
            ('Cumulative Return', cumulative_returns_by_factor),
        ]),
        index=risk_exposures.columns,
    )

    return summary, risk_exposure_summary

def
create_perf_attrib_stats
(
perf_attrib
,
risk_exposures
)
:
summary
=
OrderedDict
(
)
total_returns
=
perf_attrib
[
'total_returns'
]
specific_returns
=
perf_attrib
[
'specific_returns'
]
common_returns
=
perf_attrib
[
'common_returns'
]
summary
[
'Annualized Specific Return'
]
=
ep
.
annual_return
(
specific_returns
)
summary
[
'Annualized Common Return'
]
=
ep
.
annual_return
(
common_returns
)
summary
[
'Annualized Total Return'
]
=
ep
.
annual_return
(
total_returns
)
summary
[
'Specific Sharpe Ratio'
]
=
ep
.
sharpe_ratio
(
specific_returns
)
summary
[
'Cumulative Specific Return'
]
=
ep
.
cum_returns_final
(
specific_returns
)
summary
[
'Cumulative Common Return'
]
=
ep
.
cum_returns_final
(
common_returns
)
summary
[
'Total Returns'
]
=
ep
.
cum_returns_final
(
total_returns
)
summary
=
pd
.
Series
(
summary
,
name
=
''
)
annualized_returns_by_factor
=
[
ep
.
annual_return
(
perf_attrib
[
c
]
)
for
c
in
risk_exposures
.
columns
]
cumulative_returns_by_factor
=
[
ep
.
cum_returns_final
(
perf_attrib
[
c
]
)
for
c
in
risk_exposures
.
columns
]
risk_exposure_summary
=
pd
.
DataFrame
(
data
=
OrderedDict
(
[
(
'Average Risk Factor Exposure'
,
risk_exposures
.
mean
(
axis
=
'rows'
)
)
,
(
'Annualized Return'
,
annualized_returns_by_factor
)
,
(
'Cumulative Return'
,
cumulative_returns_by_factor
)
,
]
)
,
index
=
risk_exposures
.
columns
,
)
return
summary
,
risk_exposure_summary

Takes perf attribution data over a period of time and computes annualized multifactor alpha multifactor sharpe risk exposures .


def show_perf_attrib_stats(returns,
                           positions,
                           factor_returns,
                           factor_loadings,
                           transactions=None,
                           pos_in_dollars=True):
    """
    Calls `perf_attrib` using inputs, and displays outputs using
    `utils.print_table`.
    """
    risk_exposures, perf_attrib_data = perf_attrib(
        returns,
        positions,
        factor_returns,
        factor_loadings,
        transactions,
        pos_in_dollars=pos_in_dollars,
    )

    perf_attrib_stats, risk_exposure_stats =\
        create_perf_attrib_stats(perf_attrib_data, risk_exposures)

    percentage_formatter = '{:.2%}'.format
    float_formatter = '{:.2f}'.format

    summary_stats = perf_attrib_stats.loc[['Annualized Specific Return',
                                           'Annualized Common Return',
                                           'Annualized Total Return',
                                           'Specific Sharpe Ratio']]

    # Format return rows in summary stats table as percentages.
    for col_name in (
        'Annualized Specific Return',
        'Annualized Common Return',
        'Annualized Total Return',
    ):
        summary_stats[col_name] = percentage_formatter(summary_stats[col_name])

    # Display sharpe to two decimal places.
    summary_stats['Specific Sharpe Ratio'] = float_formatter(
        summary_stats['Specific Sharpe Ratio']
    )

    print_table(summary_stats, name='Summary Statistics')

    print_table(
        risk_exposure_stats,
        name='Exposures Summary',
        # In exposures table, format exposure column to 2 decimal places, and
        # return columns  as percentages.
        formatters={
            'Average Risk Factor Exposure': float_formatter,
            'Annualized Return': percentage_formatter,
            'Cumulative Return': percentage_formatter,
        },
    )

def
show_perf_attrib_stats
(
returns
,
positions
,
factor_returns
,
factor_loadings
,
transactions
=
,
pos_in_dollars
=
True
)
:
risk_exposures
,
perf_attrib_data
=
perf_attrib
(
returns
,
positions
,
factor_returns
,
factor_loadings
,
transactions
,
pos_in_dollars
=
pos_in_dollars
,
)
perf_attrib_stats
,
risk_exposure_stats
=
create_perf_attrib_stats
(
perf_attrib_data
,
risk_exposures
)
percentage_formatter
=
'{:.2%}'
.
format
float_formatter
=
'{:.2f}'
.
format
summary_stats
=
perf_attrib_stats
.
loc
[
[
'Annualized Specific Return'
,
'Annualized Common Return'
,
'Annualized Total Return'
,
'Specific Sharpe Ratio'
]
]
for
col_name
in
(
'Annualized Specific Return'
,
'Annualized Common Return'
,
'Annualized Total Return'
,
)
:
summary_stats
[
col_name
]
=
percentage_formatter
(
summary_stats
[
col_name
]
)
summary_stats
[
'Specific Sharpe Ratio'
]
=
float_formatter
(
summary_stats
[
'Specific Sharpe Ratio'
]
)
print_table
(
summary_stats
,
name
=
'Summary Statistics'
)
print_table
(
risk_exposure_stats
,
name
=
'Exposures Summary'
,
formatters
=
{
'Average Risk Factor Exposure'
:
float_formatter
,
'Annualized Return'
:
percentage_formatter
,
'Cumulative Return'
:
percentage_formatter
,
}
,
)

Calls perf_attrib using inputs and displays outputs using utils . print_table .


def plot_returns(perf_attrib_data, cost=None, ax=None):
    """
    Plot total, specific, and common returns.

    Parameters
    ----------
    perf_attrib_data : pd.DataFrame
        df with factors, common returns, and specific returns as columns,
        and datetimes as index. Assumes the `total_returns` column is NOT
        cost adjusted.
        - Example:
                        momentum  reversal  common_returns  specific_returns
            dt
            2017-01-01  0.249087  0.935925        1.185012          1.185012
            2017-01-02 -0.003194 -0.400786       -0.403980         -0.403980

    cost : pd.Series, optional
        if present, gets subtracted from `perf_attrib_data['total_returns']`,
        and gets plotted separately

    ax :  matplotlib.axes.Axes
        axes on which plots are made. if None, current axes will be used

    Returns
    -------
    ax :  matplotlib.axes.Axes
    """

    if ax is None:
        ax = plt.gca()

    returns = perf_attrib_data['total_returns']
    total_returns_label = 'Total returns'

    cumulative_returns_less_costs = _cumulative_returns_less_costs(
        returns,
        cost
    )
    if cost is not None:
        total_returns_label += ' (adjusted)'

    specific_returns = perf_attrib_data['specific_returns']
    common_returns = perf_attrib_data['common_returns']

    ax.plot(cumulative_returns_less_costs, color='b',
            label=total_returns_label)
    ax.plot(ep.cum_returns(specific_returns), color='g',
            label='Cumulative specific returns')
    ax.plot(ep.cum_returns(common_returns), color='r',
            label='Cumulative common returns')

    if cost is not None:
        ax.plot(-ep.cum_returns(cost), color='k',
                label='Cumulative cost spent')

    ax.set_title('Time series of cumulative returns')
    ax.set_ylabel('Returns')

    configure_legend(ax)

    return ax

def
plot_returns
(
perf_attrib_data
,
cost
=
,
ax
=
)
:
if
ax
is
:
ax
=
plt
.
gca
(
)
returns
=
perf_attrib_data
[
'total_returns'
]
total_returns_label
=
'Total returns'
cumulative_returns_less_costs
=
_cumulative_returns_less_costs
(
returns
,
cost
)
if
cost
is
not
:
total_returns_label
+=
' (adjusted)'
specific_returns
=
perf_attrib_data
[
'specific_returns'
]
common_returns
=
perf_attrib_data
[
'common_returns'
]
ax
.
plot
(
cumulative_returns_less_costs
,
color
=
'b'
,
label
=
total_returns_label
)
ax
.
plot
(
ep
.
cum_returns
(
specific_returns
)
,
color
=
'g'
,
label
=
'Cumulative specific returns'
)
ax
.
plot
(
ep
.
cum_returns
(
common_returns
)
,
color
=
'r'
,
label
=
'Cumulative common returns'
)
if
cost
is
not
:
ax
.
plot
(
ep
.
cum_returns
(
cost
)
,
color
=
'k'
,
label
=
'Cumulative cost spent'
)
ax
.
set_title
(
'Time series of cumulative returns'
)
ax
.
set_ylabel
(
'Returns'
)
configure_legend
(
ax
)
return
ax

Plot total specific and common returns .


def plot_factor_contribution_to_perf(
        perf_attrib_data,
        ax=None,
        title='Cumulative common returns attribution',
):
    """
    Plot each factor's contribution to performance.

    Parameters
    ----------
    perf_attrib_data : pd.DataFrame
        df with factors, common returns, and specific returns as columns,
        and datetimes as index
        - Example:
                        momentum  reversal  common_returns  specific_returns
            dt
            2017-01-01  0.249087  0.935925        1.185012          1.185012
            2017-01-02 -0.003194 -0.400786       -0.403980         -0.403980

    ax :  matplotlib.axes.Axes
        axes on which plots are made. if None, current axes will be used

    title : str, optional
        title of plot

    Returns
    -------
    ax :  matplotlib.axes.Axes
    """
    if ax is None:
        ax = plt.gca()

    factors_to_plot = perf_attrib_data.drop(
        ['total_returns', 'common_returns'], axis='columns', errors='ignore'
    )

    factors_cumulative = pd.DataFrame()
    for factor in factors_to_plot:
        factors_cumulative[factor] = ep.cum_returns(factors_to_plot[factor])

    for col in factors_cumulative:
        ax.plot(factors_cumulative[col])

    ax.axhline(0, color='k')
    configure_legend(ax, change_colors=True)

    ax.set_ylabel('Cumulative returns by factor')
    ax.set_title(title)

    return ax

def
plot_factor_contribution_to_perf
(
perf_attrib_data
,
ax
=
,
title
=
'Cumulative common returns attribution'
,
)
:
if
ax
is
:
ax
=
plt
.
gca
(
)
factors_to_plot
=
perf_attrib_data
.
drop
(
[
'total_returns'
,
'common_returns'
]
,
axis
=
'columns'
,
errors
=
'ignore'
)
factors_cumulative
=
pd
.
DataFrame
(
)
for
factor
in
factors_to_plot
:
factors_cumulative
[
factor
]
=
ep
.
cum_returns
(
factors_to_plot
[
factor
]
)
for
col
in
factors_cumulative
:
ax
.
plot
(
factors_cumulative
[
col
]
)
ax
.
axhline
(
0
,
color
=
'k'
)
configure_legend
(
ax
,
change_colors
=
True
)
ax
.
set_ylabel
(
'Cumulative returns by factor'
)
ax
.
set_title
(
title
)
return
ax

Plot each factor s contribution to performance .


def _stack_positions(positions, pos_in_dollars=True):
    """
    Convert positions to percentages if necessary, and change them
    to long format.

    Parameters
    ----------
    positions: pd.DataFrame
        Daily holdings (in dollars or percentages), indexed by date.
        Will be converted to percentages if positions are in dollars.
        Short positions show up as cash in the 'cash' column.

    pos_in_dollars : bool
        Flag indicating whether `positions` are in dollars or percentages
        If True, positions are in dollars.
    """
    if pos_in_dollars:
        # convert holdings to percentages
        positions = get_percent_alloc(positions)

    # remove cash after normalizing positions
    positions = positions.drop('cash', axis='columns')

    # convert positions to long format
    positions = positions.stack()
    positions.index = positions.index.set_names(['dt', 'ticker'])

    return positions

def _stack_positions ( positions , pos_in_dollars = True ) : if pos_in_dollars : positions = get_percent_alloc ( positions ) positions = positions . drop ( 'cash' , axis = 'columns' ) positions = positions . stack ( ) positions . index = positions . index . set_names ( [ 'dt' , 'ticker' ] ) return positions

Convert positions to percentages if necessary and change them to long format .


def _cumulative_returns_less_costs(returns, costs):
    """
    Compute cumulative returns, less costs.
    """
    if costs is None:
        return ep.cum_returns(returns)
    return ep.cum_returns(returns - costs)

def _cumulative_returns_less_costs ( returns , costs ) : if costs is None : return ep . cum_returns ( returns ) return ep . cum_returns ( returns - costs )


def format_asset(asset):
    """
    If zipline asset objects are used, we want to print them out prettily
    within the tear sheet. This function should only be applied directly
    before displaying.
    """

    try:
        import zipline.assets
    except ImportError:
        return asset

    if isinstance(asset, zipline.assets.Asset):
        return asset.symbol
    else:
        return asset

def format_asset ( asset ) : try : import zipline . assets except ImportError : return asset if isinstance ( asset , zipline . assets . Asset ) : return asset . symbol else : return asset

If zipline asset objects are used we want to print them out prettily within the tear sheet . This function should only be applied directly before displaying .


def vectorize(func):
    """
    Decorator so that functions can be written to work on Series but
    may still be called with DataFrames.
    """

    def wrapper(df, *args, **kwargs):
        if df.ndim == 1:
            return func(df, *args, **kwargs)
        elif df.ndim == 2:
            return df.apply(func, *args, **kwargs)

    return wrapper

def vectorize ( func ) : def wrapper ( df , * args , ** kwargs ) : if df . ndim == 1 : return func ( df , * args , ** kwargs ) elif df . ndim == 2 : return df . apply ( func , * args , ** kwargs ) return wrapper

Decorator so that functions can be written to work on Series but may still be called with DataFrames .


def print_table(table,
                name=None,
                float_format=None,
                formatters=None,
                header_rows=None):
    """
    Pretty print a pandas DataFrame.

    Uses HTML output if running inside Jupyter Notebook, otherwise
    formatted text output.

    Parameters
    ----------
    table : pandas.Series or pandas.DataFrame
        Table to pretty-print.
    name : str, optional
        Table name to display in upper left corner.
    float_format : function, optional
        Formatter to use for displaying table elements, passed as the
        `float_format` arg to pd.Dataframe.to_html.
        E.g. `'{0:.2%}'.format` for displaying 100 as '100.00%'.
    formatters : list or dict, optional
        Formatters to use by column, passed as the `formatters` arg to
        pd.Dataframe.to_html.
    header_rows : dict, optional
        Extra rows to display at the top of the table.
    """

    if isinstance(table, pd.Series):
        table = pd.DataFrame(table)

    if name is not None:
        table.columns.name = name

    html = table.to_html(float_format=float_format, formatters=formatters)

    if header_rows is not None:
        # Count the number of columns for the text to span
        n_cols = html.split('
')[1].split('
')[0].count('')

        # Generate the HTML for the extra rows
        rows = ''
        for name, value in header_rows.items():
            rows += ('\n
%s	' +
                     '%s
') % (name, n_cols, value)

        # Inject the new HTML
        html = html.replace('
', '
' + rows)

    display(HTML(html))


def detect_intraday(positions, transactions, threshold=0.25):
    """
    Attempt to detect an intraday strategy. Get the number of
    positions held at the end of the day, and divide that by the
    number of unique stocks transacted every day. If the average quotient
    is below a threshold, then an intraday strategy is detected.

    Parameters
    ----------
    positions : pd.DataFrame
        Daily net position values.
         - See full explanation in create_full_tear_sheet.
    transactions : pd.DataFrame
        Prices and amounts of executed trades. One row per trade.
         - See full explanation in create_full_tear_sheet.

    Returns
    -------
    boolean
        True if an intraday strategy is detected.
    """

    daily_txn = transactions.copy()
    daily_txn.index = daily_txn.index.date
    txn_count = daily_txn.groupby(level=0).symbol.nunique().sum()
    daily_pos = positions.drop('cash', axis=1).replace(0, np.nan)
    return daily_pos.count(axis=1).sum() / txn_count < threshold

def detect_intraday ( positions , transactions , threshold = 0.25 ) : daily_txn = transactions . copy ( ) daily_txn . index = daily_txn . index . date txn_count = daily_txn . groupby ( level = 0 ) . symbol . nunique ( ) . sum ( ) daily_pos = positions . drop ( 'cash' , axis = 1 ) . replace ( 0 , np . nan ) return daily_pos . count ( axis = 1 ) . sum ( ) / txn_count < threshold

Attempt to detect an intraday strategy . Get the number of positions held at the end of the day and divide that by the number of unique stocks transacted every day . If the average quotient is below a threshold then an intraday strategy is detected .


def check_intraday(estimate, returns, positions, transactions):
    """
    Logic for checking if a strategy is intraday and processing it.

    Parameters
    ----------
    estimate: boolean or str, optional
        Approximate returns for intraday strategies.
        See description in tears.create_full_tear_sheet.
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in create_full_tear_sheet.
    positions : pd.DataFrame
        Daily net position values.
         - See full explanation in create_full_tear_sheet.
    transactions : pd.DataFrame
        Prices and amounts of executed trades. One row per trade.
         - See full explanation in create_full_tear_sheet.

    Returns
    -------
    pd.DataFrame
        Daily net position values, adjusted for intraday movement.
    """

    if estimate == 'infer':
        if positions is not None and transactions is not None:
            if detect_intraday(positions, transactions):
                warnings.warn('Detected intraday strategy; inferring positi' +
                              'ons from transactions. Set estimate_intraday' +
                              '=False to disable.')
                return estimate_intraday(returns, positions, transactions)
            else:
                return positions
        else:
            return positions

    elif estimate:
        if positions is not None and transactions is not None:
            return estimate_intraday(returns, positions, transactions)
        else:
            raise ValueError('Positions and txns needed to estimate intraday')
    else:
        return positions

Logic for checking if a strategy is intraday and processing it .


def estimate_intraday(returns, positions, transactions, EOD_hour=23):
    """
    Intraday strategies will often not hold positions at the day end.
    This attempts to find the point in the day that best represents
    the activity of the strategy on that day, and effectively resamples
    the end-of-day positions with the positions at this point of day.
    The point of day is found by detecting when our exposure in the
    market is at its maximum point. Note that this is an estimate.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in create_full_tear_sheet.
    positions : pd.DataFrame
        Daily net position values.
         - See full explanation in create_full_tear_sheet.
    transactions : pd.DataFrame
        Prices and amounts of executed trades. One row per trade.
         - See full explanation in create_full_tear_sheet.

    Returns
    -------
    pd.DataFrame
        Daily net position values, resampled for intraday behavior.
    """

    # Construct DataFrame of transaction amounts
    txn_val = transactions.copy()
    txn_val.index.names = ['date']
    txn_val['value'] = txn_val.amount * txn_val.price
    txn_val = txn_val.reset_index().pivot_table(
        index='date', values='value',
        columns='symbol').replace(np.nan, 0)

    # Cumulate transaction amounts each day
    txn_val['date'] = txn_val.index.date
    txn_val = txn_val.groupby('date').cumsum()

    # Calculate exposure, then take peak of exposure every day
    txn_val['exposure'] = txn_val.abs().sum(axis=1)
    condition = (txn_val['exposure'] == txn_val.groupby(
        pd.TimeGrouper('24H'))['exposure'].transform(max))
    txn_val = txn_val[condition].drop('exposure', axis=1)

    # Compute cash delta
    txn_val['cash'] = -txn_val.sum(axis=1)

    # Shift EOD positions to positions at start of next trading day
    positions_shifted = positions.copy().shift(1).fillna(0)
    starting_capital = positions.iloc[0].sum() / (1 + returns[0])
    positions_shifted.cash[0] = starting_capital

    # Format and add start positions to intraday position changes
    txn_val.index = txn_val.index.normalize()
    corrected_positions = positions_shifted.add(txn_val, fill_value=0)
    corrected_positions.index.name = 'period_close'
    corrected_positions.columns.name = 'sid'

    return corrected_positions

def estimate_intraday ( returns , positions , transactions , EOD_hour = 23 ) : txn_val = transactions . copy ( ) txn_val . index . names = [ 'date' ] txn_val [ 'value' ] = txn_val . amount * txn_val . price txn_val = txn_val . reset_index ( ) . pivot_table ( index = 'date' , values = 'value' , columns = 'symbol' ) . replace ( np . nan , 0 ) txn_val [ 'date' ] = txn_val . index . date txn_val = txn_val . groupby ( 'date' ) . cumsum ( ) txn_val [ 'exposure' ] = txn_val . abs ( ) . sum ( axis = 1 ) condition = ( txn_val [ 'exposure' ] == txn_val . groupby ( pd . TimeGrouper ( '24H' ) ) [ 'exposure' ] . transform ( max ) ) txn_val = txn_val [ condition ] . drop ( 'exposure' , axis = 1 ) txn_val [ 'cash' ] = - txn_val . sum ( axis = 1 ) positions_shifted = positions . copy ( ) . shift ( 1 ) . fillna ( 0 ) starting_capital = positions . iloc [ 0 ] . sum ( ) / ( 1 + returns [ 0 ] ) positions_shifted . cash [ 0 ] = starting_capital txn_val . index = txn_val . index . normalize ( ) corrected_positions = positions_shifted . add ( txn_val , fill_value = 0 ) corrected_positions . index . name = 'period_close' corrected_positions . columns . name = 'sid' return corrected_positions

Intraday strategies will often not hold positions at the day end . This attempts to find the point in the day that best represents the activity of the strategy on that day and effectively resamples the end - of - day positions with the positions at this point of day . The point of day is found by detecting when our exposure in the market is at its maximum point . Note that this is an estimate .


def clip_returns_to_benchmark(rets, benchmark_rets):
    """
    Drop entries from rets so that the start and end dates of rets match those
    of benchmark_rets.

    Parameters
    ----------
    rets : pd.Series
        Daily returns of the strategy, noncumulative.
         - See pf.tears.create_full_tear_sheet for more details

    benchmark_rets : pd.Series
        Daily returns of the benchmark, noncumulative.

    Returns
    -------
    clipped_rets : pd.Series
        Daily noncumulative returns with index clipped to match that of
        benchmark returns.
    """

    if (rets.index[0] < benchmark_rets.index[0]) \
            or (rets.index[-1] > benchmark_rets.index[-1]):
        clipped_rets = rets[benchmark_rets.index]
    else:
        clipped_rets = rets

    return clipped_rets

def clip_returns_to_benchmark ( rets , benchmark_rets ) : if ( rets . index [ 0 ] < benchmark_rets . index [ 0 ] ) or ( rets . index [ - 1 ] > benchmark_rets . index [ - 1 ] ) : clipped_rets = rets [ benchmark_rets . index ] else : clipped_rets = rets return clipped_rets

Drop entries from rets so that the start and end dates of rets match those of benchmark_rets .


def to_utc(df):
    """
    For use in tests; applied UTC timestamp to DataFrame.
    """

    try:
        df.index = df.index.tz_localize('UTC')
    except TypeError:
        df.index = df.index.tz_convert('UTC')

    return df

def to_utc ( df ) : try : df . index = df . index . tz_localize ( 'UTC' ) except TypeError : df . index = df . index . tz_convert ( 'UTC' ) return df

For use in tests ; applied UTC timestamp to DataFrame .


def get_symbol_rets(symbol, start=None, end=None):
    """
    Calls the currently registered 'returns_func'

    Parameters
    ----------
    symbol : object
        An identifier for the asset whose return
        series is desired.
        e.g. ticker symbol or database ID
    start : date, optional
        Earliest date to fetch data for.
        Defaults to earliest date available.
    end : date, optional
        Latest date to fetch data for.
        Defaults to latest date available.

    Returns
    -------
    pandas.Series
        Returned by the current 'returns_func'
    """

    return SETTINGS['returns_func'](symbol,
                                    start=start,
                                    end=end)

def get_symbol_rets ( symbol , start = None , end = None ) : return SETTINGS [ 'returns_func' ] ( symbol , start = start , end = end )

Calls the currently registered returns_func


def sample_colormap(cmap_name, n_samples):
    """
    Sample a colormap from matplotlib
    """
    colors = []
    colormap = cm.cmap_d[cmap_name]
    for i in np.linspace(0, 1, n_samples):
        colors.append(colormap(i))

    return colors

def sample_colormap ( cmap_name , n_samples ) : colors = [ ] colormap = cm . cmap_d [ cmap_name ] for i in np . linspace ( 0 , 1 , n_samples ) : colors . append ( colormap ( i ) ) return colors


def customize(func):
    """
    Decorator to set plotting context and axes style during function call.
    """
    @wraps(func)
    def call_w_context(*args, **kwargs):
        set_context = kwargs.pop('set_context', True)
        if set_context:
            with plotting_context(), axes_style():
                return func(*args, **kwargs)
        else:
            return func(*args, **kwargs)
    return call_w_context

def customize ( func ) : @ wraps ( func ) def call_w_context ( * args , ** kwargs ) : set_context = kwargs . pop ( 'set_context' , True ) if set_context : with plotting_context ( ) , axes_style ( ) : return func ( * args , ** kwargs ) else : return func ( * args , ** kwargs ) return call_w_context

Decorator to set plotting context and axes style during function call .


def plotting_context(context='notebook', font_scale=1.5, rc=None):
    """
    Create pyfolio default plotting style context.

    Under the hood, calls and returns seaborn.plotting_context() with
    some custom settings. Usually you would use in a with-context.

    Parameters
    ----------
    context : str, optional
        Name of seaborn context.
    font_scale : float, optional
        Scale font by factor font_scale.
    rc : dict, optional
        Config flags.
        By default, {'lines.linewidth': 1.5}
        is being used and will be added to any
        rc passed in, unless explicitly overriden.

    Returns
    -------
    seaborn plotting context

    Example
    -------
    >>> with pyfolio.plotting.plotting_context(font_scale=2):
    >>>    pyfolio.create_full_tear_sheet(..., set_context=False)

    See also
    --------
    For more information, see seaborn.plotting_context().

    """
    if rc is None:
        rc = {}

    rc_default = {'lines.linewidth': 1.5}

    # Add defaults if they do not exist
    for name, val in rc_default.items():
        rc.setdefault(name, val)

    return sns.plotting_context(context=context, font_scale=font_scale, rc=rc)

def plotting_context ( context = 'notebook' , font_scale = 1.5 , rc = None ) : if rc is None : rc = { } rc_default = { 'lines.linewidth' : 1.5 } for name , val in rc_default . items ( ) : rc . setdefault ( name , val ) return sns . plotting_context ( context = context , font_scale = font_scale , rc = rc )

Create pyfolio default plotting style context .


def axes_style(style='darkgrid', rc=None):
    """
    Create pyfolio default axes style context.

    Under the hood, calls and returns seaborn.axes_style() with
    some custom settings. Usually you would use in a with-context.

    Parameters
    ----------
    style : str, optional
        Name of seaborn style.
    rc : dict, optional
        Config flags.

    Returns
    -------
    seaborn plotting context

    Example
    -------
    >>> with pyfolio.plotting.axes_style(style='whitegrid'):
    >>>    pyfolio.create_full_tear_sheet(..., set_context=False)

    See also
    --------
    For more information, see seaborn.plotting_context().

    """
    if rc is None:
        rc = {}

    rc_default = {}

    # Add defaults if they do not exist
    for name, val in rc_default.items():
        rc.setdefault(name, val)

    return sns.axes_style(style=style, rc=rc)

def axes_style ( style = 'darkgrid' , rc = None ) : if rc is None : rc = { } rc_default = { } for name , val in rc_default . items ( ) : rc . setdefault ( name , val ) return sns . axes_style ( style = style , rc = rc )

Create pyfolio default axes style context .


def plot_monthly_returns_heatmap(returns, ax=None, **kwargs):
    """
    Plots a heatmap of returns by month.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in tears.create_full_tear_sheet.
    ax : matplotlib.Axes, optional
        Axes upon which to plot.
    **kwargs, optional
        Passed to seaborn plotting function.

    Returns
    -------
    ax : matplotlib.Axes
        The axes that were plotted on.
    """

    if ax is None:
        ax = plt.gca()

    monthly_ret_table = ep.aggregate_returns(returns, 'monthly')
    monthly_ret_table = monthly_ret_table.unstack().round(3)

    sns.heatmap(
        monthly_ret_table.fillna(0) *
        100.0,
        annot=True,
        annot_kws={"size": 9},
        alpha=1.0,
        center=0.0,
        cbar=False,
        cmap=matplotlib.cm.RdYlGn,
        ax=ax, **kwargs)
    ax.set_ylabel('Year')
    ax.set_xlabel('Month')
    ax.set_title("Monthly returns (%)")
    return ax

def
plot_monthly_returns_heatmap
(
returns
,
ax
=
,
**
kwargs
)
:
if
ax
is
:
ax
=
plt
.
gca
(
)
monthly_ret_table
=
ep
.
aggregate_returns
(
returns
,
'monthly'
)
monthly_ret_table
=
monthly_ret_table
.
unstack
(
)
.
round
(
3
)
sns
.
heatmap
(
monthly_ret_table
.
fillna
(
0
)
*
100.0
,
annot
=
True
,
annot_kws
=
{
"size"
:
9
}
,
alpha
=
1.0
,
center
=
0.0
,
cbar
=
False
,
cmap
=
matplotlib
.
cm
.
RdYlGn
,
ax
=
ax
,
**
kwargs
)
ax
.
set_ylabel
(
'Year'
)
ax
.
set_xlabel
(
'Month'
)
ax
.
set_title
(
"Monthly returns (%)"
)
return
ax


def plot_annual_returns(returns, ax=None, **kwargs):
    """
    Plots a bar graph of returns by year.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in tears.create_full_tear_sheet.
    ax : matplotlib.Axes, optional
        Axes upon which to plot.
    **kwargs, optional
        Passed to plotting function.

    Returns
    -------
    ax : matplotlib.Axes
        The axes that were plotted on.
    """

    if ax is None:
        ax = plt.gca()

    x_axis_formatter = FuncFormatter(utils.percentage)
    ax.xaxis.set_major_formatter(FuncFormatter(x_axis_formatter))
    ax.tick_params(axis='x', which='major')

    ann_ret_df = pd.DataFrame(
        ep.aggregate_returns(
            returns,
            'yearly'))

    ax.axvline(
        100 *
        ann_ret_df.values.mean(),
        color='steelblue',
        linestyle='--',
        lw=4,
        alpha=0.7)
    (100 * ann_ret_df.sort_index(ascending=False)
     ).plot(ax=ax, kind='barh', alpha=0.70, **kwargs)
    ax.axvline(0.0, color='black', linestyle='-', lw=3)

    ax.set_ylabel('Year')
    ax.set_xlabel('Returns')
    ax.set_title("Annual returns")
    ax.legend(['Mean'], frameon=True, framealpha=0.5)
    return ax

def
plot_annual_returns
(
returns
,
ax
=
,
**
kwargs
)
:
if
ax
is
:
ax
=
plt
.
gca
(
)
x_axis_formatter
=
FuncFormatter
(
utils
.
percentage
)
ax
.
xaxis
.
set_major_formatter
(
FuncFormatter
(
x_axis_formatter
)
)
ax
.
tick_params
(
axis
=
'x'
,
which
=
'major'
)
ann_ret_df
=
pd
.
DataFrame
(
ep
.
aggregate_returns
(
returns
,
'yearly'
)
)
ax
.
axvline
(
100
*
ann_ret_df
.
values
.
mean
(
)
,
color
=
'steelblue'
,
linestyle
=
'--'
,
lw
=
4
,
alpha
=
0.7
)
(
100
*
ann_ret_df
.
sort_index
(
ascending
=
False
)
)
.
plot
(
ax
=
ax
,
kind
=
'barh'
,
alpha
=
0.70
,
**
kwargs
)
ax
.
axvline
(
0.0
,
color
=
'black'
,
linestyle
=
'-'
,
lw
=
3
)
ax
.
set_ylabel
(
'Year'
)
ax
.
set_xlabel
(
'Returns'
)
ax
.
set_title
(
"Annual returns"
)
ax
.
legend
(
[
'Mean'
]
,
frameon
=
True
,
framealpha
=
0.5
)
return
ax


def plot_monthly_returns_dist(returns, ax=None, **kwargs):
    """
    Plots a distribution of monthly returns.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in tears.create_full_tear_sheet.
    ax : matplotlib.Axes, optional
        Axes upon which to plot.
    **kwargs, optional
        Passed to plotting function.

    Returns
    -------
    ax : matplotlib.Axes
        The axes that were plotted on.
    """

    if ax is None:
        ax = plt.gca()

    x_axis_formatter = FuncFormatter(utils.percentage)
    ax.xaxis.set_major_formatter(FuncFormatter(x_axis_formatter))
    ax.tick_params(axis='x', which='major')

    monthly_ret_table = ep.aggregate_returns(returns, 'monthly')

    ax.hist(
        100 * monthly_ret_table,
        color='orangered',
        alpha=0.80,
        bins=20,
        **kwargs)

    ax.axvline(
        100 * monthly_ret_table.mean(),
        color='gold',
        linestyle='--',
        lw=4,
        alpha=1.0)

    ax.axvline(0.0, color='black', linestyle='-', lw=3, alpha=0.75)
    ax.legend(['Mean'], frameon=True, framealpha=0.5)
    ax.set_ylabel('Number of months')
    ax.set_xlabel('Returns')
    ax.set_title("Distribution of monthly returns")
    return ax

def
plot_monthly_returns_dist
(
returns
,
ax
=
,
**
kwargs
)
:
if
ax
is
:
ax
=
plt
.
gca
(
)
x_axis_formatter
=
FuncFormatter
(
utils
.
percentage
)
ax
.
xaxis
.
set_major_formatter
(
FuncFormatter
(
x_axis_formatter
)
)
ax
.
tick_params
(
axis
=
'x'
,
which
=
'major'
)
monthly_ret_table
=
ep
.
aggregate_returns
(
returns
,
'monthly'
)
ax
.
hist
(
100
*
monthly_ret_table
,
color
=
'orangered'
,
alpha
=
0.80
,
bins
=
20
,
**
kwargs
)
ax
.
axvline
(
100
*
monthly_ret_table
.
mean
(
)
,
color
=
'gold'
,
linestyle
=
'--'
,
lw
=
4
,
alpha
=
1.0
)
ax
.
axvline
(
0.0
,
color
=
'black'
,
linestyle
=
'-'
,
lw
=
3
,
alpha
=
0.75
)
ax
.
legend
(
[
'Mean'
]
,
frameon
=
True
,
framealpha
=
0.5
)
ax
.
set_ylabel
(
'Number of months'
)
ax
.
set_xlabel
(
'Returns'
)
ax
.
set_title
(
"Distribution of monthly returns"
)
return
ax

Plots a distribution of monthly returns .


def plot_holdings(returns, positions, legend_loc='best', ax=None, **kwargs):
    """
    Plots total amount of stocks with an active position, either short
    or long. Displays daily total, daily average per month, and
    all-time daily average.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in tears.create_full_tear_sheet.
    positions : pd.DataFrame, optional
        Daily net position values.
         - See full explanation in tears.create_full_tear_sheet.
    legend_loc : matplotlib.loc, optional
        The location of the legend on the plot.
    ax : matplotlib.Axes, optional
        Axes upon which to plot.
    **kwargs, optional
        Passed to plotting function.

    Returns
    -------
    ax : matplotlib.Axes
        The axes that were plotted on.
    """

    if ax is None:
        ax = plt.gca()

    positions = positions.copy().drop('cash', axis='columns')
    df_holdings = positions.replace(0, np.nan).count(axis=1)
    df_holdings_by_month = df_holdings.resample('1M').mean()
    df_holdings.plot(color='steelblue', alpha=0.6, lw=0.5, ax=ax, **kwargs)
    df_holdings_by_month.plot(
        color='orangered',
        lw=2,
        ax=ax,
        **kwargs)
    ax.axhline(
        df_holdings.values.mean(),
        color='steelblue',
        ls='--',
        lw=3)

    ax.set_xlim((returns.index[0], returns.index[-1]))

    leg = ax.legend(['Daily holdings',
                     'Average daily holdings, by month',
                     'Average daily holdings, overall'],
                    loc=legend_loc, frameon=True,
                    framealpha=0.5)
    leg.get_frame().set_edgecolor('black')

    ax.set_title('Total holdings')
    ax.set_ylabel('Holdings')
    ax.set_xlabel('')
    return ax

def
plot_holdings
(
returns
,
positions
,
legend_loc
=
'best'
,
ax
=
,
**
kwargs
)
:
if
ax
is
:
ax
=
plt
.
gca
(
)
positions
=
positions
.
copy
(
)
.
drop
(
'cash'
,
axis
=
'columns'
)
df_holdings
=
positions
.
replace
(
0
,
np
.
)
.
count
(
axis
=
1
)
df_holdings_by_month
=
df_holdings
.
resample
(
'1M'
)
.
mean
(
)
df_holdings
.
plot
(
color
=
'steelblue'
,
alpha
=
0.6
,
lw
=
0.5
,
ax
=
ax
,
**
kwargs
)
df_holdings_by_month
.
plot
(
color
=
'orangered'
,
lw
=
2
,
ax
=
ax
,
**
kwargs
)
ax
.
axhline
(
df_holdings
.
values
.
mean
(
)
,
color
=
'steelblue'
,
ls
=
'--'
,
lw
=
3
)
ax
.
set_xlim
(
(
returns
.
index
[
0
]
,
returns
.
index
[
1
]
)
)
leg
=
ax
.
legend
(
[
'Daily holdings'
,
'Average daily holdings, by month'
,
'Average daily holdings, overall'
]
,
loc
=
legend_loc
,
frameon
=
True
,
framealpha
=
0.5
)
leg
.
get_frame
(
)
.
set_edgecolor
(
'black'
)
ax
.
set_title
(
'Total holdings'
)
ax
.
set_ylabel
(
'Holdings'
)
ax
.
set_xlabel
(
''
)
return
ax

Plots total amount of stocks with an active position either short or long . Displays daily total daily average per month and all - time daily average .


def plot_long_short_holdings(returns, positions,
                             legend_loc='upper left', ax=None, **kwargs):
    """
    Plots total amount of stocks with an active position, breaking out
    short and long into transparent filled regions.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in tears.create_full_tear_sheet.
    positions : pd.DataFrame, optional
        Daily net position values.
         - See full explanation in tears.create_full_tear_sheet.
    legend_loc : matplotlib.loc, optional
        The location of the legend on the plot.
    ax : matplotlib.Axes, optional
        Axes upon which to plot.
    **kwargs, optional
        Passed to plotting function.

    Returns
    -------
    ax : matplotlib.Axes
        The axes that were plotted on.

    """

    if ax is None:
        ax = plt.gca()

    positions = positions.drop('cash', axis='columns')
    positions = positions.replace(0, np.nan)
    df_longs = positions[positions > 0].count(axis=1)
    df_shorts = positions[positions < 0].count(axis=1)
    lf = ax.fill_between(df_longs.index, 0, df_longs.values,
                         color='g', alpha=0.5, lw=2.0)
    sf = ax.fill_between(df_shorts.index, 0, df_shorts.values,
                         color='r', alpha=0.5, lw=2.0)

    bf = patches.Rectangle([0, 0], 1, 1, color='darkgoldenrod')
    leg = ax.legend([lf, sf, bf],
                    ['Long (max: %s, min: %s)' % (df_longs.max(),
                                                  df_longs.min()),
                     'Short (max: %s, min: %s)' % (df_shorts.max(),
                                                   df_shorts.min()),
                     'Overlap'], loc=legend_loc, frameon=True,
                    framealpha=0.5)
    leg.get_frame().set_edgecolor('black')

    ax.set_xlim((returns.index[0], returns.index[-1]))
    ax.set_title('Long and short holdings')
    ax.set_ylabel('Holdings')
    ax.set_xlabel('')
    return ax

def
plot_long_short_holdings
(
returns
,
positions
,
legend_loc
=
'upper left'
,
ax
=
,
**
kwargs
)
:
if
ax
is
:
ax
=
plt
.
gca
(
)
positions
=
positions
.
drop
(
'cash'
,
axis
=
'columns'
)
positions
=
positions
.
replace
(
0
,
np
.
)
df_longs
=
positions
[
positions
>
0
]
.
count
(
axis
=
1
)
df_shorts
=
positions
[
positions
<
0
]
.
count
(
axis
=
1
)
lf
=
ax
.
fill_between
(
df_longs
.
index
,
0
,
df_longs
.
values
,
color
=
'g'
,
alpha
=
0.5
,
lw
=
2.0
)
sf
=
ax
.
fill_between
(
df_shorts
.
index
,
0
,
df_shorts
.
values
,
color
=
'r'
,
alpha
=
0.5
,
lw
=
2.0
)
bf
=
patches
.
Rectangle
(
[
0
,
0
]
,
1
,
1
,
color
=
'darkgoldenrod'
)
leg
=
ax
.
legend
(
[
lf
,
sf
,
bf
]
,
[
'Long (max: %s, min: %s)'
%
(
df_longs
.
max
(
)
,
df_longs
.
min
(
)
)
,
'Short (max: %s, min: %s)'
%
(
df_shorts
.
max
(
)
,
df_shorts
.
min
(
)
)
,
'Overlap'
]
,
loc
=
legend_loc
,
frameon
=
True
,
framealpha
=
0.5
)
leg
.
get_frame
(
)
.
set_edgecolor
(
'black'
)
ax
.
set_xlim
(
(
returns
.
index
[
0
]
,
returns
.
index
[
1
]
)
)
ax
.
set_title
(
'Long and short holdings'
)
ax
.
set_ylabel
(
'Holdings'
)
ax
.
set_xlabel
(
''
)
return
ax

Plots total amount of stocks with an active position breaking out short and long into transparent filled regions .


def plot_drawdown_periods(returns, top=10, ax=None, **kwargs):
    """
    Plots cumulative returns highlighting top drawdown periods.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in tears.create_full_tear_sheet.
    top : int, optional
        Amount of top drawdowns periods to plot (default 10).
    ax : matplotlib.Axes, optional
        Axes upon which to plot.
    **kwargs, optional
        Passed to plotting function.

    Returns
    -------
    ax : matplotlib.Axes
        The axes that were plotted on.
    """

    if ax is None:
        ax = plt.gca()

    y_axis_formatter = FuncFormatter(utils.two_dec_places)
    ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))

    df_cum_rets = ep.cum_returns(returns, starting_value=1.0)
    df_drawdowns = timeseries.gen_drawdown_table(returns, top=top)

    df_cum_rets.plot(ax=ax, **kwargs)

    lim = ax.get_ylim()
    colors = sns.cubehelix_palette(len(df_drawdowns))[::-1]
    for i, (peak, recovery) in df_drawdowns[
            ['Peak date', 'Recovery date']].iterrows():
        if pd.isnull(recovery):
            recovery = returns.index[-1]
        ax.fill_between((peak, recovery),
                        lim[0],
                        lim[1],
                        alpha=.4,
                        color=colors[i])
    ax.set_ylim(lim)
    ax.set_title('Top %i drawdown periods' % top)
    ax.set_ylabel('Cumulative returns')
    ax.legend(['Portfolio'], loc='upper left',
              frameon=True, framealpha=0.5)
    ax.set_xlabel('')
    return ax

def
plot_drawdown_periods
(
returns
,
top
=
10
,
ax
=
,
**
kwargs
)
:
if
ax
is
:
ax
=
plt
.
gca
(
)
y_axis_formatter
=
FuncFormatter
(
utils
.
two_dec_places
)
ax
.
yaxis
.
set_major_formatter
(
FuncFormatter
(
y_axis_formatter
)
)
df_cum_rets
=
ep
.
cum_returns
(
returns
,
starting_value
=
1.0
)
df_drawdowns
=
timeseries
.
gen_drawdown_table
(
returns
,
top
=
top
)
df_cum_rets
.
plot
(
ax
=
ax
,
**
kwargs
)
lim
=
ax
.
get_ylim
(
)
colors
=
sns
.
cubehelix_palette
(
len
(
df_drawdowns
)
)
[
:
:
1
]
for
i
,
(
peak
,
recovery
)
in
df_drawdowns
[
[
'Peak date'
,
'Recovery date'
]
]
.
iterrows
(
)
:
if
pd
.
isnull
(
recovery
)
:
recovery
=
returns
.
index
[
1
]
ax
.
fill_between
(
(
peak
,
recovery
)
,
lim
[
0
]
,
lim
[
1
]
,
alpha
=
.4
,
color
=
colors
[
i
]
)
ax
.
set_ylim
(
lim
)
ax
.
set_title
(
'Top %i drawdown periods'
%
top
)
ax
.
set_ylabel
(
'Cumulative returns'
)
ax
.
legend
(
[
'Portfolio'
]
,
loc
=
'upper left'
,
frameon
=
True
,
framealpha
=
0.5
)
ax
.
set_xlabel
(
''
)
return
ax

Plots cumulative returns highlighting top drawdown periods .


def plot_drawdown_underwater(returns, ax=None, **kwargs):
    """
    Plots how far underwaterr returns are over time, or plots current
    drawdown vs. date.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in tears.create_full_tear_sheet.
    ax : matplotlib.Axes, optional
        Axes upon which to plot.
    **kwargs, optional
        Passed to plotting function.

    Returns
    -------
    ax : matplotlib.Axes
        The axes that were plotted on.
    """

    if ax is None:
        ax = plt.gca()

    y_axis_formatter = FuncFormatter(utils.percentage)
    ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))

    df_cum_rets = ep.cum_returns(returns, starting_value=1.0)
    running_max = np.maximum.accumulate(df_cum_rets)
    underwater = -100 * ((running_max - df_cum_rets) / running_max)
    (underwater).plot(ax=ax, kind='area', color='coral', alpha=0.7, **kwargs)
    ax.set_ylabel('Drawdown')
    ax.set_title('Underwater plot')
    ax.set_xlabel('')
    return ax

def
plot_drawdown_underwater
(
returns
,
ax
=
,
**
kwargs
)
:
if
ax
is
:
ax
=
plt
.
gca
(
)
y_axis_formatter
=
FuncFormatter
(
utils
.
percentage
)
ax
.
yaxis
.
set_major_formatter
(
FuncFormatter
(
y_axis_formatter
)
)
df_cum_rets
=
ep
.
cum_returns
(
returns
,
starting_value
=
1.0
)
running_max
=
np
.
maximum
.
accumulate
(
df_cum_rets
)
underwater
=
100
*
(
(
running_max
df_cum_rets
)
/
running_max
)
(
underwater
)
.
plot
(
ax
=
ax
,
kind
=
'area'
,
color
=
'coral'
,
alpha
=
0.7
,
**
kwargs
)
ax
.
set_ylabel
(
'Drawdown'
)
ax
.
set_title
(
'Underwater plot'
)
ax
.
set_xlabel
(
''
)
return
ax

Plots how far underwaterr returns are over time or plots current drawdown vs . date .


def plot_perf_stats(returns, factor_returns, ax=None):
    """
    Create box plot of some performance metrics of the strategy.
    The width of the box whiskers is determined by a bootstrap.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in tears.create_full_tear_sheet.
    factor_returns : pd.Series
        Daily noncumulative returns of the benchmark factor to which betas are
        computed. Usually a benchmark such as market returns.
         - This is in the same style as returns.
    ax : matplotlib.Axes, optional
        Axes upon which to plot.

    Returns
    -------
    ax : matplotlib.Axes
        The axes that were plotted on.
    """

    if ax is None:
        ax = plt.gca()

    bootstrap_values = timeseries.perf_stats_bootstrap(returns,
                                                       factor_returns,
                                                       return_stats=False)
    bootstrap_values = bootstrap_values.drop('Kurtosis', axis='columns')

    sns.boxplot(data=bootstrap_values, orient='h', ax=ax)

    return ax

def plot_perf_stats ( returns , factor_returns , ax = None ) : if ax is None : ax = plt . gca ( ) bootstrap_values = timeseries . perf_stats_bootstrap ( returns , factor_returns , return_stats = False ) bootstrap_values = bootstrap_values . drop ( 'Kurtosis' , axis = 'columns' ) sns . boxplot ( data = bootstrap_values , orient = 'h' , ax = ax ) return ax

Create box plot of some performance metrics of the strategy . The width of the box whiskers is determined by a bootstrap .


def show_perf_stats(returns, factor_returns=None, positions=None,
                    transactions=None, turnover_denom='AGB',
                    live_start_date=None, bootstrap=False,
                    header_rows=None):
    """
    Prints some performance metrics of the strategy.

    - Shows amount of time the strategy has been run in backtest and
      out-of-sample (in live trading).

    - Shows Omega ratio, max drawdown, Calmar ratio, annual return,
      stability, Sharpe ratio, annual volatility, alpha, and beta.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in tears.create_full_tear_sheet.
    factor_returns : pd.Series, optional
        Daily noncumulative returns of the benchmark factor to which betas are
        computed. Usually a benchmark such as market returns.
         - This is in the same style as returns.
    positions : pd.DataFrame, optional
        Daily net position values.
         - See full explanation in create_full_tear_sheet.
    transactions : pd.DataFrame, optional
        Prices and amounts of executed trades. One row per trade.
        - See full explanation in tears.create_full_tear_sheet
    turnover_denom : str, optional
        Either AGB or portfolio_value, default AGB.
        - See full explanation in txn.get_turnover.
    live_start_date : datetime, optional
        The point in time when the strategy began live trading, after
        its backtest period.
    bootstrap : boolean, optional
        Whether to perform bootstrap analysis for the performance
        metrics.
         - For more information, see timeseries.perf_stats_bootstrap
    header_rows : dict or OrderedDict, optional
        Extra rows to display at the top of the displayed table.
    """

    if bootstrap:
        perf_func = timeseries.perf_stats_bootstrap
    else:
        perf_func = timeseries.perf_stats

    perf_stats_all = perf_func(
        returns,
        factor_returns=factor_returns,
        positions=positions,
        transactions=transactions,
        turnover_denom=turnover_denom)

    date_rows = OrderedDict()
    if len(returns.index) > 0:
        date_rows['Start date'] = returns.index[0].strftime('%Y-%m-%d')
        date_rows['End date'] = returns.index[-1].strftime('%Y-%m-%d')

    if live_start_date is not None:
        live_start_date = ep.utils.get_utc_timestamp(live_start_date)
        returns_is = returns[returns.index < live_start_date]
        returns_oos = returns[returns.index >= live_start_date]

        positions_is = None
        positions_oos = None
        transactions_is = None
        transactions_oos = None

        if positions is not None:
            positions_is = positions[positions.index < live_start_date]
            positions_oos = positions[positions.index >= live_start_date]
            if transactions is not None:
                transactions_is = transactions[(transactions.index <
                                                live_start_date)]
                transactions_oos = transactions[(transactions.index >
                                                 live_start_date)]

        perf_stats_is = perf_func(
            returns_is,
            factor_returns=factor_returns,
            positions=positions_is,
            transactions=transactions_is,
            turnover_denom=turnover_denom)

        perf_stats_oos = perf_func(
            returns_oos,
            factor_returns=factor_returns,
            positions=positions_oos,
            transactions=transactions_oos,
            turnover_denom=turnover_denom)
        if len(returns.index) > 0:
            date_rows['In-sample months'] = int(len(returns_is) /
                                                APPROX_BDAYS_PER_MONTH)
            date_rows['Out-of-sample months'] = int(len(returns_oos) /
                                                    APPROX_BDAYS_PER_MONTH)

        perf_stats = pd.concat(OrderedDict([
            ('In-sample', perf_stats_is),
            ('Out-of-sample', perf_stats_oos),
            ('All', perf_stats_all),
        ]), axis=1)
    else:
        if len(returns.index) > 0:
            date_rows['Total months'] = int(len(returns) /
                                            APPROX_BDAYS_PER_MONTH)
        perf_stats = pd.DataFrame(perf_stats_all, columns=['Backtest'])

    for column in perf_stats.columns:
        for stat, value in perf_stats[column].iteritems():
            if stat in STAT_FUNCS_PCT:
                perf_stats.loc[stat, column] = str(np.round(value * 100,
                                                            1)) + '%'
    if header_rows is None:
        header_rows = date_rows
    else:
        header_rows = OrderedDict(header_rows)
        header_rows.update(date_rows)

    utils.print_table(
        perf_stats,
        float_format='{0:.2f}'.format,
        header_rows=header_rows,
    )

def
show_perf_stats
(
returns
,
factor_returns
=
,
positions
=
,
transactions
=
,
turnover_denom
=
'AGB'
,
live_start_date
=
,
bootstrap
=
False
,
header_rows
=
)
:
if
bootstrap
:
perf_func
=
timeseries
.
perf_stats_bootstrap
else
:
perf_func
=
timeseries
.
perf_stats
perf_stats_all
=
perf_func
(
returns
,
factor_returns
=
factor_returns
,
positions
=
positions
,
transactions
=
transactions
,
turnover_denom
=
turnover_denom
)
date_rows
=
OrderedDict
(
)
if
len
(
returns
.
index
)
>
0
:
date_rows
[
'Start date'
]
=
returns
.
index
[
0
]
.
strftime
(
'%Y-%m-%d'
)
date_rows
[
'End date'
]
=
returns
.
index
[
1
]
.
strftime
(
'%Y-%m-%d'
)
if
live_start_date
is
not
:
live_start_date
=
ep
.
utils
.
get_utc_timestamp
(
live_start_date
)
returns_is
=
returns
[
returns
.
index
<
live_start_date
]
returns_oos
=
returns
[
returns
.
index
>=
live_start_date
]
positions_is
=
positions_oos
=
transactions_is
=
transactions_oos
=
if
positions
is
not
:
positions_is
=
positions
[
positions
.
index
<
live_start_date
]
positions_oos
=
positions
[
positions
.
index
>=
live_start_date
]
if
transactions
is
not
:
transactions_is
=
transactions
[
(
transactions
.
index
<
live_start_date
)
]
transactions_oos
=
transactions
[
(
transactions
.
index
>
live_start_date
)
]
perf_stats_is
=
perf_func
(
returns_is
,
factor_returns
=
factor_returns
,
positions
=
positions_is
,
transactions
=
transactions_is
,
turnover_denom
=
turnover_denom
)
perf_stats_oos
=
perf_func
(
returns_oos
,
factor_returns
=
factor_returns
,
positions
=
positions_oos
,
transactions
=
transactions_oos
,
turnover_denom
=
turnover_denom
)
if
len
(
returns
.
index
)
>
0
:
date_rows
[
'In-sample months'
]
=
int
(
len
(
returns_is
)
/
APPROX_BDAYS_PER_MONTH
)
date_rows
[
'Out-of-sample months'
]
=
int
(
len
(
returns_oos
)
/
APPROX_BDAYS_PER_MONTH
)
perf_stats
=
pd
.
concat
(
OrderedDict
(
[
(
'In-sample'
,
perf_stats_is
)
,
(
'Out-of-sample'
,
perf_stats_oos
)
,
(
'All'
,
perf_stats_all
)
,
]
)
,
axis
=
1
)
else
:
if
len
(
returns
.
index
)
>
0
:
date_rows
[
'Total months'
]
=
int
(
len
(
returns
)
/
APPROX_BDAYS_PER_MONTH
)
perf_stats
=
pd
.
DataFrame
(
perf_stats_all
,
columns
=
[
'Backtest'
]
)
for
column
in
perf_stats
.
columns
:
for
stat
,
value
in
perf_stats
[
column
]
.
iteritems
(
)
:
if
stat
in
STAT_FUNCS_PCT
:
perf_stats
.
loc
[
stat
,
column
]
=
str
(
np
.
round
(
value
*
100
,
1
)
)
+
'%'
if
header_rows
is
:
header_rows
=
date_rows
else
:
header_rows
=
OrderedDict
(
header_rows
)
header_rows
.
update
(
date_rows
)
utils
.
print_table
(
perf_stats
,
float_format
=
'{0:.2f}'
.
format
,
header_rows
=
header_rows
,
)

Prints some performance metrics of the strategy .


def plot_returns(returns,
                 live_start_date=None,
                 ax=None):
    """
    Plots raw returns over time.

    Backtest returns are in green, and out-of-sample (live trading)
    returns are in red.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in tears.create_full_tear_sheet.
    live_start_date : datetime, optional
        The date when the strategy began live trading, after
        its backtest period. This date should be normalized.
    ax : matplotlib.Axes, optional
        Axes upon which to plot.
    **kwargs, optional
        Passed to plotting function.

    Returns
    -------
    ax : matplotlib.Axes
        The axes that were plotted on.
    """

    if ax is None:
        ax = plt.gca()

    ax.set_label('')
    ax.set_ylabel('Returns')

    if live_start_date is not None:
        live_start_date = ep.utils.get_utc_timestamp(live_start_date)
        is_returns = returns.loc[returns.index < live_start_date]
        oos_returns = returns.loc[returns.index >= live_start_date]
        is_returns.plot(ax=ax, color='g')
        oos_returns.plot(ax=ax, color='r')

    else:
        returns.plot(ax=ax, color='g')

    return ax

def plot_returns ( returns , live_start_date = None , ax = None ) : if ax is None : ax = plt . gca ( ) ax . set_label ( '' ) ax . set_ylabel ( 'Returns' ) if live_start_date is not None : live_start_date = ep . utils . get_utc_timestamp ( live_start_date ) is_returns = returns . loc [ returns . index < live_start_date ] oos_returns = returns . loc [ returns . index >= live_start_date ] is_returns . plot ( ax = ax , color = 'g' ) oos_returns . plot ( ax = ax , color = 'r' ) else : returns . plot ( ax = ax , color = 'g' ) return ax


def plot_rolling_returns(returns,
                         factor_returns=None,
                         live_start_date=None,
                         logy=False,
                         cone_std=None,
                         legend_loc='best',
                         volatility_match=False,
                         cone_function=timeseries.forecast_cone_bootstrap,
                         ax=None, **kwargs):
    """
    Plots cumulative rolling returns versus some benchmarks'.

    Backtest returns are in green, and out-of-sample (live trading)
    returns are in red.

    Additionally, a non-parametric cone plot may be added to the
    out-of-sample returns region.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in tears.create_full_tear_sheet.
    factor_returns : pd.Series, optional
        Daily noncumulative returns of the benchmark factor to which betas are
        computed. Usually a benchmark such as market returns.
         - This is in the same style as returns.
    live_start_date : datetime, optional
        The date when the strategy began live trading, after
        its backtest period. This date should be normalized.
    logy : bool, optional
        Whether to log-scale the y-axis.
    cone_std : float, or tuple, optional
        If float, The standard deviation to use for the cone plots.
        If tuple, Tuple of standard deviation values to use for the cone plots
         - See timeseries.forecast_cone_bounds for more details.
    legend_loc : matplotlib.loc, optional
        The location of the legend on the plot.
    volatility_match : bool, optional
        Whether to normalize the volatility of the returns to those of the
        benchmark returns. This helps compare strategies with different
        volatilities. Requires passing of benchmark_rets.
    cone_function : function, optional
        Function to use when generating forecast probability cone.
        The function signiture must follow the form:
        def cone(in_sample_returns (pd.Series),
                 days_to_project_forward (int),
                 cone_std= (float, or tuple),
                 starting_value= (int, or float))
        See timeseries.forecast_cone_bootstrap for an example.
    ax : matplotlib.Axes, optional
        Axes upon which to plot.
    **kwargs, optional
        Passed to plotting function.

    Returns
    -------
    ax : matplotlib.Axes
        The axes that were plotted on.
    """

    if ax is None:
        ax = plt.gca()

    ax.set_xlabel('')
    ax.set_ylabel('Cumulative returns')
    ax.set_yscale('log' if logy else 'linear')

    if volatility_match and factor_returns is None:
        raise ValueError('volatility_match requires passing of '
                         'factor_returns.')
    elif volatility_match and factor_returns is not None:
        bmark_vol = factor_returns.loc[returns.index].std()
        returns = (returns / returns.std()) * bmark_vol

    cum_rets = ep.cum_returns(returns, 1.0)

    y_axis_formatter = FuncFormatter(utils.two_dec_places)
    ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))

    if factor_returns is not None:
        cum_factor_returns = ep.cum_returns(
            factor_returns[cum_rets.index], 1.0)
        cum_factor_returns.plot(lw=2, color='gray',
                                label=factor_returns.name, alpha=0.60,
                                ax=ax, **kwargs)

    if live_start_date is not None:
        live_start_date = ep.utils.get_utc_timestamp(live_start_date)
        is_cum_returns = cum_rets.loc[cum_rets.index < live_start_date]
        oos_cum_returns = cum_rets.loc[cum_rets.index >= live_start_date]
    else:
        is_cum_returns = cum_rets
        oos_cum_returns = pd.Series([])

    is_cum_returns.plot(lw=3, color='forestgreen', alpha=0.6,
                        label='Backtest', ax=ax, **kwargs)

    if len(oos_cum_returns) > 0:
        oos_cum_returns.plot(lw=4, color='red', alpha=0.6,
                             label='Live', ax=ax, **kwargs)

        if cone_std is not None:
            if isinstance(cone_std, (float, int)):
                cone_std = [cone_std]

            is_returns = returns.loc[returns.index < live_start_date]
            cone_bounds = cone_function(
                is_returns,
                len(oos_cum_returns),
                cone_std=cone_std,
                starting_value=is_cum_returns[-1])

            cone_bounds = cone_bounds.set_index(oos_cum_returns.index)
            for std in cone_std:
                ax.fill_between(cone_bounds.index,
                                cone_bounds[float(std)],
                                cone_bounds[float(-std)],
                                color='steelblue', alpha=0.5)

    if legend_loc is not None:
        ax.legend(loc=legend_loc, frameon=True, framealpha=0.5)
    ax.axhline(1.0, linestyle='--', color='black', lw=2)

    return ax

def
plot_rolling_returns
(
returns
,
factor_returns
=
,
live_start_date
=
,
logy
=
False
,
cone_std
=
,
legend_loc
=
'best'
,
volatility_match
=
False
,
cone_function
=
timeseries
.
forecast_cone_bootstrap
,
ax
=
,
**
kwargs
)
:
if
ax
is
:
ax
=
plt
.
gca
(
)
ax
.
set_xlabel
(
''
)
ax
.
set_ylabel
(
'Cumulative returns'
)
ax
.
set_yscale
(
'log'
if
logy
else
'linear'
)
if
volatility_match
and
factor_returns
is
:
raise
ValueError
(
'volatility_match requires passing of '
'factor_returns.'
)
elif
volatility_match
and
factor_returns
is
not
:
bmark_vol
=
factor_returns
.
loc
[
returns
.
index
]
.
std
(
)
returns
=
(
returns
/
returns
.
std
(
)
)
*
bmark_vol
cum_rets
=
ep
.
cum_returns
(
returns
,
1.0
)
y_axis_formatter
=
FuncFormatter
(
utils
.
two_dec_places
)
ax
.
yaxis
.
set_major_formatter
(
FuncFormatter
(
y_axis_formatter
)
)
if
factor_returns
is
not
:
cum_factor_returns
=
ep
.
cum_returns
(
factor_returns
[
cum_rets
.
index
]
,
1.0
)
cum_factor_returns
.
plot
(
lw
=
2
,
color
=
'gray'
,
label
=
factor_returns
.
name
,
alpha
=
0.60
,
ax
=
ax
,
**
kwargs
)
if
live_start_date
is
not
:
live_start_date
=
ep
.
utils
.
get_utc_timestamp
(
live_start_date
)
is_cum_returns
=
cum_rets
.
loc
[
cum_rets
.
index
<
live_start_date
]
oos_cum_returns
=
cum_rets
.
loc
[
cum_rets
.
index
>=
live_start_date
]
else
:
is_cum_returns
=
cum_rets
oos_cum_returns
=
pd
.
Series
(
[
]
)
is_cum_returns
.
plot
(
lw
=
3
,
color
=
'forestgreen'
,
alpha
=
0.6
,
label
=
'Backtest'
,
ax
=
ax
,
**
kwargs
)
if
len
(
oos_cum_returns
)
>
0
:
oos_cum_returns
.
plot
(
lw
=
4
,
color
=
'red'
,
alpha
=
0.6
,
label
=
'Live'
,
ax
=
ax
,
**
kwargs
)
if
cone_std
is
not
:
if
isinstance
(
cone_std
,
(
float
,
int
)
)
:
cone_std
=
[
cone_std
]
is_returns
=
returns
.
loc
[
returns
.
index
<
live_start_date
]
cone_bounds
=
cone_function
(
is_returns
,
len
(
oos_cum_returns
)
,
cone_std
=
cone_std
,
starting_value
=
is_cum_returns
[
1
]
)
cone_bounds
=
cone_bounds
.
set_index
(
oos_cum_returns
.
index
)
for
std
in
cone_std
:
ax
.
fill_between
(
cone_bounds
.
index
,
cone_bounds
[
float
(
std
)
]
,
cone_bounds
[
float
(
std
)
]
,
color
=
'steelblue'
,
alpha
=
0.5
)
if
legend_loc
is
not
:
ax
.
legend
(
loc
=
legend_loc
,
frameon
=
True
,
framealpha
=
0.5
)
ax
.
axhline
(
1.0
,
linestyle
=
'--'
,
color
=
'black'
,
lw
=
2
)
return
ax

Plots cumulative rolling returns versus some benchmarks .


def plot_rolling_beta(returns, factor_returns, legend_loc='best',
                      ax=None, **kwargs):
    """
    Plots the rolling 6-month and 12-month beta versus date.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in tears.create_full_tear_sheet.
    factor_returns : pd.Series
        Daily noncumulative returns of the benchmark factor to which betas are
        computed. Usually a benchmark such as market returns.
         - This is in the same style as returns.
    legend_loc : matplotlib.loc, optional
        The location of the legend on the plot.
    ax : matplotlib.Axes, optional
        Axes upon which to plot.
    **kwargs, optional
        Passed to plotting function.

    Returns
    -------
    ax : matplotlib.Axes
        The axes that were plotted on.
    """

    if ax is None:
        ax = plt.gca()

    y_axis_formatter = FuncFormatter(utils.two_dec_places)
    ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))

    ax.set_title("Rolling portfolio beta to " + str(factor_returns.name))
    ax.set_ylabel('Beta')
    rb_1 = timeseries.rolling_beta(
        returns, factor_returns, rolling_window=APPROX_BDAYS_PER_MONTH * 6)
    rb_1.plot(color='steelblue', lw=3, alpha=0.6, ax=ax, **kwargs)
    rb_2 = timeseries.rolling_beta(
        returns, factor_returns, rolling_window=APPROX_BDAYS_PER_MONTH * 12)
    rb_2.plot(color='grey', lw=3, alpha=0.4, ax=ax, **kwargs)
    ax.axhline(rb_1.mean(), color='steelblue', linestyle='--', lw=3)
    ax.axhline(0.0, color='black', linestyle='-', lw=2)

    ax.set_xlabel('')
    ax.legend(['6-mo',
               '12-mo'],
              loc=legend_loc, frameon=True, framealpha=0.5)
    ax.set_ylim((-1.0, 1.0))
    return ax

def
plot_rolling_beta
(
returns
,
factor_returns
,
legend_loc
=
'best'
,
ax
=
,
**
kwargs
)
:
if
ax
is
:
ax
=
plt
.
gca
(
)
y_axis_formatter
=
FuncFormatter
(
utils
.
two_dec_places
)
ax
.
yaxis
.
set_major_formatter
(
FuncFormatter
(
y_axis_formatter
)
)
ax
.
set_title
(
"Rolling portfolio beta to "
+
str
(
factor_returns
.
name
)
)
ax
.
set_ylabel
(
'Beta'
)
rb_1
=
timeseries
.
rolling_beta
(
returns
,
factor_returns
,
rolling_window
=
APPROX_BDAYS_PER_MONTH
*
6
)
rb_1
.
plot
(
color
=
'steelblue'
,
lw
=
3
,
alpha
=
0.6
,
ax
=
ax
,
**
kwargs
)
rb_2
=
timeseries
.
rolling_beta
(
returns
,
factor_returns
,
rolling_window
=
APPROX_BDAYS_PER_MONTH
*
12
)
rb_2
.
plot
(
color
=
'grey'
,
lw
=
3
,
alpha
=
0.4
,
ax
=
ax
,
**
kwargs
)
ax
.
axhline
(
rb_1
.
mean
(
)
,
color
=
'steelblue'
,
linestyle
=
'--'
,
lw
=
3
)
ax
.
axhline
(
0.0
,
color
=
'black'
,
linestyle
=
'-'
,
lw
=
2
)
ax
.
set_xlabel
(
''
)
ax
.
legend
(
[
'6-mo'
,
'12-mo'
]
,
loc
=
legend_loc
,
frameon
=
True
,
framealpha
=
0.5
)
ax
.
set_ylim
(
(
1.0
,
1.0
)
)
return
ax

Plots the rolling 6 - month and 12 - month beta versus date .


def plot_rolling_volatility(returns, factor_returns=None,
                            rolling_window=APPROX_BDAYS_PER_MONTH * 6,
                            legend_loc='best', ax=None, **kwargs):
    """
    Plots the rolling volatility versus date.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in tears.create_full_tear_sheet.
    factor_returns : pd.Series, optional
        Daily noncumulative returns of the benchmark factor to which betas are
        computed. Usually a benchmark such as market returns.
         - This is in the same style as returns.
    rolling_window : int, optional
        The days window over which to compute the volatility.
    legend_loc : matplotlib.loc, optional
        The location of the legend on the plot.
    ax : matplotlib.Axes, optional
        Axes upon which to plot.
    **kwargs, optional
        Passed to plotting function.

    Returns
    -------
    ax : matplotlib.Axes
        The axes that were plotted on.
    """

    if ax is None:
        ax = plt.gca()

    y_axis_formatter = FuncFormatter(utils.two_dec_places)
    ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))

    rolling_vol_ts = timeseries.rolling_volatility(
        returns, rolling_window)
    rolling_vol_ts.plot(alpha=.7, lw=3, color='orangered', ax=ax,
                        **kwargs)
    if factor_returns is not None:
        rolling_vol_ts_factor = timeseries.rolling_volatility(
            factor_returns, rolling_window)
        rolling_vol_ts_factor.plot(alpha=.7, lw=3, color='grey', ax=ax,
                                   **kwargs)

    ax.set_title('Rolling volatility (6-month)')
    ax.axhline(
        rolling_vol_ts.mean(),
        color='steelblue',
        linestyle='--',
        lw=3)

    ax.axhline(0.0, color='black', linestyle='-', lw=2)

    ax.set_ylabel('Volatility')
    ax.set_xlabel('')
    if factor_returns is None:
        ax.legend(['Volatility', 'Average volatility'],
                  loc=legend_loc, frameon=True, framealpha=0.5)
    else:
        ax.legend(['Volatility', 'Benchmark volatility', 'Average volatility'],
                  loc=legend_loc, frameon=True, framealpha=0.5)
    return ax

def
plot_rolling_volatility
(
returns
,
factor_returns
=
,
rolling_window
=
APPROX_BDAYS_PER_MONTH
*
6
,
legend_loc
=
'best'
,
ax
=
,
**
kwargs
)
:
if
ax
is
:
ax
=
plt
.
gca
(
)
y_axis_formatter
=
FuncFormatter
(
utils
.
two_dec_places
)
ax
.
yaxis
.
set_major_formatter
(
FuncFormatter
(
y_axis_formatter
)
)
rolling_vol_ts
=
timeseries
.
rolling_volatility
(
returns
,
rolling_window
)
rolling_vol_ts
.
plot
(
alpha
=
.7
,
lw
=
3
,
color
=
'orangered'
,
ax
=
ax
,
**
kwargs
)
if
factor_returns
is
not
:
rolling_vol_ts_factor
=
timeseries
.
rolling_volatility
(
factor_returns
,
rolling_window
)
rolling_vol_ts_factor
.
plot
(
alpha
=
.7
,
lw
=
3
,
color
=
'grey'
,
ax
=
ax
,
**
kwargs
)
ax
.
set_title
(
'Rolling volatility (6-month)'
)
ax
.
axhline
(
rolling_vol_ts
.
mean
(
)
,
color
=
'steelblue'
,
linestyle
=
'--'
,
lw
=
3
)
ax
.
axhline
(
0.0
,
color
=
'black'
,
linestyle
=
'-'
,
lw
=
2
)
ax
.
set_ylabel
(
'Volatility'
)
ax
.
set_xlabel
(
''
)
if
factor_returns
is
:
ax
.
legend
(
[
'Volatility'
,
'Average volatility'
]
,
loc
=
legend_loc
,
frameon
=
True
,
framealpha
=
0.5
)
else
:
ax
.
legend
(
[
'Volatility'
,
'Benchmark volatility'
,
'Average volatility'
]
,
loc
=
legend_loc
,
frameon
=
True
,
framealpha
=
0.5
)
return
ax

Plots the rolling volatility versus date .


def plot_rolling_sharpe(returns, factor_returns=None,
                        rolling_window=APPROX_BDAYS_PER_MONTH * 6,
                        legend_loc='best', ax=None, **kwargs):
    """
    Plots the rolling Sharpe ratio versus date.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in tears.create_full_tear_sheet.
    factor_returns : pd.Series, optional
        Daily noncumulative returns of the benchmark factor for
        which the benchmark rolling Sharpe is computed. Usually
        a benchmark such as market returns.
         - This is in the same style as returns.
    rolling_window : int, optional
        The days window over which to compute the sharpe ratio.
    legend_loc : matplotlib.loc, optional
        The location of the legend on the plot.
    ax : matplotlib.Axes, optional
        Axes upon which to plot.
    **kwargs, optional
        Passed to plotting function.

    Returns
    -------
    ax : matplotlib.Axes
        The axes that were plotted on.
    """

    if ax is None:
        ax = plt.gca()

    y_axis_formatter = FuncFormatter(utils.two_dec_places)
    ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))

    rolling_sharpe_ts = timeseries.rolling_sharpe(
        returns, rolling_window)
    rolling_sharpe_ts.plot(alpha=.7, lw=3, color='orangered', ax=ax,
                           **kwargs)

    if factor_returns is not None:
        rolling_sharpe_ts_factor = timeseries.rolling_sharpe(
            factor_returns, rolling_window)
        rolling_sharpe_ts_factor.plot(alpha=.7, lw=3, color='grey', ax=ax,
                                      **kwargs)

    ax.set_title('Rolling Sharpe ratio (6-month)')
    ax.axhline(
        rolling_sharpe_ts.mean(),
        color='steelblue',
        linestyle='--',
        lw=3)
    ax.axhline(0.0, color='black', linestyle='-', lw=3)

    ax.set_ylabel('Sharpe ratio')
    ax.set_xlabel('')
    if factor_returns is None:
        ax.legend(['Sharpe', 'Average'],
                  loc=legend_loc, frameon=True, framealpha=0.5)
    else:
        ax.legend(['Sharpe', 'Benchmark Sharpe', 'Average'],
                  loc=legend_loc, frameon=True, framealpha=0.5)

    return ax

def
plot_rolling_sharpe
(
returns
,
factor_returns
=
,
rolling_window
=
APPROX_BDAYS_PER_MONTH
*
6
,
legend_loc
=
'best'
,
ax
=
,
**
kwargs
)
:
if
ax
is
:
ax
=
plt
.
gca
(
)
y_axis_formatter
=
FuncFormatter
(
utils
.
two_dec_places
)
ax
.
yaxis
.
set_major_formatter
(
FuncFormatter
(
y_axis_formatter
)
)
rolling_sharpe_ts
=
timeseries
.
rolling_sharpe
(
returns
,
rolling_window
)
rolling_sharpe_ts
.
plot
(
alpha
=
.7
,
lw
=
3
,
color
=
'orangered'
,
ax
=
ax
,
**
kwargs
)
if
factor_returns
is
not
:
rolling_sharpe_ts_factor
=
timeseries
.
rolling_sharpe
(
factor_returns
,
rolling_window
)
rolling_sharpe_ts_factor
.
plot
(
alpha
=
.7
,
lw
=
3
,
color
=
'grey'
,
ax
=
ax
,
**
kwargs
)
ax
.
set_title
(
'Rolling Sharpe ratio (6-month)'
)
ax
.
axhline
(
rolling_sharpe_ts
.
mean
(
)
,
color
=
'steelblue'
,
linestyle
=
'--'
,
lw
=
3
)
ax
.
axhline
(
0.0
,
color
=
'black'
,
linestyle
=
'-'
,
lw
=
3
)
ax
.
set_ylabel
(
'Sharpe ratio'
)
ax
.
set_xlabel
(
''
)
if
factor_returns
is
:
ax
.
legend
(
[
'Sharpe'
,
'Average'
]
,
loc
=
legend_loc
,
frameon
=
True
,
framealpha
=
0.5
)
else
:
ax
.
legend
(
[
'Sharpe'
,
'Benchmark Sharpe'
,
'Average'
]
,
loc
=
legend_loc
,
frameon
=
True
,
framealpha
=
0.5
)
return
ax

Plots the rolling Sharpe ratio versus date .


def plot_gross_leverage(returns, positions, ax=None, **kwargs):
    """
    Plots gross leverage versus date.

    Gross leverage is the sum of long and short exposure per share
    divided by net asset value.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in tears.create_full_tear_sheet.
    positions : pd.DataFrame
        Daily net position values.
         - See full explanation in create_full_tear_sheet.
    ax : matplotlib.Axes, optional
        Axes upon which to plot.
    **kwargs, optional
        Passed to plotting function.

    Returns
    -------
    ax : matplotlib.Axes
        The axes that were plotted on.
    """

    if ax is None:
        ax = plt.gca()
    gl = timeseries.gross_lev(positions)
    gl.plot(lw=0.5, color='limegreen', legend=False, ax=ax, **kwargs)

    ax.axhline(gl.mean(), color='g', linestyle='--', lw=3)

    ax.set_title('Gross leverage')
    ax.set_ylabel('Gross leverage')
    ax.set_xlabel('')
    return ax

def
plot_gross_leverage
(
returns
,
positions
,
ax
=
,
**
kwargs
)
:
if
ax
is
:
ax
=
plt
.
gca
(
)
gl
=
timeseries
.
gross_lev
(
positions
)
gl
.
plot
(
lw
=
0.5
,
color
=
'limegreen'
,
legend
=
False
,
ax
=
ax
,
**
kwargs
)
ax
.
axhline
(
gl
.
mean
(
)
,
color
=
'g'
,
linestyle
=
'--'
,
lw
=
3
)
ax
.
set_title
(
'Gross leverage'
)
ax
.
set_ylabel
(
'Gross leverage'
)
ax
.
set_xlabel
(
''
)
return
ax


def plot_exposures(returns, positions, ax=None, **kwargs):
    """
    Plots a cake chart of the long and short exposure.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in tears.create_full_tear_sheet.
    positions_alloc : pd.DataFrame
        Portfolio allocation of positions. See
        pos.get_percent_alloc.
    ax : matplotlib.Axes, optional
        Axes upon which to plot.
    **kwargs, optional
        Passed to plotting function.

    Returns
    -------
    ax : matplotlib.Axes
        The axes that were plotted on.
    """

    if ax is None:
        ax = plt.gca()

    pos_no_cash = positions.drop('cash', axis=1)
    l_exp = pos_no_cash[pos_no_cash > 0].sum(axis=1) / positions.sum(axis=1)
    s_exp = pos_no_cash[pos_no_cash < 0].sum(axis=1) / positions.sum(axis=1)
    net_exp = pos_no_cash.sum(axis=1) / positions.sum(axis=1)

    ax.fill_between(l_exp.index,
                    0,
                    l_exp.values,
                    label='Long', color='green', alpha=0.5)
    ax.fill_between(s_exp.index,
                    0,
                    s_exp.values,
                    label='Short', color='red', alpha=0.5)
    ax.plot(net_exp.index, net_exp.values,
            label='Net', color='black', linestyle='dotted')

    ax.set_xlim((returns.index[0], returns.index[-1]))
    ax.set_title("Exposure")
    ax.set_ylabel('Exposure')
    ax.legend(loc='lower left', frameon=True, framealpha=0.5)
    ax.set_xlabel('')
    return ax

def
plot_exposures
(
returns
,
positions
,
ax
=
,
**
kwargs
)
:
if
ax
is
:
ax
=
plt
.
gca
(
)
pos_no_cash
=
positions
.
drop
(
'cash'
,
axis
=
1
)
l_exp
=
pos_no_cash
[
pos_no_cash
>
0
]
.
sum
(
axis
=
1
)
/
positions
.
sum
(
axis
=
1
)
s_exp
=
pos_no_cash
[
pos_no_cash
<
0
]
.
sum
(
axis
=
1
)
/
positions
.
sum
(
axis
=
1
)
net_exp
=
pos_no_cash
.
sum
(
axis
=
1
)
/
positions
.
sum
(
axis
=
1
)
ax
.
fill_between
(
l_exp
.
index
,
0
,
l_exp
.
values
,
label
=
'Long'
,
color
=
'green'
,
alpha
=
0.5
)
ax
.
fill_between
(
s_exp
.
index
,
0
,
s_exp
.
values
,
label
=
'Short'
,
color
=
'red'
,
alpha
=
0.5
)
ax
.
plot
(
net_exp
.
index
,
net_exp
.
values
,
label
=
'Net'
,
color
=
'black'
,
linestyle
=
'dotted'
)
ax
.
set_xlim
(
(
returns
.
index
[
0
]
,
returns
.
index
[
1
]
)
)
ax
.
set_title
(
"Exposure"
)
ax
.
set_ylabel
(
'Exposure'
)
ax
.
legend
(
loc
=
'lower left'
,
frameon
=
True
,
framealpha
=
0.5
)
ax
.
set_xlabel
(
''
)
return
ax

Plots a cake chart of the long and short exposure .


def plot_max_median_position_concentration(positions, ax=None, **kwargs):
    """
    Plots the max and median of long and short position concentrations
    over the time.

    Parameters
    ----------
    positions : pd.DataFrame
        The positions that the strategy takes over time.
    ax : matplotlib.Axes, optional
        Axes upon which to plot.

    Returns
    -------
    ax : matplotlib.Axes
        The axes that were plotted on.
    """

    if ax is None:
        ax = plt.gca()

    alloc_summary = pos.get_max_median_position_concentration(positions)
    colors = ['mediumblue', 'steelblue', 'tomato', 'firebrick']
    alloc_summary.plot(linewidth=1, color=colors, alpha=0.6, ax=ax)

    ax.legend(loc='center left', frameon=True, framealpha=0.5)
    ax.set_ylabel('Exposure')
    ax.set_title('Long/short max and median position concentration')

    return ax

Plots the max and median of long and short position concentrations over the time .


def plot_sector_allocations(returns, sector_alloc, ax=None, **kwargs):
    """
    Plots the sector exposures of the portfolio over time.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in tears.create_full_tear_sheet.
    sector_alloc : pd.DataFrame
        Portfolio allocation of positions. See pos.get_sector_alloc.
    ax : matplotlib.Axes, optional
        Axes upon which to plot.
    **kwargs, optional
        Passed to plotting function.

    Returns
    -------
    ax : matplotlib.Axes
        The axes that were plotted on.
    """

    if ax is None:
        ax = plt.gca()

    sector_alloc.plot(title='Sector allocation over time',
                      alpha=0.5, ax=ax, **kwargs)

    box = ax.get_position()
    ax.set_position([box.x0, box.y0 + box.height * 0.1,
                     box.width, box.height * 0.9])

    # Put a legend below current axis
    ax.legend(loc='upper center', frameon=True, framealpha=0.5,
              bbox_to_anchor=(0.5, -0.14), ncol=5)

    ax.set_xlim((sector_alloc.index[0], sector_alloc.index[-1]))
    ax.set_ylabel('Exposure by sector')
    ax.set_xlabel('')

    return ax

def
plot_sector_allocations
(
returns
,
sector_alloc
,
ax
=
,
**
kwargs
)
:
if
ax
is
:
ax
=
plt
.
gca
(
)
sector_alloc
.
plot
(
title
=
'Sector allocation over time'
,
alpha
=
0.5
,
ax
=
ax
,
**
kwargs
)
box
=
ax
.
get_position
(
)
ax
.
set_position
(
[
box
.
x0
,
box
.
y0
+
box
.
height
*
0.1
,
box
.
width
,
box
.
height
*
0.9
]
)
ax
.
legend
(
loc
=
'upper center'
,
frameon
=
True
,
framealpha
=
0.5
,
bbox_to_anchor
=
(
0.5
,
0.14
)
,
ncol
=
5
)
ax
.
set_xlim
(
(
sector_alloc
.
index
[
0
]
,
sector_alloc
.
index
[
1
]
)
)
ax
.
set_ylabel
(
'Exposure by sector'
)
ax
.
set_xlabel
(
''
)
return
ax

Plots the sector exposures of the portfolio over time .


def plot_return_quantiles(returns, live_start_date=None, ax=None, **kwargs):
    """
    Creates a box plot of daily, weekly, and monthly return
    distributions.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in tears.create_full_tear_sheet.
    live_start_date : datetime, optional
        The point in time when the strategy began live trading, after
        its backtest period.
    ax : matplotlib.Axes, optional
        Axes upon which to plot.
    **kwargs, optional
        Passed to seaborn plotting function.

    Returns
    -------
    ax : matplotlib.Axes
        The axes that were plotted on.
    """

    if ax is None:
        ax = plt.gca()

    is_returns = returns if live_start_date is None \
        else returns.loc[returns.index < live_start_date]
    is_weekly = ep.aggregate_returns(is_returns, 'weekly')
    is_monthly = ep.aggregate_returns(is_returns, 'monthly')
    sns.boxplot(data=[is_returns, is_weekly, is_monthly],
                palette=["#4c72B0", "#55A868", "#CCB974"],
                ax=ax, **kwargs)

    if live_start_date is not None:
        oos_returns = returns.loc[returns.index >= live_start_date]
        oos_weekly = ep.aggregate_returns(oos_returns, 'weekly')
        oos_monthly = ep.aggregate_returns(oos_returns, 'monthly')

        sns.swarmplot(data=[oos_returns, oos_weekly, oos_monthly], ax=ax,
                      color="red",
                      marker="d", **kwargs)
        red_dots = matplotlib.lines.Line2D([], [], color="red", marker="d",
                                           label="Out-of-sample data",
                                           linestyle='')
        ax.legend(handles=[red_dots], frameon=True, framealpha=0.5)
    ax.set_xticklabels(['Daily', 'Weekly', 'Monthly'])
    ax.set_title('Return quantiles')

    return ax

def
plot_return_quantiles
(
returns
,
live_start_date
=
,
ax
=
,
**
kwargs
)
:
if
ax
is
:
ax
=
plt
.
gca
(
)
is_returns
=
returns
if
live_start_date
is
else
returns
.
loc
[
returns
.
index
<
live_start_date
]
is_weekly
=
ep
.
aggregate_returns
(
is_returns
,
'weekly'
)
is_monthly
=
ep
.
aggregate_returns
(
is_returns
,
'monthly'
)
sns
.
boxplot
(
data
=
[
is_returns
,
is_weekly
,
is_monthly
]
,
palette
=
[
"#4c72B0"
,
"#55A868"
,
"#CCB974"
]
,
ax
=
ax
,
**
kwargs
)
if
live_start_date
is
not
:
oos_returns
=
returns
.
loc
[
returns
.
index
>=
live_start_date
]
oos_weekly
=
ep
.
aggregate_returns
(
oos_returns
,
'weekly'
)
oos_monthly
=
ep
.
aggregate_returns
(
oos_returns
,
'monthly'
)
sns
.
swarmplot
(
data
=
[
oos_returns
,
oos_weekly
,
oos_monthly
]
,
ax
=
ax
,
color
=
"red"
,
marker
=
"d"
,
**
kwargs
)
red_dots
=
matplotlib
.
lines
.
Line2D
(
[
]
,
[
]
,
color
=
"red"
,
marker
=
"d"
,
label
=
"Out-of-sample data"
,
linestyle
=
''
)
ax
.
legend
(
handles
=
[
red_dots
]
,
frameon
=
True
,
framealpha
=
0.5
)
ax
.
set_xticklabels
(
[
'Daily'
,
'Weekly'
,
'Monthly'
]
)
ax
.
set_title
(
'Return quantiles'
)
return
ax

Creates a box plot of daily weekly and monthly return distributions .


def plot_turnover(returns, transactions, positions,
                  legend_loc='best', ax=None, **kwargs):
    """
    Plots turnover vs. date.

    Turnover is the number of shares traded for a period as a fraction
    of total shares.

    Displays daily total, daily average per month, and all-time daily
    average.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in tears.create_full_tear_sheet.
    transactions : pd.DataFrame
        Prices and amounts of executed trades. One row per trade.
         - See full explanation in tears.create_full_tear_sheet.
    positions : pd.DataFrame
        Daily net position values.
         - See full explanation in tears.create_full_tear_sheet.
    legend_loc : matplotlib.loc, optional
        The location of the legend on the plot.
    ax : matplotlib.Axes, optional
        Axes upon which to plot.
    **kwargs, optional
        Passed to plotting function.

    Returns
    -------
    ax : matplotlib.Axes
        The axes that were plotted on.
    """

    if ax is None:
        ax = plt.gca()

    y_axis_formatter = FuncFormatter(utils.two_dec_places)
    ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))

    df_turnover = txn.get_turnover(positions, transactions)
    df_turnover_by_month = df_turnover.resample("M").mean()
    df_turnover.plot(color='steelblue', alpha=1.0, lw=0.5, ax=ax, **kwargs)
    df_turnover_by_month.plot(
        color='orangered',
        alpha=0.5,
        lw=2,
        ax=ax,
        **kwargs)
    ax.axhline(
        df_turnover.mean(), color='steelblue', linestyle='--', lw=3, alpha=1.0)
    ax.legend(['Daily turnover',
               'Average daily turnover, by month',
               'Average daily turnover, net'],
              loc=legend_loc, frameon=True, framealpha=0.5)
    ax.set_title('Daily turnover')
    ax.set_xlim((returns.index[0], returns.index[-1]))
    ax.set_ylim((0, 2))
    ax.set_ylabel('Turnover')
    ax.set_xlabel('')
    return ax

def
plot_turnover
(
returns
,
transactions
,
positions
,
legend_loc
=
'best'
,
ax
=
,
**
kwargs
)
:
if
ax
is
:
ax
=
plt
.
gca
(
)
y_axis_formatter
=
FuncFormatter
(
utils
.
two_dec_places
)
ax
.
yaxis
.
set_major_formatter
(
FuncFormatter
(
y_axis_formatter
)
)
df_turnover
=
txn
.
get_turnover
(
positions
,
transactions
)
df_turnover_by_month
=
df_turnover
.
resample
(
"M"
)
.
mean
(
)
df_turnover
.
plot
(
color
=
'steelblue'
,
alpha
=
1.0
,
lw
=
0.5
,
ax
=
ax
,
**
kwargs
)
df_turnover_by_month
.
plot
(
color
=
'orangered'
,
alpha
=
0.5
,
lw
=
2
,
ax
=
ax
,
**
kwargs
)
ax
.
axhline
(
df_turnover
.
mean
(
)
,
color
=
'steelblue'
,
linestyle
=
'--'
,
lw
=
3
,
alpha
=
1.0
)
ax
.
legend
(
[
'Daily turnover'
,
'Average daily turnover, by month'
,
'Average daily turnover, net'
]
,
loc
=
legend_loc
,
frameon
=
True
,
framealpha
=
0.5
)
ax
.
set_title
(
'Daily turnover'
)
ax
.
set_xlim
(
(
returns
.
index
[
0
]
,
returns
.
index
[
1
]
)
)
ax
.
set_ylim
(
(
0
,
2
)
)
ax
.
set_ylabel
(
'Turnover'
)
ax
.
set_xlabel
(
''
)
return
ax