API

The pyfolio API is organized into various modules:

Tear Sheets

Pyfolio combines key portfolio metrics in thematic plots and summary tear sheets.

pyfolio.tears.create_capacity_tear_sheet(returns, positions, transactions, market_data, liquidation_daily_vol_limit=0.2, trade_daily_vol_limit=0.05, last_n_days=126, days_to_liquidate_limit=1, estimate_intraday='infer', return_fig=False)

Generates a report detailing portfolio size constraints set by least liquid tickers. Plots a “capacity sweep,” a curve describing projected sharpe ratio given the slippage penalties that are applied at various capital bases.

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in create_full_tear_sheet.

positionspd.DataFrame
Daily net position values.
  • See full explanation in create_full_tear_sheet.

transactionspd.DataFrame
Prices and amounts of executed trades. One row per trade.
  • See full explanation in create_full_tear_sheet.

market_datapd.DataFrame

Daily market_data - DataFrame has a multi-index index, one level is dates and another is market_data contains volume & price, equities as columns

liquidation_daily_vol_limitfloat

Max proportion of a daily bar that can be consumed in the process of liquidating a position in the “days to liquidation” analysis.

trade_daily_vol_limitfloat

Flag daily transaction totals that exceed proportion of daily bar.

last_n_daysinteger

Compute max position allocation and dollar volume for only the last N days of the backtest

days_to_liquidate_limitinteger

Display all tickers with greater max days to liquidation.

estimate_intraday: boolean or str, optional

Approximate returns for intraday strategies. See description in create_full_tear_sheet.

return_figboolean, optional

If True, returns the figure that was plotted on.

pyfolio.tears.create_full_tear_sheet(returns, positions=None, transactions=None, market_data=None, benchmark_rets=None, slippage=None, live_start_date=None, sector_mappings=None, round_trips=False, estimate_intraday='infer', hide_positions=False, cone_std=(1.0, 1.5, 2.0), bootstrap=False, unadjusted_returns=None, turnover_denom='AGB', set_context=True, factor_returns=None, factor_loadings=None, pos_in_dollars=True, header_rows=None, factor_partitions={'sector': ['basic_materials', 'consumer_cyclical', 'financial_services', 'real_estate', 'consumer_defensive', 'health_care', 'utilities', 'communication_services', 'energy', 'industrials', 'technology'], 'style': ['momentum', 'size', 'value', 'reversal_short_term', 'volatility']})

Generate a number of tear sheets that are useful for analyzing a strategy’s performance.

  • Fetches benchmarks if needed.

  • Creates tear sheets for returns, and significant events.

    If possible, also creates tear sheets for position analysis and transaction analysis.

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • Time series with decimal returns.

  • Example:

    2015-07-16 -0.012143 2015-07-17 0.045350 2015-07-20 0.030957 2015-07-21 0.004902

positionspd.DataFrame, optional
Daily net position values.
  • Time series of dollar amount invested in each position and cash.

  • Days where stocks are not held can be represented by 0 or NaN.

  • Non-working capital is labelled ‘cash’

  • Example:

    index ‘AAPL’ ‘MSFT’ cash 2004-01-09 13939.3800 -14012.9930 711.5585 2004-01-12 14492.6300 -14624.8700 27.1821 2004-01-13 -13853.2800 13653.6400 -43.6375

transactionspd.DataFrame, optional

Executed trade volumes and fill prices. - 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’

market_datapd.DataFrame, optional

Daily market_data - DataFrame has a multi-index index, one level is dates and another is market_data contains volume & price, equities as columns

slippageint/float, optional

Basis points of slippage to apply to returns before generating tearsheet stats and plots. If a value is provided, slippage parameter sweep plots will be generated from the unadjusted returns. Transactions and positions must also be passed. - See txn.adjust_returns_for_slippage for more details.

live_start_datedatetime, optional

The point in time when the strategy began live trading, after its backtest period. This datetime should be normalized.

hide_positionsbool, optional

If True, will not output any symbol names.

round_trips: boolean, optional

If True, causes the generation of a round trip tear sheet.

sector_mappingsdict or pd.Series, optional

Security identifier to sector mapping. Security ids as keys, sectors as values.

estimate_intraday: boolean or str, optional

Instead of using the end-of-day positions, use the point in the day where we have the most $ invested. This will adjust positions to better approximate and represent how an intraday strategy behaves. By default, this is ‘infer’, and an attempt will be made to detect an intraday strategy. Specifying this value will prevent detection.

cone_stdfloat, 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

  • The cone is a normal distribution with this standard deviation

    centered around a linear regression.

bootstrapboolean (optional)

Whether to perform bootstrap analysis for the performance metrics. Takes a few minutes longer.

turnover_denomstr

Either AGB or portfolio_value, default AGB. - See full explanation in txn.get_turnover.

factor_returnspd.Dataframe, optional

Returns by factor, with date as index and factors as columns

factor_loadingspd.Dataframe, optional

Factor loadings for all days in the date range, with date and ticker as index, and factors as columns.

pos_in_dollarsboolean, optional

indicates whether positions is in dollars

header_rowsdict or OrderedDict, optional

Extra rows to display at the top of the perf stats table.

set_contextboolean, optional
If True, set default plotting style context.
  • See plotting.context().

factor_partitionsdict, optional

dict specifying how factors should be separated in perf attrib factor returns and risk exposures plots - See create_perf_attrib_tear_sheet().

pyfolio.tears.create_interesting_times_tear_sheet(returns, benchmark_rets=None, periods=None, legend_loc='best', return_fig=False)

Generate a number of returns plots around interesting points in time, like the flash crash and 9/11.

Plots: returns around the dotcom bubble burst, Lehmann Brothers’ failure, 9/11, US downgrade and EU debt crisis, Fukushima meltdown, US housing bubble burst, EZB IR, Great Recession (August 2007, March and September of 2008, Q1 & Q2 2009), flash crash, April and October 2014.

benchmark_rets must be passed, as it is meaningless to analyze performance during interesting times without some benchmark to refer to.

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in create_full_tear_sheet.

benchmark_retspd.Series
Daily noncumulative returns of the benchmark.
  • This is in the same style as returns.

periods: dict or OrderedDict, optional

historical event dates that may have had significant impact on markets

legend_locplt.legend_loc, optional

The legend’s location.

return_figboolean, optional

If True, returns the figure that was plotted on.

pyfolio.tears.create_perf_attrib_tear_sheet(returns, positions, factor_returns, factor_loadings, transactions=None, pos_in_dollars=True, factor_partitions={'sector': ['basic_materials', 'consumer_cyclical', 'financial_services', 'real_estate', 'consumer_defensive', 'health_care', 'utilities', 'communication_services', 'energy', 'industrials', 'technology'], 'style': ['momentum', 'size', 'value', 'reversal_short_term', 'volatility']}, return_fig=False)

Generate plots and tables for analyzing a strategy’s performance.

Parameters
returnspd.Series

Returns for each day in the date range.

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.

factor_returnspd.DataFrame

Returns by factor, with date as index and factors as columns

factor_loadingspd.DataFrame

Factor loadings for all days in the date range, with date and ticker as index, and factors as columns.

transactionspd.DataFrame, optional
Prices and amounts of executed trades. One row per trade.
  • See full explanation in create_full_tear_sheet.

  • Default is None.

pos_in_dollarsboolean, optional

Flag indicating whether positions are in dollars or percentages If True, positions are in dollars.

factor_partitionsdict

dict specifying how factors should be separated in factor returns and risk exposures plots - Example:

{‘style’: [‘momentum’, ‘size’, ‘value’, …],

‘sector’: [‘technology’, ‘materials’, … ]}

return_figboolean, optional

If True, returns the figure that was plotted on.

pyfolio.tears.create_position_tear_sheet(returns, positions, show_and_plot_top_pos=2, hide_positions=False, sector_mappings=None, transactions=None, estimate_intraday='infer', return_fig=False)

Generate a number of plots for analyzing a strategy’s positions and holdings.

  • Plots: gross leverage, exposures, top positions, and holdings.

  • Will also print the top positions held.

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in create_full_tear_sheet.

positionspd.DataFrame
Daily net position values.
  • See full explanation in create_full_tear_sheet.

show_and_plot_top_posint, optional

By default, this is 2, and both prints and plots the top 10 positions. If this is 0, it will only plot; if 1, it will only print.

hide_positionsbool, optional

If True, will not output any symbol names. Overrides show_and_plot_top_pos to 0 to suppress text output.

sector_mappingsdict or pd.Series, optional

Security identifier to sector mapping. Security ids as keys, sectors as values.

transactionspd.DataFrame, optional
Prices and amounts of executed trades. One row per trade.
  • See full explanation in create_full_tear_sheet.

estimate_intraday: boolean or str, optional

Approximate returns for intraday strategies. See description in create_full_tear_sheet.

return_figboolean, optional

If True, returns the figure that was plotted on.

pyfolio.tears.create_returns_tear_sheet(returns, positions=None, transactions=None, live_start_date=None, cone_std=(1.0, 1.5, 2.0), benchmark_rets=None, bootstrap=False, turnover_denom='AGB', header_rows=None, return_fig=False)

Generate a number of plots for analyzing a strategy’s returns.

  • Fetches benchmarks, then creates the plots on a single figure.

  • Plots: rolling returns (with cone), rolling beta, rolling sharpe,

    rolling Fama-French risk factors, drawdowns, underwater plot, monthly and annual return plots, daily similarity plots, and return quantile box plot.

  • Will also print the start and end dates of the strategy,

    performance statistics, drawdown periods, and the return range.

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in create_full_tear_sheet.

positionspd.DataFrame, optional
Daily net position values.
  • See full explanation in create_full_tear_sheet.

transactionspd.DataFrame, optional

Executed trade volumes and fill prices. - See full explanation in create_full_tear_sheet.

live_start_datedatetime, optional

The point in time when the strategy began live trading, after its backtest period.

cone_stdfloat, 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

  • The cone is a normal distribution with this standard deviation

    centered around a linear regression.

benchmark_retspd.Series, optional
Daily noncumulative returns of the benchmark.
  • This is in the same style as returns.

bootstrapboolean, optional

Whether to perform bootstrap analysis for the performance metrics. Takes a few minutes longer.

turnover_denomstr, optional

Either AGB or portfolio_value, default AGB. - See full explanation in txn.get_turnover.

header_rowsdict or OrderedDict, optional

Extra rows to display at the top of the perf stats table.

return_figboolean, optional

If True, returns the figure that was plotted on.

pyfolio.tears.create_round_trip_tear_sheet(returns, positions, transactions, sector_mappings=None, estimate_intraday='infer', return_fig=False)

Generate a number of figures and plots describing the duration, frequency, and profitability of trade “round trips.” A round trip is started when a new long or short position is opened and is only completed when the number of shares in that position returns to or crosses zero.

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in create_full_tear_sheet.

positionspd.DataFrame
Daily net position values.
  • See full explanation in create_full_tear_sheet.

transactionspd.DataFrame
Prices and amounts of executed trades. One row per trade.
  • See full explanation in create_full_tear_sheet.

sector_mappingsdict or pd.Series, optional

Security identifier to sector mapping. Security ids as keys, sectors as values.

estimate_intraday: boolean or str, optional

Approximate returns for intraday strategies. See description in create_full_tear_sheet.

return_figboolean, optional

If True, returns the figure that was plotted on.

pyfolio.tears.create_simple_tear_sheet(returns, positions=None, transactions=None, benchmark_rets=None, slippage=None, estimate_intraday='infer', live_start_date=None, turnover_denom='AGB', header_rows=None)

Simpler version of create_full_tear_sheet; generates summary performance statistics and important plots as a single image.

  • Plots: cumulative returns, rolling beta, rolling Sharpe, underwater,

    exposure, top 10 holdings, total holdings, long/short holdings, daily turnover, transaction time distribution.

  • Never accept market_data input (market_data = None)

  • Never accept sector_mappings input (sector_mappings = None)

  • Never perform bootstrap analysis (bootstrap = False)

  • Never hide posistions on top 10 holdings plot (hide_positions = False)

  • Always use default cone_std (cone_std = (1.0, 1.5, 2.0))

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • Time series with decimal returns.

  • Example:

    2015-07-16 -0.012143 2015-07-17 0.045350 2015-07-20 0.030957 2015-07-21 0.004902

positionspd.DataFrame, optional
Daily net position values.
  • Time series of dollar amount invested in each position and cash.

  • Days where stocks are not held can be represented by 0 or NaN.

  • Non-working capital is labelled ‘cash’

  • Example:

    index ‘AAPL’ ‘MSFT’ cash 2004-01-09 13939.3800 -14012.9930 711.5585 2004-01-12 14492.6300 -14624.8700 27.1821 2004-01-13 -13853.2800 13653.6400 -43.6375

transactionspd.DataFrame, optional

Executed trade volumes and fill prices. - 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’

benchmark_retspd.Series, optional

Daily returns of the benchmark, noncumulative.

slippageint/float, optional

Basis points of slippage to apply to returns before generating tearsheet stats and plots. If a value is provided, slippage parameter sweep plots will be generated from the unadjusted returns. Transactions and positions must also be passed. - See txn.adjust_returns_for_slippage for more details.

live_start_datedatetime, optional

The point in time when the strategy began live trading, after its backtest period. This datetime should be normalized.

turnover_denomstr, optional

Either AGB or portfolio_value, default AGB. - See full explanation in txn.get_turnover.

header_rowsdict or OrderedDict, optional

Extra rows to display at the top of the perf stats table.

set_contextboolean, optional

If True, set default plotting style context.

pyfolio.tears.create_txn_tear_sheet(returns, positions, transactions, turnover_denom='AGB', unadjusted_returns=None, estimate_intraday='infer', return_fig=False)

Generate a number of plots for analyzing a strategy’s transactions.

Plots: turnover, daily volume, and a histogram of daily volume.

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in create_full_tear_sheet.

positionspd.DataFrame
Daily net position values.
  • See full explanation in create_full_tear_sheet.

transactionspd.DataFrame
Prices and amounts of executed trades. One row per trade.
  • See full explanation in create_full_tear_sheet.

turnover_denomstr, optional

Either AGB or portfolio_value, default AGB. - See full explanation in txn.get_turnover.

unadjusted_returnspd.Series, optional

Daily unadjusted returns of the strategy, noncumulative. Will plot additional swippage sweep analysis.

  • See pyfolio.plotting.plot_swippage_sleep and pyfolio.plotting.plot_slippage_sensitivity

estimate_intraday: boolean or str, optional

Approximate returns for intraday strategies. See description in create_full_tear_sheet.

return_figboolean, optional

If True, returns the figure that was plotted on.

pyfolio.tears.timer(msg_body, previous_time)

Time Series Metrics

The module pyfolio.timeseries provides performance and risk metrics.

pyfolio.timeseries.aggregate_returns(returns, convert_to)

Aggregates returns by week, month, or year.

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
convert_tostr

Can be ‘weekly’, ‘monthly’, or ‘yearly’.

Returns
pd.Series

Aggregated returns.

pyfolio.timeseries.alpha(returns, factor_returns)

Calculates annualized alpha.

Parameters
returnspd.Series

Daily returns of the strategy, noncumulative. - See full explanation in cum_returns().

factor_returnspd.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.

Returns
float

Alpha.

pyfolio.timeseries.alpha_beta(returns, factor_returns)

Calculates both alpha and beta.

Parameters
returnspd.Series

Daily returns of the strategy, noncumulative. - See full explanation in cum_returns().

factor_returnspd.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.

Returns
float

Alpha.

float

Beta.

pyfolio.timeseries.annual_return(returns, period='daily')

Determines the mean annual growth rate of returns.

Parameters
returnspd.Series

Periodic returns of the strategy, noncumulative. - See full explanation in cum_returns().

periodstr, optional

Defines the periodicity of the ‘returns’ data for purposes of annualizing. Can be ‘monthly’, ‘weekly’, or ‘daily’. - Defaults to ‘daily’.

Returns
float

Annual Return as CAGR (Compounded Annual Growth Rate).

pyfolio.timeseries.annual_volatility(returns, period='daily')

Determines the annual volatility of a strategy.

Parameters
returnspd.Series

Periodic returns of the strategy, noncumulative. - See full explanation in cum_returns().

periodstr, optional

Defines the periodicity of the ‘returns’ data for purposes of annualizing volatility. Can be ‘monthly’ or ‘weekly’ or ‘daily’. - Defaults to ‘daily’.

Returns
float

Annual volatility.

pyfolio.timeseries.beta(returns, factor_returns)

Calculates beta.

Parameters
returnspd.Series

Daily returns of the strategy, noncumulative. - See full explanation in cum_returns().

factor_returnspd.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.

Returns
float

Beta.

pyfolio.timeseries.calc_bootstrap(func, returns, *args, **kwargs)

Performs a bootstrap analysis on a user-defined function returning a summary statistic.

Parameters
funcfunction

Function that either takes a single array (commonly returns) or two arrays (commonly returns and factor returns) and returns a single value (commonly a summary statistic). Additional args and kwargs are passed as well.

returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in tears.create_full_tear_sheet.

factor_returnspd.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.

n_samplesint, optional

Number of bootstrap samples to draw. Default is 1000. Increasing this will lead to more stable / accurate estimates.

Returns
numpy.ndarray

Bootstrapped sampling distribution of passed in func.

pyfolio.timeseries.calc_distribution_stats(x)

Calculate various summary statistics of data.

Parameters
xnumpy.ndarray or pandas.Series

Array to compute summary statistics for.

Returns
pandas.Series

Series containing mean, median, std, as well as 5, 25, 75 and 95 percentiles of passed in values.

pyfolio.timeseries.calmar_ratio(returns, period='daily')

Determines the Calmar ratio, or drawdown ratio, of a strategy.

Parameters
returnspd.Series

Daily returns of the strategy, noncumulative. - See full explanation in cum_returns().

periodstr, optional

Defines the periodicity of the ‘returns’ data for purposes of annualizing. Can be ‘monthly’, ‘weekly’, or ‘daily’. - Defaults to ‘daily’.

Returns
float

Calmar ratio (drawdown ratio) as float. Returns np.nan if there is no calmar ratio.

pyfolio.timeseries.common_sense_ratio(returns)

Common sense ratio is the multiplication of the tail ratio and the Gain-to-Pain-Ratio – sum(profits) / sum(losses).

See http://bit.ly/1ORzGBk for more information on motivation of this metric.

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in tears.create_full_tear_sheet.

Returns
float

common sense ratio

pyfolio.timeseries.cum_returns(returns, starting_value=0)

Compute cumulative returns from simple returns.

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in tears.create_full_tear_sheet.

starting_valuefloat, optional

The starting returns (default 1).

Returns
pandas.Series

Series of cumulative returns.

Notes

For increased numerical accuracy, convert input to log returns where it is possible to sum instead of multiplying.

pyfolio.timeseries.downside_risk(returns, required_return=0, period='daily')

Determines the downside deviation below a threshold

Parameters
returnspd.Series or pd.DataFrame

Daily returns of the strategy, noncumulative. - See full explanation in cum_returns().

required_return: float / series

minimum acceptable return

periodstr, optional

Defines the periodicity of the ‘returns’ data for purposes of annualizing. Can be ‘monthly’, ‘weekly’, or ‘daily’. - Defaults to ‘daily’.

Returns
depends on input type
series ==> float
DataFrame ==> np.array

Annualized downside deviation

pyfolio.timeseries.extract_interesting_date_ranges(returns, periods=None)

Extracts returns based on interesting events. See gen_date_range_interesting.

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in tears.create_full_tear_sheet.

Returns
rangesOrderedDict

Date ranges, with returns, of all valid events.

pyfolio.timeseries.forecast_cone_bootstrap(is_returns, num_days, cone_std=(1.0, 1.5, 2.0), starting_value=1, num_samples=1000, random_seed=None)

Determines the upper and lower bounds of an n standard deviation cone of forecasted cumulative returns. Future cumulative mean and standard devation are computed by repeatedly sampling from the in-sample daily returns (i.e. bootstrap). This cone is non-parametric, meaning it does not assume that returns are normally distributed.

Parameters
is_returnspd.Series
In-sample daily returns of the strategy, noncumulative.
  • See full explanation in tears.create_full_tear_sheet.

num_daysint

Number of days to project the probability cone forward.

cone_stdint, float, or list of int/float

Number of standard devations to use in the boundaries of the cone. If multiple values are passed, cone bounds will be generated for each value.

starting_valueint or float

Starting value of the out of sample period.

num_samplesint

Number of samples to draw from the in-sample daily returns. Each sample will be an array with length num_days. A higher number of samples will generate a more accurate bootstrap cone.

random_seedint

Seed for the pseudorandom number generator used by the pandas sample method.

Returns
pd.DataFrame

Contains upper and lower cone boundaries. Column names are strings corresponding to the number of standard devations above (positive) or below (negative) the projected mean cumulative returns.

pyfolio.timeseries.gen_drawdown_table(returns, top=10)

Places top drawdowns in a table.

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in tears.create_full_tear_sheet.

topint, optional

The amount of top drawdowns to find (default 10).

Returns
df_drawdownspd.DataFrame

Information about top drawdowns.

pyfolio.timeseries.get_max_drawdown(returns)

Determines the maximum drawdown of a strategy.

Parameters
returnspd.Series

Daily returns of the strategy, noncumulative. - See full explanation in cum_returns().

Returns
float

Maximum drawdown.

pyfolio.timeseries.get_max_drawdown_underwater(underwater)

Determines peak, valley, and recovery dates given an ‘underwater’ DataFrame.

An underwater DataFrame is a DataFrame that has precomputed rolling drawdown.

Parameters
underwaterpd.Series

Underwater returns (rolling drawdown) of a strategy.

Returns
peakdatetime

The maximum drawdown’s peak.

valleydatetime

The maximum drawdown’s valley.

recoverydatetime

The maximum drawdown’s recovery.

pyfolio.timeseries.get_top_drawdowns(returns, top=10)

Finds top drawdowns, sorted by drawdown amount.

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in tears.create_full_tear_sheet.

topint, optional

The amount of top drawdowns to find (default 10).

Returns
drawdownslist

List of drawdown peaks, valleys, and recoveries. See get_max_drawdown.

pyfolio.timeseries.gross_lev(positions)

Calculates the gross leverage of a strategy.

Parameters
positionspd.DataFrame
Daily net position values.
  • See full explanation in tears.create_full_tear_sheet.

Returns
pd.Series

Gross leverage.

pyfolio.timeseries.max_drawdown(returns)

Determines the maximum drawdown of a strategy.

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in tears.create_full_tear_sheet.

Returns
float

Maximum drawdown.

pyfolio.timeseries.normalize(returns, starting_value=1)

Normalizes a returns timeseries based on the first value.

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in tears.create_full_tear_sheet.

starting_valuefloat, optional

The starting returns (default 1).

Returns
pd.Series

Normalized returns.

pyfolio.timeseries.omega_ratio(returns, annual_return_threshhold=0.0)

Determines the Omega ratio of a strategy.

Parameters
returnspd.Series

Daily returns of the strategy, noncumulative. - See full explanation in cum_returns().

annual_return_thresholdfloat, optional

Minimum acceptable return of the investor. Annual threshold over which returns are considered positive or negative. It is converted to a value appropriate for the period of the returns for this ratio. E.g. An annual minimum acceptable return of 100 translates to a daily minimum acceptable return of 0.01848.

(1 + 100) ** (1. / 252) - 1 = 0.01848

Daily returns must exceed this value to be considered positive. The daily return yields the desired annual return when compounded over the average number of business days in a year.

(1 + 0.01848) ** 252 - 1 = 99.93

  • Defaults to 0.0

Returns
float

Omega ratio.

pyfolio.timeseries.perf_stats(returns, factor_returns=None, positions=None, transactions=None, turnover_denom='AGB')

Calculates various performance metrics of a strategy, for use in plotting.show_perf_stats.

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in tears.create_full_tear_sheet.

factor_returnspd.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.

  • If None, do not compute alpha, beta, and information ratio.

positionspd.DataFrame
Daily net position values.
  • See full explanation in tears.create_full_tear_sheet.

transactionspd.DataFrame

Prices and amounts of executed trades. One row per trade. - See full explanation in tears.create_full_tear_sheet.

turnover_denomstr

Either AGB or portfolio_value, default AGB. - See full explanation in txn.get_turnover.

Returns
pd.Series

Performance metrics.

pyfolio.timeseries.perf_stats_bootstrap(returns, factor_returns=None, return_stats=True, **kwargs)

Calculates various bootstrapped performance metrics of a strategy.

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in tears.create_full_tear_sheet.

factor_returnspd.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.

  • If None, do not compute alpha, beta, and information ratio.

return_statsboolean (optional)

If True, returns a DataFrame of mean, median, 5 and 95 percentiles for each perf metric. If False, returns a DataFrame with the bootstrap samples for each perf metric.

Returns
pd.DataFrame

if return_stats is True: - Distributional statistics of bootstrapped sampling distribution of performance metrics. if return_stats is False: - Bootstrap samples for each performance metric.

pyfolio.timeseries.rolling_beta(returns, factor_returns, rolling_window=126)

Determines the rolling beta of a strategy.

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in tears.create_full_tear_sheet.

factor_returnspd.Series or pd.DataFrame

Daily noncumulative returns of the benchmark factor to which betas are computed. Usually a benchmark such as market returns.

  • If DataFrame is passed, computes rolling beta for each column.

  • This is in the same style as returns.

rolling_windowint, optional

The size of the rolling window, in days, over which to compute beta (default 6 months).

Returns
pd.Series

Rolling beta.

pyfolio.timeseries.rolling_regression(returns, factor_returns, rolling_window=126, nan_threshold=0.1)

Computes rolling factor betas using a multivariate linear regression (separate linear regressions is problematic because the factors may be confounded).

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in tears.create_full_tear_sheet.

factor_returnspd.DataFrame

Daily noncumulative returns of the benchmark factor to which betas are computed. Usually a benchmark such as market returns.

  • Computes rolling beta for each column.

  • This is in the same style as returns.

rolling_windowint, optional

The days window over which to compute the beta. Defaults to 6 months.

nan_thresholdfloat, optional

If there are more than this fraction of NaNs, the rolling regression for the given date will be skipped.

Returns
pandas.DataFrame

DataFrame containing rolling beta coefficients to SMB, HML and UMD

pyfolio.timeseries.rolling_sharpe(returns, rolling_sharpe_window)

Determines the rolling Sharpe ratio of a strategy.

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in tears.create_full_tear_sheet.

rolling_sharpe_windowint

Length of rolling window, in days, over which to compute.

Returns
pd.Series

Rolling Sharpe ratio.

pyfolio.timeseries.rolling_volatility(returns, rolling_vol_window)

Determines the rolling volatility of a strategy.

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in tears.create_full_tear_sheet.

rolling_vol_windowint

Length of rolling window, in days, over which to compute.

Returns
pd.Series

Rolling volatility.

pyfolio.timeseries.sharpe_ratio(returns, risk_free=0, period='daily')

Determines the Sharpe ratio of a strategy.

Parameters
returnspd.Series

Daily returns of the strategy, noncumulative. - See full explanation in cum_returns().

risk_freeint, float

Constant risk-free return throughout the period.

periodstr, optional

Defines the periodicity of the ‘returns’ data for purposes of annualizing. Can be ‘monthly’, ‘weekly’, or ‘daily’. - Defaults to ‘daily’.

Returns
float

Sharpe ratio.

np.nan

If insufficient length of returns or if if adjusted returns are 0.

pyfolio.timeseries.simulate_paths(is_returns, num_days, starting_value=1, num_samples=1000, random_seed=None)

Gnerate alternate paths using available values from in-sample returns.

Parameters
is_returnspandas.core.frame.DataFrame

Non-cumulative in-sample returns.

num_daysint

Number of days to project the probability cone forward.

starting_valueint or float

Starting value of the out of sample period.

num_samplesint

Number of samples to draw from the in-sample daily returns. Each sample will be an array with length num_days. A higher number of samples will generate a more accurate bootstrap cone.

random_seedint

Seed for the pseudorandom number generator used by the pandas sample method.

Returns
samplesnumpy.ndarray
pyfolio.timeseries.sortino_ratio(returns, required_return=0, period='daily')

Determines the Sortino ratio of a strategy.

Parameters
returnspd.Series or pd.DataFrame

Daily returns of the strategy, noncumulative. - See full explanation in cum_returns().

required_return: float / series

minimum acceptable return

periodstr, optional

Defines the periodicity of the ‘returns’ data for purposes of annualizing. Can be ‘monthly’, ‘weekly’, or ‘daily’. - Defaults to ‘daily’.

Returns
depends on input type
series ==> float
DataFrame ==> np.array

Annualized Sortino ratio.

pyfolio.timeseries.stability_of_timeseries(returns)

Determines R-squared of a linear fit to the cumulative log returns. Computes an ordinary least squares linear fit, and returns R-squared.

Parameters
returnspd.Series

Daily returns of the strategy, noncumulative. - See full explanation in cum_returns().

Returns
float

R-squared.

pyfolio.timeseries.summarize_paths(samples, cone_std=(1.0, 1.5, 2.0), starting_value=1.0)

Gnerate the upper and lower bounds of an n standard deviation cone of forecasted cumulative returns.

Parameters
samplesnumpy.ndarray

Alternative paths, or series of possible outcomes.

cone_stdlist of int/float

Number of standard devations to use in the boundaries of the cone. If multiple values are passed, cone bounds will be generated for each value.

Returns
samplespandas.core.frame.DataFrame
pyfolio.timeseries.tail_ratio(returns)

Determines the ratio between the right (95%) and left tail (5%).

For example, a ratio of 0.25 means that losses are four times as bad as profits.

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
Returns
float

tail ratio

pyfolio.timeseries.value_at_risk(returns, period=None, sigma=2.0)

Get value at risk (VaR).

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in tears.create_full_tear_sheet.

periodstr, optional

Period over which to calculate VaR. Set to ‘weekly’, ‘monthly’, or ‘yearly’, otherwise defaults to period of returns (typically daily).

sigmafloat, optional

Standard deviations of VaR, default 2.

pyfolio.timeseries.var_cov_var_normal(P, c, mu=0, sigma=1)

Variance-covariance calculation of daily Value-at-Risk in a portfolio.

Parameters
Pfloat

Portfolio value.

cfloat

Confidence level.

mufloat, optional

Mean.

Returns
float

Variance-covariance.

Performance Attribution:

The module pyfolio.perf_attrib provides performance and risk metrics.

pyfolio.perf_attrib.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_loadingspd.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_positionsbool

Flag indicating whether positions should be converted to long format.

pos_in_dollarsbool

Flag indicating whether positions are in dollars or percentages If True, positions are in dollars.

Returns
risk_exposures_portfoliopd.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

pyfolio.perf_attrib.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.

pyfolio.perf_attrib.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
returnspd.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_returnspd.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_loadingspd.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

transactionspd.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_dollarsbool

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_portfoliopd.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_attributionpd.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

pyfolio.perf_attrib.plot_alpha_returns(alpha_returns, ax=None)

Plot histogram of daily multi-factor alpha returns (specific returns).

Parameters
alpha_returnspd.Series

series of daily alpha returns indexed by datetime

axmatplotlib.axes.Axes

axes on which plots are made. if None, current axes will be used

Returns
axmatplotlib.axes.Axes
pyfolio.perf_attrib.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_datapd.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

axmatplotlib.axes.Axes

axes on which plots are made. if None, current axes will be used

titlestr, optional

title of plot

Returns
axmatplotlib.axes.Axes
pyfolio.perf_attrib.plot_returns(perf_attrib_data, cost=None, ax=None)

Plot total, specific, and common returns.

Parameters
perf_attrib_datapd.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

costpd.Series, optional

if present, gets subtracted from perf_attrib_data[‘total_returns’], and gets plotted separately

axmatplotlib.axes.Axes

axes on which plots are made. if None, current axes will be used

Returns
axmatplotlib.axes.Axes
pyfolio.perf_attrib.plot_risk_exposures(exposures, ax=None, title='Daily risk factor exposures')
Parameters
exposurespd.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

axmatplotlib.axes.Axes

axes on which plots are made. if None, current axes will be used

Returns
axmatplotlib.axes.Axes
pyfolio.perf_attrib.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.

Plotting Functions

The module pyfolio.plotting facilitates the visualization of performance metrics.

pyfolio.plotting.customize(func)

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

pyfolio.plotting.plot_annual_returns(returns, ax=None, **kwargs)

Plots a bar graph of returns by year.

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in tears.create_full_tear_sheet.

axmatplotlib.Axes, optional

Axes upon which to plot.

**kwargs, optional

Passed to plotting function.

Returns
axmatplotlib.Axes

The axes that were plotted on.

pyfolio.plotting.plot_capacity_sweep(returns, transactions, market_data, bt_starting_capital, min_pv=100000, max_pv=300000000, step_size=1000000, ax=None)
pyfolio.plotting.plot_cones(name, bounds, oos_returns, num_samples=1000, ax=None, cone_std=(1.0, 1.5, 2.0), random_seed=None, num_strikes=3)

Plots the upper and lower bounds of an n standard deviation cone of forecasted cumulative returns. Redraws a new cone when cumulative returns fall outside of last cone drawn.

Parameters
namestr

Account name to be used as figure title.

boundspandas.core.frame.DataFrame

Contains upper and lower cone boundaries. Column names are strings corresponding to the number of standard devations above (positive) or below (negative) the projected mean cumulative returns.

oos_returnspandas.core.frame.DataFrame

Non-cumulative out-of-sample returns.

num_samplesint

Number of samples to draw from the in-sample daily returns. Each sample will be an array with length num_days. A higher number of samples will generate a more accurate bootstrap cone.

axmatplotlib.Axes, optional

Axes upon which to plot.

cone_stdlist of int/float

Number of standard devations to use in the boundaries of the cone. If multiple values are passed, cone bounds will be generated for each value.

random_seedint

Seed for the pseudorandom number generator used by the pandas sample method.

num_strikesint

Upper limit for number of cones drawn. Can be anything from 0 to 3.

Returns
Returns are either an ax or fig option, but not both. If a
matplotlib.Axes instance is passed in as ax, then it will be modified
and returned. This allows for users to plot interactively in jupyter
notebook. When no ax object is passed in, a matplotlib.figure instance
is generated and returned. This figure can then be used to save
the plot as an image without viewing it.
axmatplotlib.Axes

The axes that were plotted on.

figmatplotlib.figure

The figure instance which contains all the plot elements.

pyfolio.plotting.plot_daily_turnover_hist(transactions, positions, turnover_denom='AGB', ax=None, **kwargs)

Plots a histogram of daily turnover rates.

Parameters
transactionspd.DataFrame
Prices and amounts of executed trades. One row per trade.
  • See full explanation in tears.create_full_tear_sheet.

positionspd.DataFrame
Daily net position values.
  • See full explanation in tears.create_full_tear_sheet.

turnover_denomstr, optional

Either AGB or portfolio_value, default AGB. - See full explanation in txn.get_turnover.

axmatplotlib.Axes, optional

Axes upon which to plot.

**kwargs, optional

Passed to seaborn plotting function.

Returns
axmatplotlib.Axes

The axes that were plotted on.

pyfolio.plotting.plot_daily_volume(returns, transactions, ax=None, **kwargs)

Plots trading volume per day vs. date.

Also displays all-time daily average.

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in tears.create_full_tear_sheet.

transactionspd.DataFrame
Prices and amounts of executed trades. One row per trade.
  • See full explanation in tears.create_full_tear_sheet.

axmatplotlib.Axes, optional

Axes upon which to plot.

**kwargs, optional

Passed to plotting function.

Returns
axmatplotlib.Axes

The axes that were plotted on.

pyfolio.plotting.plot_drawdown_periods(returns, top=10, ax=None, **kwargs)

Plots cumulative returns highlighting top drawdown periods.

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in tears.create_full_tear_sheet.

topint, optional

Amount of top drawdowns periods to plot (default 10).

axmatplotlib.Axes, optional

Axes upon which to plot.

**kwargs, optional

Passed to plotting function.

Returns
axmatplotlib.Axes

The axes that were plotted on.

pyfolio.plotting.plot_drawdown_underwater(returns, ax=None, **kwargs)

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

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in tears.create_full_tear_sheet.

axmatplotlib.Axes, optional

Axes upon which to plot.

**kwargs, optional

Passed to plotting function.

Returns
axmatplotlib.Axes

The axes that were plotted on.

pyfolio.plotting.plot_exposures(returns, positions, ax=None, **kwargs)

Plots a cake chart of the long and short exposure.

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in tears.create_full_tear_sheet.

positions_allocpd.DataFrame

Portfolio allocation of positions. See pos.get_percent_alloc.

axmatplotlib.Axes, optional

Axes upon which to plot.

**kwargs, optional

Passed to plotting function.

Returns
axmatplotlib.Axes

The axes that were plotted on.

pyfolio.plotting.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
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in tears.create_full_tear_sheet.

positionspd.DataFrame
Daily net position values.
  • See full explanation in create_full_tear_sheet.

axmatplotlib.Axes, optional

Axes upon which to plot.

**kwargs, optional

Passed to plotting function.

Returns
axmatplotlib.Axes

The axes that were plotted on.

pyfolio.plotting.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
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in tears.create_full_tear_sheet.

positionspd.DataFrame, optional
Daily net position values.
  • See full explanation in tears.create_full_tear_sheet.

legend_locmatplotlib.loc, optional

The location of the legend on the plot.

axmatplotlib.Axes, optional

Axes upon which to plot.

**kwargs, optional

Passed to plotting function.

Returns
axmatplotlib.Axes

The axes that were plotted on.

pyfolio.plotting.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
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in tears.create_full_tear_sheet.

positionspd.DataFrame, optional
Daily net position values.
  • See full explanation in tears.create_full_tear_sheet.

legend_locmatplotlib.loc, optional

The location of the legend on the plot.

axmatplotlib.Axes, optional

Axes upon which to plot.

**kwargs, optional

Passed to plotting function.

Returns
axmatplotlib.Axes

The axes that were plotted on.

pyfolio.plotting.plot_max_median_position_concentration(positions, ax=None, **kwargs)

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

Parameters
positionspd.DataFrame

The positions that the strategy takes over time.

axmatplotlib.Axes, optional

Axes upon which to plot.

Returns
axmatplotlib.Axes

The axes that were plotted on.

pyfolio.plotting.plot_monthly_returns_dist(returns, ax=None, **kwargs)

Plots a distribution of monthly returns.

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in tears.create_full_tear_sheet.

axmatplotlib.Axes, optional

Axes upon which to plot.

**kwargs, optional

Passed to plotting function.

Returns
axmatplotlib.Axes

The axes that were plotted on.

pyfolio.plotting.plot_monthly_returns_heatmap(returns, ax=None, **kwargs)

Plots a heatmap of returns by month.

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in tears.create_full_tear_sheet.

axmatplotlib.Axes, optional

Axes upon which to plot.

**kwargs, optional

Passed to seaborn plotting function.

Returns
axmatplotlib.Axes

The axes that were plotted on.

pyfolio.plotting.plot_monthly_returns_timeseries(returns, ax=None, **kwargs)

Plots monthly returns as a timeseries.

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in tears.create_full_tear_sheet.

axmatplotlib.Axes, optional

Axes upon which to plot.

**kwargs, optional

Passed to seaborn plotting function.

Returns
axmatplotlib.Axes

The axes that were plotted on.

pyfolio.plotting.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
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in tears.create_full_tear_sheet.

factor_returnspd.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.

axmatplotlib.Axes, optional

Axes upon which to plot.

Returns
axmatplotlib.Axes

The axes that were plotted on.

pyfolio.plotting.plot_prob_profit_trade(round_trips, ax=None)

Plots a probability distribution for the event of making a profitable trade.

Parameters
round_tripspd.DataFrame

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

axmatplotlib.Axes, optional

Axes upon which to plot.

Returns
axmatplotlib.Axes

The axes that were plotted on.

pyfolio.plotting.plot_return_quantiles(returns, live_start_date=None, ax=None, **kwargs)

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

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in tears.create_full_tear_sheet.

live_start_datedatetime, optional

The point in time when the strategy began live trading, after its backtest period.

axmatplotlib.Axes, optional

Axes upon which to plot.

**kwargs, optional

Passed to seaborn plotting function.

Returns
axmatplotlib.Axes

The axes that were plotted on.

pyfolio.plotting.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
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in tears.create_full_tear_sheet.

live_start_datedatetime, optional

The date when the strategy began live trading, after its backtest period. This date should be normalized.

axmatplotlib.Axes, optional

Axes upon which to plot.

**kwargs, optional

Passed to plotting function.

Returns
axmatplotlib.Axes

The axes that were plotted on.

pyfolio.plotting.plot_rolling_beta(returns, factor_returns, legend_loc='best', ax=None, **kwargs)

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

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in tears.create_full_tear_sheet.

factor_returnspd.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_locmatplotlib.loc, optional

The location of the legend on the plot.

axmatplotlib.Axes, optional

Axes upon which to plot.

**kwargs, optional

Passed to plotting function.

Returns
axmatplotlib.Axes

The axes that were plotted on.

pyfolio.plotting.plot_rolling_returns(returns, factor_returns=None, live_start_date=None, logy=False, cone_std=None, legend_loc='best', volatility_match=False, cone_function=<function 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
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in tears.create_full_tear_sheet.

factor_returnspd.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_datedatetime, optional

The date when the strategy began live trading, after its backtest period. This date should be normalized.

logybool, optional

Whether to log-scale the y-axis.

cone_stdfloat, 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_locmatplotlib.loc, optional

The location of the legend on the plot.

volatility_matchbool, 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_functionfunction, 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.

axmatplotlib.Axes, optional

Axes upon which to plot.

**kwargs, optional

Passed to plotting function.

Returns
axmatplotlib.Axes

The axes that were plotted on.

pyfolio.plotting.plot_rolling_sharpe(returns, factor_returns=None, rolling_window=126, legend_loc='best', ax=None, **kwargs)

Plots the rolling Sharpe ratio versus date.

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in tears.create_full_tear_sheet.

factor_returnspd.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_windowint, optional

The days window over which to compute the sharpe ratio.

legend_locmatplotlib.loc, optional

The location of the legend on the plot.

axmatplotlib.Axes, optional

Axes upon which to plot.

**kwargs, optional

Passed to plotting function.

Returns
axmatplotlib.Axes

The axes that were plotted on.

pyfolio.plotting.plot_rolling_volatility(returns, factor_returns=None, rolling_window=126, legend_loc='best', ax=None, **kwargs)

Plots the rolling volatility versus date.

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in tears.create_full_tear_sheet.

factor_returnspd.Series, optional

Daily noncumulative returns of the benchmark factor for which the benchmark rolling volatility is computed. Usually a benchmark such as market returns.

  • This is in the same style as returns.

rolling_windowint, optional

The days window over which to compute the volatility.

legend_locmatplotlib.loc, optional

The location of the legend on the plot.

axmatplotlib.Axes, optional

Axes upon which to plot.

**kwargs, optional

Passed to plotting function.

Returns
axmatplotlib.Axes

The axes that were plotted on.

pyfolio.plotting.plot_round_trip_lifetimes(round_trips, disp_amount=16, lsize=18, ax=None)

Plots timespans and directions of a sample of round trip trades.

Parameters
round_tripspd.DataFrame

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

axmatplotlib.Axes, optional

Axes upon which to plot.

Returns
axmatplotlib.Axes

The axes that were plotted on.

pyfolio.plotting.plot_sector_allocations(returns, sector_alloc, ax=None, **kwargs)

Plots the sector exposures of the portfolio over time.

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in tears.create_full_tear_sheet.

sector_allocpd.DataFrame

Portfolio allocation of positions. See pos.get_sector_alloc.

axmatplotlib.Axes, optional

Axes upon which to plot.

**kwargs, optional

Passed to plotting function.

Returns
axmatplotlib.Axes

The axes that were plotted on.

pyfolio.plotting.plot_slippage_sensitivity(returns, positions, transactions, ax=None, **kwargs)

Plots curve relating per-dollar slippage to average annual returns.

Parameters
returnspd.Series

Timeseries of portfolio returns to be adjusted for various degrees of slippage.

positionspd.DataFrame
Daily net position values.
  • See full explanation in tears.create_full_tear_sheet.

transactionspd.DataFrame
Prices and amounts of executed trades. One row per trade.
  • See full explanation in tears.create_full_tear_sheet.

axmatplotlib.Axes, optional

Axes upon which to plot.

**kwargs, optional

Passed to seaborn plotting function.

Returns
axmatplotlib.Axes

The axes that were plotted on.

pyfolio.plotting.plot_slippage_sweep(returns, positions, transactions, slippage_params=(3, 8, 10, 12, 15, 20, 50), ax=None, **kwargs)

Plots equity curves at different per-dollar slippage assumptions.

Parameters
returnspd.Series

Timeseries of portfolio returns to be adjusted for various degrees of slippage.

positionspd.DataFrame
Daily net position values.
  • See full explanation in tears.create_full_tear_sheet.

transactionspd.DataFrame
Prices and amounts of executed trades. One row per trade.
  • See full explanation in tears.create_full_tear_sheet.

slippage_params: tuple

Slippage pameters to apply to the return time series (in basis points).

axmatplotlib.Axes, optional

Axes upon which to plot.

**kwargs, optional

Passed to seaborn plotting function.

Returns
axmatplotlib.Axes

The axes that were plotted on.

pyfolio.plotting.plot_turnover(returns, transactions, positions, turnover_denom='AGB', 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
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in tears.create_full_tear_sheet.

transactionspd.DataFrame
Prices and amounts of executed trades. One row per trade.
  • See full explanation in tears.create_full_tear_sheet.

positionspd.DataFrame
Daily net position values.
  • See full explanation in tears.create_full_tear_sheet.

turnover_denomstr, optional

Either AGB or portfolio_value, default AGB. - See full explanation in txn.get_turnover.

legend_locmatplotlib.loc, optional

The location of the legend on the plot.

axmatplotlib.Axes, optional

Axes upon which to plot.

**kwargs, optional

Passed to plotting function.

Returns
axmatplotlib.Axes

The axes that were plotted on.

pyfolio.plotting.plot_txn_time_hist(transactions, bin_minutes=5, tz='America/New_York', ax=None, **kwargs)

Plots a histogram of transaction times, binning the times into buckets of a given duration.

Parameters
transactionspd.DataFrame
Prices and amounts of executed trades. One row per trade.
  • See full explanation in tears.create_full_tear_sheet.

bin_minutesfloat, optional

Sizes of the bins in minutes, defaults to 5 minutes.

tzstr, optional

Time zone to plot against. Note that if the specified zone does not apply daylight savings, the distribution may be partially offset.

axmatplotlib.Axes, optional

Axes upon which to plot.

**kwargs, optional

Passed to plotting function.

Returns
axmatplotlib.Axes

The axes that were plotted on.

pyfolio.plotting.show_and_plot_top_positions(returns, positions_alloc, show_and_plot=2, hide_positions=False, legend_loc='real_best', ax=None, **kwargs)

Prints and/or plots the exposures of the top 10 held positions of all time.

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in tears.create_full_tear_sheet.

positions_allocpd.DataFrame

Portfolio allocation of positions. See pos.get_percent_alloc.

show_and_plotint, optional

By default, this is 2, and both prints and plots. If this is 0, it will only plot; if 1, it will only print.

hide_positionsbool, optional

If True, will not output any symbol names.

legend_locmatplotlib.loc, optional

The location of the legend on the plot. By default, the legend will display below the plot.

axmatplotlib.Axes, optional

Axes upon which to plot.

**kwargs, optional

Passed to plotting function.

Returns
axmatplotlib.Axes, conditional

The axes that were plotted on.

pyfolio.plotting.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
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in tears.create_full_tear_sheet.

factor_returnspd.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.

positionspd.DataFrame, optional
Daily net position values.
  • See full explanation in create_full_tear_sheet.

transactionspd.DataFrame, optional

Prices and amounts of executed trades. One row per trade. - See full explanation in tears.create_full_tear_sheet

turnover_denomstr, optional

Either AGB or portfolio_value, default AGB. - See full explanation in txn.get_turnover.

live_start_datedatetime, optional

The point in time when the strategy began live trading, after its backtest period.

bootstrapboolean, optional

Whether to perform bootstrap analysis for the performance metrics.

  • For more information, see timeseries.perf_stats_bootstrap

header_rowsdict or OrderedDict, optional

Extra rows to display at the top of the displayed table.

pyfolio.plotting.show_profit_attribution(round_trips)

Prints the share of total PnL contributed by each traded name.

Parameters
round_tripspd.DataFrame

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

axmatplotlib.Axes, optional

Axes upon which to plot.

Returns
axmatplotlib.Axes

The axes that were plotted on.

pyfolio.plotting.show_worst_drawdown_periods(returns, top=5)

Prints information about the worst drawdown periods.

Prints peak dates, valley dates, recovery dates, and net drawdowns.

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in tears.create_full_tear_sheet.

topint, optional

Amount of top drawdowns periods to plot (default 5).

Utilities

The module pyfolio.utils contains various helper functions, e.g. to format factor data into the requisite input format.

pyfolio.utils.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.

returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in create_full_tear_sheet.

positionspd.DataFrame
Daily net position values.
  • See full explanation in create_full_tear_sheet.

transactionspd.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.

pyfolio.utils.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
retspd.Series
Daily returns of the strategy, noncumulative.
  • See pf.tears.create_full_tear_sheet for more details

benchmark_retspd.Series

Daily returns of the benchmark, noncumulative.

Returns
clipped_retspd.Series

Daily noncumulative returns with index clipped to match that of benchmark returns.

pyfolio.utils.configure_legend(ax, autofmt_xdate=True, change_colors=False, rotation=30, ha='right')

Format legend for perf attribution plots: - put legend to the right of plot instead of overlapping with it - make legend order match up with graph lines - set colors according to colormap

pyfolio.utils.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
positionspd.DataFrame
Daily net position values.
  • See full explanation in create_full_tear_sheet.

transactionspd.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.

pyfolio.utils.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
returnspd.Series
Daily returns of the strategy, noncumulative.
  • See full explanation in create_full_tear_sheet.

positionspd.DataFrame
Daily net position values.
  • See full explanation in create_full_tear_sheet.

transactionspd.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.

pyfolio.utils.extract_rets_pos_txn_from_zipline(backtest)

Extract returns, positions, transactions and leverage from the backtest data structure returned by zipline.TradingAlgorithm.run().

The returned data structures are in a format compatible with the rest of pyfolio and can be directly passed to e.g. tears.create_full_tear_sheet().

Parameters
backtestpd.DataFrame

DataFrame returned by zipline.TradingAlgorithm.run()

Returns
returnspd.Series
Daily returns of strategy.
  • See full explanation in tears.create_full_tear_sheet.

positionspd.DataFrame
Daily net position values.
  • See full explanation in tears.create_full_tear_sheet.

transactionspd.DataFrame
Prices and amounts of executed trades. One row per trade.
  • See full explanation in tears.create_full_tear_sheet.

pyfolio.utils.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.

pyfolio.utils.get_symbol_rets(symbol, start=None, end=None)

Calls the currently registered ‘returns_func’

Parameters
symbolobject

An identifier for the asset whose return series is desired. e.g. ticker symbol or database ID

startdate, optional

Earliest date to fetch data for. Defaults to earliest date available.

enddate, optional

Latest date to fetch data for. Defaults to latest date available.

Returns
pandas.Series

Returned by the current ‘returns_func’

pyfolio.utils.one_dec_places(x, pos)

Adds 1/10th decimal to plot ticks.

pyfolio.utils.percentage(x, pos)

Adds percentage sign to plot ticks.

pyfolio.utils.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
tablepandas.Series or pandas.DataFrame

Table to pretty-print.

namestr, optional

Table name to display in upper left corner.

float_formatfunction, 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%’.

formatterslist or dict, optional

Formatters to use by column, passed as the formatters arg to pd.Dataframe.to_html.

header_rowsdict, optional

Extra rows to display at the top of the table.

pyfolio.utils.register_return_func(func)

Registers the ‘returns_func’ that will be called for retrieving returns data.

Parameters
funcfunction

A function that returns a pandas Series of asset returns. The signature of the function must be as follows

>>> func(symbol)

Where symbol is an asset identifier

Returns
None
pyfolio.utils.sample_colormap(cmap_name, n_samples)

Sample a colormap from matplotlib

pyfolio.utils.standardize_data(x)

Standardize an array with mean and standard deviation.

Parameters
xnp.array

Array to standardize.

Returns
np.array

Standardized array.

pyfolio.utils.to_series(df)

For use in tests; converts DataFrame’s first column to Series.

pyfolio.utils.to_utc(df)

For use in tests; applied UTC timestamp to DataFrame.

pyfolio.utils.two_dec_places(x, pos)

Adds 1/100th decimal to plot ticks.

pyfolio.utils.vectorize(func)

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