positions = utils.check_intraday(estimate_intraday, returns,<EOL>positions, transactions)<EOL>vertical_sections = <NUM_LIT:6> if unadjusted_returns is not None else <NUM_LIT:4><EOL>fig = plt.figure(figsize=(<NUM_LIT>, vertical_sections * <NUM_LIT:6>))<EOL>gs = gridspec.GridSpec(vertical_sections, <NUM_LIT:3>, wspace=<NUM_LIT:0.5>, hspace=<NUM_LIT:0.5>)<EOL>ax_turnover = plt.subplot(gs[<NUM_LIT:0>, :])<EOL>ax_daily_volume = plt.subplot(gs[<NUM_LIT:1>, :], sharex=ax_turnover)<EOL>ax_turnover_hist = plt.subplot(gs[<NUM_LIT:2>, :])<EOL>ax_txn_timings = plt.subplot(gs[<NUM_LIT:3>, :])<EOL>plotting.plot_turnover(<EOL>returns,<EOL>transactions,<EOL>positions,<EOL>ax=ax_turnover)<EOL>plotting.plot_daily_volume(returns, transactions, ax=ax_daily_volume)<EOL>try:<EOL><INDENT>plotting.plot_daily_turnover_hist(transactions, positions,<EOL>ax=ax_turnover_hist)<EOL><DEDENT>except ValueError:<EOL><INDENT>warnings.warn('<STR_LIT>', UserWarning)<EOL><DEDENT>plotting.plot_txn_time_hist(transactions, ax=ax_txn_timings)<EOL>if unadjusted_returns is not None:<EOL><INDENT>ax_slippage_sweep = plt.subplot(gs[<NUM_LIT:4>, :])<EOL>plotting.plot_slippage_sweep(unadjusted_returns,<EOL>positions,<EOL>transactions,<EOL>ax=ax_slippage_sweep<EOL>)<EOL>ax_slippage_sensitivity = plt.subplot(gs[<NUM_LIT:5>, :])<EOL>plotting.plot_slippage_sensitivity(unadjusted_returns,<EOL>positions,<EOL>transactions,<EOL>ax=ax_slippage_sensitivity<EOL>)<EOL><DEDENT>for ax in fig.axes:<EOL><INDENT>plt.setp(ax.get_xticklabels(), visible=True)<EOL><DEDENT>if return_fig:<EOL><INDENT>return fig<EOL><DEDENT>

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

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

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.
unadjusted_returns : pd.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_fig : boolean, optional
    If True, returns the figure that was plotted on.


positions = utils.check_intraday(estimate_intraday, returns,<EOL>positions, transactions)<EOL>transactions_closed = round_trips.add_closing_transactions(positions,<EOL>transactions)<EOL>trades = round_trips.extract_round_trips(<EOL>transactions_closed,<EOL>portfolio_value=positions.sum(axis='<STR_LIT>') / (<NUM_LIT:1> + returns)<EOL>)<EOL>if len(trades) < <NUM_LIT:5>:<EOL><INDENT>warnings.warn(<EOL>"""<STR_LIT>""", UserWarning)<EOL>return<EOL><DEDENT>round_trips.print_round_trip_stats(trades)<EOL>plotting.show_profit_attribution(trades)<EOL>if sector_mappings is not None:<EOL><INDENT>sector_trades = round_trips.apply_sector_mappings_to_round_trips(<EOL>trades, sector_mappings)<EOL>plotting.show_profit_attribution(sector_trades)<EOL><DEDENT>fig = plt.figure(figsize=(<NUM_LIT>, <NUM_LIT:3> * <NUM_LIT:6>))<EOL>gs = gridspec.GridSpec(<NUM_LIT:3>, <NUM_LIT:2>, wspace=<NUM_LIT:0.5>, hspace=<NUM_LIT:0.5>)<EOL>ax_trade_lifetimes = plt.subplot(gs[<NUM_LIT:0>, :])<EOL>ax_prob_profit_trade = plt.subplot(gs[<NUM_LIT:1>, <NUM_LIT:0>])<EOL>ax_holding_time = plt.subplot(gs[<NUM_LIT:1>, <NUM_LIT:1>])<EOL>ax_pnl_per_round_trip_dollars = plt.subplot(gs[<NUM_LIT:2>, <NUM_LIT:0>])<EOL>ax_pnl_per_round_trip_pct = plt.subplot(gs[<NUM_LIT:2>, <NUM_LIT:1>])<EOL>plotting.plot_round_trip_lifetimes(trades, ax=ax_trade_lifetimes)<EOL>plotting.plot_prob_profit_trade(trades, ax=ax_prob_profit_trade)<EOL>trade_holding_times = [x.days for x in trades['<STR_LIT>']]<EOL>sns.distplot(trade_holding_times, kde=False, ax=ax_holding_time)<EOL>ax_holding_time.set(xlabel='<STR_LIT>')<EOL>sns.distplot(trades.pnl, kde=False, ax=ax_pnl_per_round_trip_dollars)<EOL>ax_pnl_per_round_trip_dollars.set(xlabel='<STR_LIT>')<EOL>sns.distplot(trades.returns.dropna() * <NUM_LIT:100>, kde=False,<EOL>ax=ax_pnl_per_round_trip_pct)<EOL>ax_pnl_per_round_trip_pct.set(<EOL>xlabel='<STR_LIT>')<EOL>gs.tight_layout(fig)<EOL>if return_fig:<EOL><INDENT>return fig<EOL><DEDENT>

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
----------
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.
sector_mappings : dict 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_fig : boolean, optional
    If True, returns the figure that was plotted on.


@plotting.customize<EOL>def create_interesting_times_tear_sheet(<EOL>returns, benchmark_rets=None, legend_loc='<STR_LIT>', return_fig=False):

rets_interesting = timeseries.extract_interesting_date_ranges(returns)<EOL>if not rets_interesting:<EOL><INDENT>warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>', UserWarning)<EOL>return<EOL><DEDENT>utils.print_table(pd.DataFrame(rets_interesting)<EOL>.describe().transpose()<EOL>.loc[:, ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']] * <NUM_LIT:100>,<EOL>name='<STR_LIT>',<EOL>float_format='<STR_LIT>'.format)<EOL>if benchmark_rets is not None:<EOL><INDENT>returns = utils.clip_returns_to_benchmark(returns, benchmark_rets)<EOL>bmark_interesting = timeseries.extract_interesting_date_ranges(<EOL>benchmark_rets)<EOL><DEDENT>num_plots = len(rets_interesting)<EOL>num_rows = int((num_plots + <NUM_LIT:1>) / <NUM_LIT>)<EOL>fig = plt.figure(figsize=(<NUM_LIT>, num_rows * <NUM_LIT>))<EOL>gs = gridspec.GridSpec(num_rows, <NUM_LIT:2>, wspace=<NUM_LIT:0.5>, hspace=<NUM_LIT:0.5>)<EOL>for i, (name, rets_period) in enumerate(rets_interesting.items()):<EOL><INDENT>ax = plt.subplot(gs[int(i / <NUM_LIT>), i % <NUM_LIT:2>])<EOL>ep.cum_returns(rets_period).plot(<EOL>ax=ax, color='<STR_LIT>', label='<STR_LIT>', alpha=<NUM_LIT>, lw=<NUM_LIT:2>)<EOL>if benchmark_rets is not None:<EOL><INDENT>ep.cum_returns(bmark_interesting[name]).plot(<EOL>ax=ax, color='<STR_LIT>', label='<STR_LIT>', alpha=<NUM_LIT>)<EOL>ax.legend(['<STR_LIT>',<EOL>'<STR_LIT>'],<EOL>loc=legend_loc, frameon=True, framealpha=<NUM_LIT:0.5>)<EOL><DEDENT>else:<EOL><INDENT>ax.legend(['<STR_LIT>'],<EOL>loc=legend_loc, frameon=True, framealpha=<NUM_LIT:0.5>)<EOL><DEDENT>ax.set_title(name)<EOL>ax.set_ylabel('<STR_LIT>')<EOL>ax.set_xlabel('<STR_LIT>')<EOL><DEDENT>if return_fig:<EOL><INDENT>return fig<EOL><DEDENT>

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
----------
returns : pd.Series
    Daily returns of the strategy, noncumulative.
     - See full explanation in create_full_tear_sheet.
benchmark_rets : pd.Series
    Daily noncumulative returns of the benchmark.
     - This is in the same style as returns.
legend_loc : plt.legend_loc, optional
     The legend's location.
return_fig : boolean, optional
    If True, returns the figure that was plotted on.


positions = utils.check_intraday(estimate_intraday, returns,<EOL>positions, transactions)<EOL>print("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>max_days_by_ticker = capacity.get_max_days_to_liquidate_by_ticker(<EOL>positions, market_data,<EOL>max_bar_consumption=liquidation_daily_vol_limit,<EOL>capital_base=<NUM_LIT>,<EOL>mean_volume_window=<NUM_LIT:5>)<EOL>max_days_by_ticker.index = (<EOL>max_days_by_ticker.index.map(utils.format_asset))<EOL>print("<STR_LIT>")<EOL>utils.print_table(<EOL>max_days_by_ticker[max_days_by_ticker.days_to_liquidate ><EOL>days_to_liquidate_limit])<EOL>max_days_by_ticker_lnd = capacity.get_max_days_to_liquidate_by_ticker(<EOL>positions, market_data,<EOL>max_bar_consumption=liquidation_daily_vol_limit,<EOL>capital_base=<NUM_LIT>,<EOL>mean_volume_window=<NUM_LIT:5>,<EOL>last_n_days=last_n_days)<EOL>max_days_by_ticker_lnd.index = (<EOL>max_days_by_ticker_lnd.index.map(utils.format_asset))<EOL>print("<STR_LIT>".format(last_n_days))<EOL>utils.print_table(<EOL>max_days_by_ticker_lnd[max_days_by_ticker_lnd.days_to_liquidate > <NUM_LIT:1>])<EOL>llt = capacity.get_low_liquidity_transactions(transactions, market_data)<EOL>llt.index = llt.index.map(utils.format_asset)<EOL>print('<STR_LIT>'<EOL>'<STR_LIT>'.format(trade_daily_vol_limit * <NUM_LIT:100>))<EOL>utils.print_table(<EOL>llt[llt['<STR_LIT>'] > trade_daily_vol_limit * <NUM_LIT:100>])<EOL>llt = capacity.get_low_liquidity_transactions(<EOL>transactions, market_data, last_n_days=last_n_days)<EOL>print("<STR_LIT>".format(last_n_days))<EOL>utils.print_table(<EOL>llt[llt['<STR_LIT>'] > trade_daily_vol_limit * <NUM_LIT:100>])<EOL>bt_starting_capital = positions.iloc[<NUM_LIT:0>].sum() / (<NUM_LIT:1> + returns.iloc[<NUM_LIT:0>])<EOL>fig, ax_capacity_sweep = plt.subplots(figsize=(<NUM_LIT>, <NUM_LIT:6>))<EOL>plotting.plot_capacity_sweep(returns, transactions, market_data,<EOL>bt_starting_capital,<EOL>min_pv=<NUM_LIT>,<EOL>max_pv=<NUM_LIT>,<EOL>step_size=<NUM_LIT>,<EOL>ax=ax_capacity_sweep)<EOL>

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
----------
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.
market_data : pd.Panel
    Panel with items axis of 'price' and 'volume' DataFrames.
    The major and minor axes should match those of the
    the passed positions DataFrame (same dates and symbols).
liquidation_daily_vol_limit : float
    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_limit : float
    Flag daily transaction totals that exceed proportion of
    daily bar.
last_n_days : integer
    Compute max position allocation and dollar volume for only
    the last N days of the backtest
days_to_liquidate_limit : integer
    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.


if not have_bayesian:<EOL><INDENT>raise NotImplementedError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>if live_start_date is None:<EOL><INDENT>raise NotImplementedError(<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT>live_start_date = ep.utils.get_utc_timestamp(live_start_date)<EOL>df_train = returns.loc[returns.index < live_start_date]<EOL>df_test = returns.loc[returns.index >= live_start_date]<EOL>print("<STR_LIT>")<EOL>previous_time = time()<EOL>start_time = previous_time<EOL>trace_t, ppc_t = bayesian.run_model('<STR_LIT:t>', df_train,<EOL>returns_test=df_test,<EOL>samples=samples, ppc=True,<EOL>progressbar=progressbar)<EOL>previous_time = timer("<STR_LIT>", previous_time)<EOL>print("<STR_LIT>")<EOL>trace_best = bayesian.run_model('<STR_LIT>', df_train,<EOL>returns_test=df_test,<EOL>samples=samples,<EOL>progressbar=progressbar)<EOL>previous_time = timer("<STR_LIT>", previous_time)<EOL>fig = plt.figure(figsize=(<NUM_LIT>, <NUM_LIT:10> * <NUM_LIT:2>))<EOL>gs = gridspec.GridSpec(<NUM_LIT:9>, <NUM_LIT:2>, wspace=<NUM_LIT>, hspace=<NUM_LIT>)<EOL>axs = []<EOL>row = <NUM_LIT:0><EOL>ax_cone = plt.subplot(gs[row, :])<EOL>bayesian.plot_bayes_cone(df_train, df_test, ppc_t, ax=ax_cone)<EOL>previous_time = timer("<STR_LIT>", previous_time)<EOL>row += <NUM_LIT:1><EOL>axs.append(plt.subplot(gs[row, <NUM_LIT:0>]))<EOL>axs.append(plt.subplot(gs[row, <NUM_LIT:1>]))<EOL>row += <NUM_LIT:1><EOL>axs.append(plt.subplot(gs[row, <NUM_LIT:0>]))<EOL>axs.append(plt.subplot(gs[row, <NUM_LIT:1>]))<EOL>row += <NUM_LIT:1><EOL>axs.append(plt.subplot(gs[row, <NUM_LIT:0>]))<EOL>axs.append(plt.subplot(gs[row, <NUM_LIT:1>]))<EOL>row += <NUM_LIT:1><EOL>axs.append(plt.subplot(gs[row, :]))<EOL>bayesian.plot_best(trace=trace_best, axs=axs)<EOL>previous_time = timer("<STR_LIT>", previous_time)<EOL>row += <NUM_LIT:1><EOL>ax_ret_pred_day = plt.subplot(gs[row, <NUM_LIT:0>])<EOL>ax_ret_pred_week = plt.subplot(gs[row, <NUM_LIT:1>])<EOL>day_pred = ppc_t[:, <NUM_LIT:0>]<EOL>p5 = scipy.stats.scoreatpercentile(day_pred, <NUM_LIT:5>)<EOL>sns.distplot(day_pred,<EOL>ax=ax_ret_pred_day<EOL>)<EOL>ax_ret_pred_day.axvline(p5, linestyle='<STR_LIT>', linewidth=<NUM_LIT>)<EOL>ax_ret_pred_day.set_xlabel('<STR_LIT>')<EOL>ax_ret_pred_day.set_ylabel('<STR_LIT>')<EOL>ax_ret_pred_day.text(<NUM_LIT>, <NUM_LIT>, '<STR_LIT>' % p5,<EOL>verticalalignment='<STR_LIT>',<EOL>horizontalalignment='<STR_LIT:right>',<EOL>transform=ax_ret_pred_day.transAxes)<EOL>previous_time = timer("<STR_LIT>", previous_time)<EOL>week_pred = (<EOL>np.cumprod(ppc_t[:, :<NUM_LIT:5>] + <NUM_LIT:1>, <NUM_LIT:1>) - <NUM_LIT:1>)[:, -<NUM_LIT:1>]<EOL>p5 = scipy.stats.scoreatpercentile(week_pred, <NUM_LIT:5>)<EOL>sns.distplot(week_pred,<EOL>ax=ax_ret_pred_week<EOL>)<EOL>ax_ret_pred_week.axvline(p5, linestyle='<STR_LIT>', linewidth=<NUM_LIT>)<EOL>ax_ret_pred_week.set_xlabel('<STR_LIT>')<EOL>ax_ret_pred_week.set_ylabel('<STR_LIT>')<EOL>ax_ret_pred_week.text(<NUM_LIT>, <NUM_LIT>, '<STR_LIT>' % p5,<EOL>verticalalignment='<STR_LIT>',<EOL>horizontalalignment='<STR_LIT:right>',<EOL>transform=ax_ret_pred_week.transAxes)<EOL>previous_time = timer("<STR_LIT>", previous_time)<EOL>if benchmark_rets is not None:<EOL><INDENT>print("<STR_LIT>")<EOL>benchmark_rets = benchmark_rets.loc[df_train.index]<EOL>trace_alpha_beta = bayesian.run_model('<STR_LIT>', df_train,<EOL>bmark=benchmark_rets,<EOL>samples=samples,<EOL>progressbar=progressbar)<EOL>previous_time = timer("<STR_LIT>", previous_time)<EOL>row += <NUM_LIT:1><EOL>ax_alpha = plt.subplot(gs[row, <NUM_LIT:0>])<EOL>ax_beta = plt.subplot(gs[row, <NUM_LIT:1>])<EOL>sns.distplot((<NUM_LIT:1> + trace_alpha_beta['<STR_LIT>'][<NUM_LIT:100>:])**<NUM_LIT> - <NUM_LIT:1>,<EOL>ax=ax_alpha)<EOL>sns.distplot(trace_alpha_beta['<STR_LIT>'][<NUM_LIT:100>:], ax=ax_beta)<EOL>ax_alpha.set_xlabel('<STR_LIT>')<EOL>ax_alpha.set_ylabel('<STR_LIT>')<EOL>ax_beta.set_xlabel('<STR_LIT>')<EOL>ax_beta.set_ylabel('<STR_LIT>')<EOL>previous_time = timer("<STR_LIT>", previous_time)<EOL><DEDENT>if stoch_vol:<EOL><INDENT>returns_cutoff = <NUM_LIT><EOL>print(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(returns_cutoff)<EOL>)<EOL>if df_train.size > returns_cutoff:<EOL><INDENT>df_train_truncated = df_train[-returns_cutoff:]<EOL><DEDENT>_, trace_stoch_vol = bayesian.model_stoch_vol(df_train_truncated)<EOL>previous_time = timer(<EOL>"<STR_LIT>", previous_time)<EOL>row += <NUM_LIT:1><EOL>ax_volatility = plt.subplot(gs[row, :])<EOL>bayesian.plot_stoch_vol(<EOL>df_train_truncated, trace=trace_stoch_vol, ax=ax_volatility)<EOL>previous_time = timer(<EOL>"<STR_LIT>", previous_time)<EOL><DEDENT>total_time = time() - start_time<EOL>print("<STR_LIT>".format(total_time))<EOL>gs.tight_layout(fig)<EOL>if return_fig:<EOL><INDENT>return fig<EOL><DEDENT>

Generate a number of Bayesian distributions and a Bayesian
cone plot of returns.

Plots: Sharpe distribution, annual volatility distribution,
annual alpha distribution, beta distribution, predicted 1 and 5
day returns distributions, and a cumulative returns cone plot.

Parameters
----------
returns : pd.Series
    Daily returns of the strategy, noncumulative.
     - See full explanation in create_full_tear_sheet.
benchmark_rets : pd.Series, optional
    Daily noncumulative returns of the benchmark.
     - This is in the same style as returns.
live_start_date : datetime, optional
    The point in time when the strategy began live
    trading, after its backtest period.
samples : int, optional
    Number of posterior samples to draw.
return_fig : boolean, optional
    If True, returns the figure that was plotted on.
stoch_vol : boolean, optional
    If True, run and plot the stochastic volatility model
progressbar : boolean, optional
    If True, show a progress bar


positions = utils.check_intraday(estimate_intraday, returns,<EOL>positions, transactions)<EOL>idx = positions.index & style_factor_panel.iloc[<NUM_LIT:0>].index & sectors.index& caps.index & shares_held.index & volumes.index<EOL>positions = positions.loc[idx]<EOL>vertical_sections = <NUM_LIT:0><EOL>if style_factor_panel is not None:<EOL><INDENT>vertical_sections += len(style_factor_panel.items)<EOL>new_style_dict = {}<EOL>for item in style_factor_panel.items:<EOL><INDENT>new_style_dict.update({item:<EOL>style_factor_panel.loc[item].loc[idx]})<EOL><DEDENT>style_factor_panel = pd.Panel()<EOL>style_factor_panel = style_factor_panel.from_dict(new_style_dict)<EOL><DEDENT>if sectors is not None:<EOL><INDENT>vertical_sections += <NUM_LIT:4><EOL>sectors = sectors.loc[idx]<EOL><DEDENT>if caps is not None:<EOL><INDENT>vertical_sections += <NUM_LIT:4><EOL>caps = caps.loc[idx]<EOL><DEDENT>if (shares_held is not None) & (volumes is not None)& (percentile is not None):<EOL><INDENT>vertical_sections += <NUM_LIT:3><EOL>shares_held = shares_held.loc[idx]<EOL>volumes = volumes.loc[idx]<EOL><DEDENT>if percentile is None:<EOL><INDENT>percentile = <NUM_LIT:0.1><EOL><DEDENT>fig = plt.figure(figsize=[<NUM_LIT>, vertical_sections * <NUM_LIT:6>])<EOL>gs = gridspec.GridSpec(vertical_sections, <NUM_LIT:3>, wspace=<NUM_LIT:0.5>, hspace=<NUM_LIT:0.5>)<EOL>if style_factor_panel is not None:<EOL><INDENT>style_axes = []<EOL>style_axes.append(plt.subplot(gs[<NUM_LIT:0>, :]))<EOL>for i in range(<NUM_LIT:1>, len(style_factor_panel.items)):<EOL><INDENT>style_axes.append(plt.subplot(gs[i, :], sharex=style_axes[<NUM_LIT:0>]))<EOL><DEDENT>j = <NUM_LIT:0><EOL>for name, df in style_factor_panel.iteritems():<EOL><INDENT>sfe = risk.compute_style_factor_exposures(positions, df)<EOL>risk.plot_style_factor_exposures(sfe, name, style_axes[j])<EOL>j += <NUM_LIT:1><EOL><DEDENT><DEDENT>if sectors is not None:<EOL><INDENT>i += <NUM_LIT:1><EOL>ax_sector_longshort = plt.subplot(gs[i:i+<NUM_LIT:2>, :], sharex=style_axes[<NUM_LIT:0>])<EOL>i += <NUM_LIT:2><EOL>ax_sector_gross = plt.subplot(gs[i, :], sharex=style_axes[<NUM_LIT:0>])<EOL>i += <NUM_LIT:1><EOL>ax_sector_net = plt.subplot(gs[i, :], sharex=style_axes[<NUM_LIT:0>])<EOL>long_exposures, short_exposures, gross_exposures, net_exposures= risk.compute_sector_exposures(positions, sectors)<EOL>risk.plot_sector_exposures_longshort(long_exposures, short_exposures,<EOL>ax=ax_sector_longshort)<EOL>risk.plot_sector_exposures_gross(gross_exposures, ax=ax_sector_gross)<EOL>risk.plot_sector_exposures_net(net_exposures, ax=ax_sector_net)<EOL><DEDENT>if caps is not None:<EOL><INDENT>i += <NUM_LIT:1><EOL>ax_cap_longshort = plt.subplot(gs[i:i+<NUM_LIT:2>, :], sharex=style_axes[<NUM_LIT:0>])<EOL>i += <NUM_LIT:2><EOL>ax_cap_gross = plt.subplot(gs[i, :], sharex=style_axes[<NUM_LIT:0>])<EOL>i += <NUM_LIT:1><EOL>ax_cap_net = plt.subplot(gs[i, :], sharex=style_axes[<NUM_LIT:0>])<EOL>long_exposures, short_exposures, gross_exposures, net_exposures= risk.compute_cap_exposures(positions, caps)<EOL>risk.plot_cap_exposures_longshort(long_exposures, short_exposures,<EOL>ax_cap_longshort)<EOL>risk.plot_cap_exposures_gross(gross_exposures, ax_cap_gross)<EOL>risk.plot_cap_exposures_net(net_exposures, ax_cap_net)<EOL><DEDENT>if volumes is not None:<EOL><INDENT>i += <NUM_LIT:1><EOL>ax_vol_longshort = plt.subplot(gs[i:i+<NUM_LIT:2>, :], sharex=style_axes[<NUM_LIT:0>])<EOL>i += <NUM_LIT:2><EOL>ax_vol_gross = plt.subplot(gs[i, :], sharex=style_axes[<NUM_LIT:0>])<EOL>longed_threshold, shorted_threshold, grossed_threshold= risk.compute_volume_exposures(positions, volumes, percentile)<EOL>risk.plot_volume_exposures_longshort(longed_threshold,<EOL>shorted_threshold, percentile,<EOL>ax_vol_longshort)<EOL>risk.plot_volume_exposures_gross(grossed_threshold, percentile,<EOL>ax_vol_gross)<EOL><DEDENT>for ax in fig.axes:<EOL><INDENT>plt.setp(ax.get_xticklabels(), visible=True)<EOL><DEDENT>if return_fig:<EOL><INDENT>return fig<EOL><DEDENT>

Creates risk tear sheet: computes and plots style factor exposures, sector
exposures, market cap exposures and volume exposures.

Parameters
----------
positions : pd.DataFrame
    Daily equity positions of algorithm, in dollars.
    - DataFrame with dates as index, equities as columns
    - Last column is cash held
    - Example:
                 Equity(24   Equity(62
                   [AAPL])      [ABT])             cash
    2017-04-03	-108062.40 	  4401.540     2.247757e+07
    2017-04-04	-108852.00	  4373.820     2.540999e+07
    2017-04-05	-119968.66	  4336.200     2.839812e+07

style_factor_panel : pd.Panel
    Panel where each item is a DataFrame that tabulates style factor per
    equity per day.
    - Each item has dates as index, equities as columns
    - Example item:
                 Equity(24   Equity(62
                   [AAPL])      [ABT])
    2017-04-03	  -0.51284     1.39173
    2017-04-04	  -0.73381     0.98149
    2017-04-05	  -0.90132	   1.13981

sectors : pd.DataFrame
    Daily Morningstar sector code per asset
    - DataFrame with dates as index and equities as columns
    - Example:
                 Equity(24   Equity(62
                   [AAPL])      [ABT])
    2017-04-03	     311.0       206.0
    2017-04-04	     311.0       206.0
    2017-04-05	     311.0	     206.0

caps : pd.DataFrame
    Daily market cap per asset
    - DataFrame with dates as index and equities as columns
    - Example:
                      Equity(24        Equity(62
                        [AAPL])           [ABT])
    2017-04-03     1.327160e+10     6.402460e+10
    2017-04-04	   1.329620e+10     6.403694e+10
    2017-04-05	   1.297464e+10	    6.397187e+10

shares_held : pd.DataFrame
    Daily number of shares held by an algorithm.
    - Example:
                      Equity(24        Equity(62
                        [AAPL])           [ABT])
    2017-04-03             1915            -2595
    2017-04-04	           1968            -3272
    2017-04-05	           2104            -3917

volumes : pd.DataFrame
    Daily volume per asset
    - DataFrame with dates as index and equities as columns
    - Example:
                      Equity(24        Equity(62
                        [AAPL])           [ABT])
    2017-04-03      34940859.00       4665573.80
    2017-04-04	    35603329.10       4818463.90
    2017-04-05	    41846731.75	      4129153.10

percentile : float
    Percentile to use when computing and plotting volume exposures.
    - Defaults to 10th percentile


portfolio_exposures, perf_attrib_data = perf_attrib.perf_attrib(<EOL>returns, positions, factor_returns, factor_loadings, transactions,<EOL>pos_in_dollars=pos_in_dollars<EOL>)<EOL>display(Markdown("<STR_LIT>"))<EOL>perf_attrib.show_perf_attrib_stats(returns, positions, factor_returns,<EOL>factor_loadings, transactions,<EOL>pos_in_dollars)<EOL>vertical_sections = <NUM_LIT:1> + <NUM_LIT:2> * max(len(factor_partitions), <NUM_LIT:1>)<EOL>current_section = <NUM_LIT:0><EOL>fig = plt.figure(figsize=[<NUM_LIT>, vertical_sections * <NUM_LIT:6>])<EOL>gs = gridspec.GridSpec(vertical_sections, <NUM_LIT:1>,<EOL>wspace=<NUM_LIT:0.5>, hspace=<NUM_LIT:0.5>)<EOL>perf_attrib.plot_returns(perf_attrib_data,<EOL>ax=plt.subplot(gs[current_section]))<EOL>current_section += <NUM_LIT:1><EOL>if factor_partitions is not None:<EOL><INDENT>for factor_type, partitions in factor_partitions.iteritems():<EOL><INDENT>columns_to_select = perf_attrib_data.columns.intersection(<EOL>partitions<EOL>)<EOL>perf_attrib.plot_factor_contribution_to_perf(<EOL>perf_attrib_data[columns_to_select],<EOL>ax=plt.subplot(gs[current_section]),<EOL>title=(<EOL>'<STR_LIT>'<EOL>).format(factor_type)<EOL>)<EOL>current_section += <NUM_LIT:1><EOL><DEDENT>for factor_type, partitions in factor_partitions.iteritems():<EOL><INDENT>perf_attrib.plot_risk_exposures(<EOL>portfolio_exposures[portfolio_exposures.columns<EOL>.intersection(partitions)],<EOL>ax=plt.subplot(gs[current_section]),<EOL>title='<STR_LIT>'.format(factor_type)<EOL>)<EOL>current_section += <NUM_LIT:1><EOL><DEDENT><DEDENT>else:<EOL><INDENT>perf_attrib.plot_factor_contribution_to_perf(<EOL>perf_attrib_data,<EOL>ax=plt.subplot(gs[current_section])<EOL>)<EOL>current_section += <NUM_LIT:1><EOL>perf_attrib.plot_risk_exposures(<EOL>portfolio_exposures,<EOL>ax=plt.subplot(gs[current_section])<EOL>)<EOL><DEDENT>gs.tight_layout(fig)<EOL>if return_fig:<EOL><INDENT>return fig<EOL><DEDENT>

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

Parameters
----------
returns : pd.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_returns : pd.DataFrame
    Returns by factor, with date as index and factors as columns

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

transactions : pd.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_dollars : boolean, optional
    Flag indicating whether `positions` are in dollars or percentages
    If True, positions are in dollars.

return_fig : boolean, optional
    If True, returns the figure that was plotted on.

factor_partitions : dict
    dict specifying how factors should be separated in factor returns
    and risk exposures plots
    - Example:
      {'style': ['momentum', 'size', 'value', ...],
       'sector': ['technology', 'materials', ... ]}


transactions.index.name = '<STR_LIT:date>'<EOL>txn_daily = pd.DataFrame(transactions.assign(<EOL>amount=abs(transactions.amount)).groupby(<EOL>['<STR_LIT>', pd.TimeGrouper('<STR_LIT:D>')]).sum()['<STR_LIT>'])<EOL>txn_daily['<STR_LIT>'] = market_data['<STR_LIT>'].unstack()<EOL>txn_daily['<STR_LIT>'] = market_data['<STR_LIT>'].unstack()<EOL>txn_daily = txn_daily.reset_index().set_index('<STR_LIT:date>')<EOL>return txn_daily<EOL>

Sums the absolute value of shares traded in each name on each day.
Adds columns containing the closing price and total daily volume for
each day-ticker combination.

Parameters
----------
transactions : pd.DataFrame
    Prices and amounts of executed trades. One row per trade.
    - See full explanation in tears.create_full_tear_sheet
market_data : pd.Panel
    Contains "volume" and "price" DataFrames for the tickers
    in the passed positions DataFrames

Returns
-------
txn_daily : pd.DataFrame
    Daily totals for transacted shares in each traded name.
    price and volume columns for close price and daily volume for
    the corresponding ticker, respectively.


DV = market_data['<STR_LIT>'] * market_data['<STR_LIT>']<EOL>roll_mean_dv = DV.rolling(window=mean_volume_window,<EOL>center=False).mean().shift()<EOL>roll_mean_dv = roll_mean_dv.replace(<NUM_LIT:0>, np.nan)<EOL>positions_alloc = pos.get_percent_alloc(positions)<EOL>positions_alloc = positions_alloc.drop('<STR_LIT>', axis=<NUM_LIT:1>)<EOL>days_to_liquidate = (positions_alloc * capital_base) /(max_bar_consumption * roll_mean_dv)<EOL>return days_to_liquidate.iloc[mean_volume_window:]<EOL>

Compute the number of days that would have been required
to fully liquidate each position on each day based on the
trailing n day mean daily bar volume and a limit on the proportion
of a daily bar that we are allowed to consume.

This analysis uses portfolio allocations and a provided capital base
rather than the dollar values in the positions DataFrame to remove the
effect of compounding on days to liquidate. In other words, this function
assumes that the net liquidation portfolio value will always remain
constant at capital_base.

Parameters
----------
positions: pd.DataFrame
    Contains daily position values including cash
    - See full explanation in tears.create_full_tear_sheet
market_data : pd.Panel
    Panel with items axis of 'price' and 'volume' DataFrames.
    The major and minor axes should match those of the
    the passed positions DataFrame (same dates and symbols).
max_bar_consumption : float
    Max proportion of a daily bar that can be consumed in the
    process of liquidating a position.
capital_base : integer
    Capital base multiplied by portfolio allocation to compute
    position value that needs liquidating.
mean_volume_window : float
    Trailing window to use in mean volume calculation.

Returns
-------
days_to_liquidate : pd.DataFrame
    Number of days required to fully liquidate daily positions.
    Datetime index, symbols as columns.


dtlp = days_to_liquidate_positions(positions, market_data,<EOL>max_bar_consumption=max_bar_consumption,<EOL>capital_base=capital_base,<EOL>mean_volume_window=mean_volume_window)<EOL>if last_n_days is not None:<EOL><INDENT>dtlp = dtlp.loc[dtlp.index.max() - pd.Timedelta(days=last_n_days):]<EOL><DEDENT>pos_alloc = pos.get_percent_alloc(positions)<EOL>pos_alloc = pos_alloc.drop('<STR_LIT>', axis=<NUM_LIT:1>)<EOL>liq_desc = pd.DataFrame()<EOL>liq_desc['<STR_LIT>'] = dtlp.unstack()<EOL>liq_desc['<STR_LIT>'] = pos_alloc.unstack() * <NUM_LIT:100><EOL>liq_desc.index.levels[<NUM_LIT:0>].name = '<STR_LIT>'<EOL>liq_desc.index.levels[<NUM_LIT:1>].name = '<STR_LIT:date>'<EOL>worst_liq = liq_desc.reset_index().sort_values(<EOL>'<STR_LIT>', ascending=False).groupby('<STR_LIT>').first()<EOL>return worst_liq<EOL>

Finds the longest estimated liquidation time for each traded
name over the course of backtest (or last n days of the backtest).

Parameters
----------
positions: pd.DataFrame
    Contains daily position values including cash
    - See full explanation in tears.create_full_tear_sheet
market_data : pd.Panel
    Panel with items axis of 'price' and 'volume' DataFrames.
    The major and minor axes should match those of the
    the passed positions DataFrame (same dates and symbols).
max_bar_consumption : float
    Max proportion of a daily bar that can be consumed in the
    process of liquidating a position.
capital_base : integer
    Capital base multiplied by portfolio allocation to compute
    position value that needs liquidating.
mean_volume_window : float
    Trailing window to use in mean volume calculation.
last_n_days : integer
    Compute for only the last n days of the passed backtest data.

Returns
-------
days_to_liquidate : pd.DataFrame
    Max Number of days required to fully liquidate each traded name.
    Index of symbols. Columns for days_to_liquidate and the corresponding
    date and position_alloc on that day.


txn_daily_w_bar = daily_txns_with_bar_data(transactions, market_data)<EOL>txn_daily_w_bar.index.name = '<STR_LIT:date>'<EOL>txn_daily_w_bar = txn_daily_w_bar.reset_index()<EOL>if last_n_days is not None:<EOL><INDENT>md = txn_daily_w_bar.date.max() - pd.Timedelta(days=last_n_days)<EOL>txn_daily_w_bar = txn_daily_w_bar[txn_daily_w_bar.date > md]<EOL><DEDENT>bar_consumption = txn_daily_w_bar.assign(<EOL>max_pct_bar_consumed=(<EOL>txn_daily_w_bar.amount/txn_daily_w_bar.volume)*<NUM_LIT:100><EOL>).sort_values('<STR_LIT>', ascending=False)<EOL>max_bar_consumption = bar_consumption.groupby('<STR_LIT>').first()<EOL>return max_bar_consumption[['<STR_LIT:date>', '<STR_LIT>']]<EOL>

For each traded name, find the daily transaction total that consumed
the greatest proportion of available daily bar volume.

Parameters
----------
transactions : pd.DataFrame
    Prices and amounts of executed trades. One row per trade.
     - See full explanation in create_full_tear_sheet.
market_data : pd.Panel
    Panel with items axis of 'price' and 'volume' DataFrames.
    The major and minor axes should match those of the
    the passed positions DataFrame (same dates and symbols).
last_n_days : integer
    Compute for only the last n days of the passed backtest data.


@wraps(func)<EOL>def call_w_context(*args, **kwargs):<EOL><INDENT>set_context = kwargs.pop('<STR_LIT>', True)<EOL>if set_context:<EOL><INDENT>with plotting_context(), axes_style():<EOL><INDENT>return func(*args, **kwargs)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return func(*args, **kwargs)<EOL><DEDENT><DEDENT>return call_w_context<EOL>

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


def plotting_context(context='<STR_LIT>', font_scale=<NUM_LIT>, rc=None):

if rc is None:<EOL><INDENT>rc = {}<EOL><DEDENT>rc_default = {'<STR_LIT>': <NUM_LIT>}<EOL>for name, val in rc_default.items():<EOL><INDENT>rc.setdefault(name, val)<EOL><DEDENT>return sns.plotting_context(context=context, font_scale=font_scale, rc=rc)<EOL>

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:<EOL><INDENT>rc = {}<EOL><DEDENT>rc_default = {}<EOL>for name, val in rc_default.items():<EOL><INDENT>rc.setdefault(name, val)<EOL><DEDENT>return sns.axes_style(style=style, rc=rc)<EOL>

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().


def plot_monthly_returns_heatmap(returns, ax=None, **kwargs):

if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>monthly_ret_table = ep.aggregate_returns(returns, '<STR_LIT>')<EOL>monthly_ret_table = monthly_ret_table.unstack().round(<NUM_LIT:3>)<EOL>sns.heatmap(<EOL>monthly_ret_table.fillna(<NUM_LIT:0>) *<EOL><NUM_LIT>,<EOL>annot=True,<EOL>annot_kws={"<STR_LIT:size>": <NUM_LIT:9>},<EOL>alpha=<NUM_LIT:1.0>,<EOL>center=<NUM_LIT:0.0>,<EOL>cbar=False,<EOL>cmap=matplotlib.cm.RdYlGn,<EOL>ax=ax, **kwargs)<EOL>ax.set_ylabel('<STR_LIT>')<EOL>ax.set_xlabel('<STR_LIT>')<EOL>ax.set_title("<STR_LIT>")<EOL>return ax<EOL>

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.


def plot_annual_returns(returns, ax=None, **kwargs):

if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>x_axis_formatter = FuncFormatter(utils.percentage)<EOL>ax.xaxis.set_major_formatter(FuncFormatter(x_axis_formatter))<EOL>ax.tick_params(axis='<STR_LIT:x>', which='<STR_LIT>')<EOL>ann_ret_df = pd.DataFrame(<EOL>ep.aggregate_returns(<EOL>returns,<EOL>'<STR_LIT>'))<EOL>ax.axvline(<EOL><NUM_LIT:100> *<EOL>ann_ret_df.values.mean(),<EOL>color='<STR_LIT>',<EOL>linestyle='<STR_LIT>',<EOL>lw=<NUM_LIT:4>,<EOL>alpha=<NUM_LIT>)<EOL>(<NUM_LIT:100> * ann_ret_df.sort_index(ascending=False)<EOL>).plot(ax=ax, kind='<STR_LIT>', alpha=<NUM_LIT>, **kwargs)<EOL>ax.axvline(<NUM_LIT:0.0>, color='<STR_LIT>', linestyle='<STR_LIT:->', lw=<NUM_LIT:3>)<EOL>ax.set_ylabel('<STR_LIT>')<EOL>ax.set_xlabel('<STR_LIT>')<EOL>ax.set_title("<STR_LIT>")<EOL>ax.legend(['<STR_LIT>'], frameon=True, framealpha=<NUM_LIT:0.5>)<EOL>return ax<EOL>

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.


def plot_monthly_returns_dist(returns, ax=None, **kwargs):

if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>x_axis_formatter = FuncFormatter(utils.percentage)<EOL>ax.xaxis.set_major_formatter(FuncFormatter(x_axis_formatter))<EOL>ax.tick_params(axis='<STR_LIT:x>', which='<STR_LIT>')<EOL>monthly_ret_table = ep.aggregate_returns(returns, '<STR_LIT>')<EOL>ax.hist(<EOL><NUM_LIT:100> * monthly_ret_table,<EOL>color='<STR_LIT>',<EOL>alpha=<NUM_LIT>,<EOL>bins=<NUM_LIT:20>,<EOL>**kwargs)<EOL>ax.axvline(<EOL><NUM_LIT:100> * monthly_ret_table.mean(),<EOL>color='<STR_LIT>',<EOL>linestyle='<STR_LIT>',<EOL>lw=<NUM_LIT:4>,<EOL>alpha=<NUM_LIT:1.0>)<EOL>ax.axvline(<NUM_LIT:0.0>, color='<STR_LIT>', linestyle='<STR_LIT:->', lw=<NUM_LIT:3>, alpha=<NUM_LIT>)<EOL>ax.legend(['<STR_LIT>'], frameon=True, framealpha=<NUM_LIT:0.5>)<EOL>ax.set_ylabel('<STR_LIT>')<EOL>ax.set_xlabel('<STR_LIT>')<EOL>ax.set_title("<STR_LIT>")<EOL>return ax<EOL>

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.


def plot_holdings(returns, positions, legend_loc='<STR_LIT>', ax=None, **kwargs):

if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>positions = positions.copy().drop('<STR_LIT>', axis='<STR_LIT>')<EOL>df_holdings = positions.replace(<NUM_LIT:0>, np.nan).count(axis=<NUM_LIT:1>)<EOL>df_holdings_by_month = df_holdings.resample('<STR_LIT>').mean()<EOL>df_holdings.plot(color='<STR_LIT>', alpha=<NUM_LIT>, lw=<NUM_LIT:0.5>, ax=ax, **kwargs)<EOL>df_holdings_by_month.plot(<EOL>color='<STR_LIT>',<EOL>lw=<NUM_LIT:2>,<EOL>ax=ax,<EOL>**kwargs)<EOL>ax.axhline(<EOL>df_holdings.values.mean(),<EOL>color='<STR_LIT>',<EOL>ls='<STR_LIT>',<EOL>lw=<NUM_LIT:3>)<EOL>ax.set_xlim((returns.index[<NUM_LIT:0>], returns.index[-<NUM_LIT:1>]))<EOL>leg = ax.legend(['<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'],<EOL>loc=legend_loc, frameon=True,<EOL>framealpha=<NUM_LIT:0.5>)<EOL>leg.get_frame().set_edgecolor('<STR_LIT>')<EOL>ax.set_title('<STR_LIT>')<EOL>ax.set_ylabel('<STR_LIT>')<EOL>ax.set_xlabel('<STR_LIT>')<EOL>return ax<EOL>

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.


def plot_long_short_holdings(returns, positions,<EOL>legend_loc='<STR_LIT>', ax=None, **kwargs):

if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>positions = positions.drop('<STR_LIT>', axis='<STR_LIT>')<EOL>positions = positions.replace(<NUM_LIT:0>, np.nan)<EOL>df_longs = positions[positions > <NUM_LIT:0>].count(axis=<NUM_LIT:1>)<EOL>df_shorts = positions[positions < <NUM_LIT:0>].count(axis=<NUM_LIT:1>)<EOL>lf = ax.fill_between(df_longs.index, <NUM_LIT:0>, df_longs.values,<EOL>color='<STR_LIT:g>', alpha=<NUM_LIT:0.5>, lw=<NUM_LIT>)<EOL>sf = ax.fill_between(df_shorts.index, <NUM_LIT:0>, df_shorts.values,<EOL>color='<STR_LIT:r>', alpha=<NUM_LIT:0.5>, lw=<NUM_LIT>)<EOL>bf = patches.Rectangle([<NUM_LIT:0>, <NUM_LIT:0>], <NUM_LIT:1>, <NUM_LIT:1>, color='<STR_LIT>')<EOL>leg = ax.legend([lf, sf, bf],<EOL>['<STR_LIT>' % (df_longs.max(),<EOL>df_longs.min()),<EOL>'<STR_LIT>' % (df_shorts.max(),<EOL>df_shorts.min()),<EOL>'<STR_LIT>'], loc=legend_loc, frameon=True,<EOL>framealpha=<NUM_LIT:0.5>)<EOL>leg.get_frame().set_edgecolor('<STR_LIT>')<EOL>ax.set_xlim((returns.index[<NUM_LIT:0>], returns.index[-<NUM_LIT:1>]))<EOL>ax.set_title('<STR_LIT>')<EOL>ax.set_ylabel('<STR_LIT>')<EOL>ax.set_xlabel('<STR_LIT>')<EOL>return ax<EOL>

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.


def plot_drawdown_periods(returns, top=<NUM_LIT:10>, ax=None, **kwargs):

if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>y_axis_formatter = FuncFormatter(utils.two_dec_places)<EOL>ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))<EOL>df_cum_rets = ep.cum_returns(returns, starting_value=<NUM_LIT:1.0>)<EOL>df_drawdowns = timeseries.gen_drawdown_table(returns, top=top)<EOL>df_cum_rets.plot(ax=ax, **kwargs)<EOL>lim = ax.get_ylim()<EOL>colors = sns.cubehelix_palette(len(df_drawdowns))[::-<NUM_LIT:1>]<EOL>for i, (peak, recovery) in df_drawdowns[<EOL>['<STR_LIT>', '<STR_LIT>']].iterrows():<EOL><INDENT>if pd.isnull(recovery):<EOL><INDENT>recovery = returns.index[-<NUM_LIT:1>]<EOL><DEDENT>ax.fill_between((peak, recovery),<EOL>lim[<NUM_LIT:0>],<EOL>lim[<NUM_LIT:1>],<EOL>alpha=<NUM_LIT>,<EOL>color=colors[i])<EOL><DEDENT>ax.set_ylim(lim)<EOL>ax.set_title('<STR_LIT>' % top)<EOL>ax.set_ylabel('<STR_LIT>')<EOL>ax.legend(['<STR_LIT>'], loc='<STR_LIT>',<EOL>frameon=True, framealpha=<NUM_LIT:0.5>)<EOL>ax.set_xlabel('<STR_LIT>')<EOL>return ax<EOL>

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.


def plot_drawdown_underwater(returns, ax=None, **kwargs):

if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>y_axis_formatter = FuncFormatter(utils.percentage)<EOL>ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))<EOL>df_cum_rets = ep.cum_returns(returns, starting_value=<NUM_LIT:1.0>)<EOL>running_max = np.maximum.accumulate(df_cum_rets)<EOL>underwater = -<NUM_LIT:100> * ((running_max - df_cum_rets) / running_max)<EOL>(underwater).plot(ax=ax, kind='<STR_LIT>', color='<STR_LIT>', alpha=<NUM_LIT>, **kwargs)<EOL>ax.set_ylabel('<STR_LIT>')<EOL>ax.set_title('<STR_LIT>')<EOL>ax.set_xlabel('<STR_LIT>')<EOL>return ax<EOL>

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.


def plot_perf_stats(returns, factor_returns, ax=None):

if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>bootstrap_values = timeseries.perf_stats_bootstrap(returns,<EOL>factor_returns,<EOL>return_stats=False)<EOL>bootstrap_values = bootstrap_values.drop('<STR_LIT>', axis='<STR_LIT>')<EOL>sns.boxplot(data=bootstrap_values, orient='<STR_LIT:h>', ax=ax)<EOL>return ax<EOL>

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.


def show_perf_stats(returns, factor_returns=None, positions=None,<EOL>transactions=None, turnover_denom='<STR_LIT>',<EOL>live_start_date=None, bootstrap=False,<EOL>header_rows=None):

if bootstrap:<EOL><INDENT>perf_func = timeseries.perf_stats_bootstrap<EOL><DEDENT>else:<EOL><INDENT>perf_func = timeseries.perf_stats<EOL><DEDENT>perf_stats_all = perf_func(<EOL>returns,<EOL>factor_returns=factor_returns,<EOL>positions=positions,<EOL>transactions=transactions,<EOL>turnover_denom=turnover_denom)<EOL>date_rows = OrderedDict()<EOL>if len(returns.index) > <NUM_LIT:0>:<EOL><INDENT>date_rows['<STR_LIT>'] = returns.index[<NUM_LIT:0>].strftime('<STR_LIT>')<EOL>date_rows['<STR_LIT>'] = returns.index[-<NUM_LIT:1>].strftime('<STR_LIT>')<EOL><DEDENT>if live_start_date is not None:<EOL><INDENT>live_start_date = ep.utils.get_utc_timestamp(live_start_date)<EOL>returns_is = returns[returns.index < live_start_date]<EOL>returns_oos = returns[returns.index >= live_start_date]<EOL>positions_is = None<EOL>positions_oos = None<EOL>transactions_is = None<EOL>transactions_oos = None<EOL>if positions is not None:<EOL><INDENT>positions_is = positions[positions.index < live_start_date]<EOL>positions_oos = positions[positions.index >= live_start_date]<EOL>if transactions is not None:<EOL><INDENT>transactions_is = transactions[(transactions.index <<EOL>live_start_date)]<EOL>transactions_oos = transactions[(transactions.index ><EOL>live_start_date)]<EOL><DEDENT><DEDENT>perf_stats_is = perf_func(<EOL>returns_is,<EOL>factor_returns=factor_returns,<EOL>positions=positions_is,<EOL>transactions=transactions_is,<EOL>turnover_denom=turnover_denom)<EOL>perf_stats_oos = perf_func(<EOL>returns_oos,<EOL>factor_returns=factor_returns,<EOL>positions=positions_oos,<EOL>transactions=transactions_oos,<EOL>turnover_denom=turnover_denom)<EOL>if len(returns.index) > <NUM_LIT:0>:<EOL><INDENT>date_rows['<STR_LIT>'] = int(len(returns_is) /<EOL>APPROX_BDAYS_PER_MONTH)<EOL>date_rows['<STR_LIT>'] = int(len(returns_oos) /<EOL>APPROX_BDAYS_PER_MONTH)<EOL><DEDENT>perf_stats = pd.concat(OrderedDict([<EOL>('<STR_LIT>', perf_stats_is),<EOL>('<STR_LIT>', perf_stats_oos),<EOL>('<STR_LIT>', perf_stats_all),<EOL>]), axis=<NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>if len(returns.index) > <NUM_LIT:0>:<EOL><INDENT>date_rows['<STR_LIT>'] = int(len(returns) /<EOL>APPROX_BDAYS_PER_MONTH)<EOL><DEDENT>perf_stats = pd.DataFrame(perf_stats_all, columns=['<STR_LIT>'])<EOL><DEDENT>for column in perf_stats.columns:<EOL><INDENT>for stat, value in perf_stats[column].iteritems():<EOL><INDENT>if stat in STAT_FUNCS_PCT:<EOL><INDENT>perf_stats.loc[stat, column] = str(np.round(value * <NUM_LIT:100>,<EOL><NUM_LIT:1>)) + '<STR_LIT:%>'<EOL><DEDENT><DEDENT><DEDENT>if header_rows is None:<EOL><INDENT>header_rows = date_rows<EOL><DEDENT>else:<EOL><INDENT>header_rows = OrderedDict(header_rows)<EOL>header_rows.update(date_rows)<EOL><DEDENT>utils.print_table(<EOL>perf_stats,<EOL>float_format='<STR_LIT>'.format,<EOL>header_rows=header_rows,<EOL>)<EOL>

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 ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>ax.set_label('<STR_LIT>')<EOL>ax.set_ylabel('<STR_LIT>')<EOL>if live_start_date is not None:<EOL><INDENT>live_start_date = ep.utils.get_utc_timestamp(live_start_date)<EOL>is_returns = returns.loc[returns.index < live_start_date]<EOL>oos_returns = returns.loc[returns.index >= live_start_date]<EOL>is_returns.plot(ax=ax, color='<STR_LIT:g>')<EOL>oos_returns.plot(ax=ax, color='<STR_LIT:r>')<EOL><DEDENT>else:<EOL><INDENT>returns.plot(ax=ax, color='<STR_LIT:g>')<EOL><DEDENT>return ax<EOL>

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:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>ax.set_xlabel('<STR_LIT>')<EOL>ax.set_ylabel('<STR_LIT>')<EOL>ax.set_yscale('<STR_LIT>' if logy else '<STR_LIT>')<EOL>if volatility_match and factor_returns is None:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>elif volatility_match and factor_returns is not None:<EOL><INDENT>bmark_vol = factor_returns.loc[returns.index].std()<EOL>returns = (returns / returns.std()) * bmark_vol<EOL><DEDENT>cum_rets = ep.cum_returns(returns, <NUM_LIT:1.0>)<EOL>y_axis_formatter = FuncFormatter(utils.two_dec_places)<EOL>ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))<EOL>if factor_returns is not None:<EOL><INDENT>cum_factor_returns = ep.cum_returns(<EOL>factor_returns[cum_rets.index], <NUM_LIT:1.0>)<EOL>cum_factor_returns.plot(lw=<NUM_LIT:2>, color='<STR_LIT>',<EOL>label=factor_returns.name, alpha=<NUM_LIT>,<EOL>ax=ax, **kwargs)<EOL><DEDENT>if live_start_date is not None:<EOL><INDENT>live_start_date = ep.utils.get_utc_timestamp(live_start_date)<EOL>is_cum_returns = cum_rets.loc[cum_rets.index < live_start_date]<EOL>oos_cum_returns = cum_rets.loc[cum_rets.index >= live_start_date]<EOL><DEDENT>else:<EOL><INDENT>is_cum_returns = cum_rets<EOL>oos_cum_returns = pd.Series([])<EOL><DEDENT>is_cum_returns.plot(lw=<NUM_LIT:3>, color='<STR_LIT>', alpha=<NUM_LIT>,<EOL>label='<STR_LIT>', ax=ax, **kwargs)<EOL>if len(oos_cum_returns) > <NUM_LIT:0>:<EOL><INDENT>oos_cum_returns.plot(lw=<NUM_LIT:4>, color='<STR_LIT>', alpha=<NUM_LIT>,<EOL>label='<STR_LIT>', ax=ax, **kwargs)<EOL>if cone_std is not None:<EOL><INDENT>if isinstance(cone_std, (float, int)):<EOL><INDENT>cone_std = [cone_std]<EOL><DEDENT>is_returns = returns.loc[returns.index < live_start_date]<EOL>cone_bounds = cone_function(<EOL>is_returns,<EOL>len(oos_cum_returns),<EOL>cone_std=cone_std,<EOL>starting_value=is_cum_returns[-<NUM_LIT:1>])<EOL>cone_bounds = cone_bounds.set_index(oos_cum_returns.index)<EOL>for std in cone_std:<EOL><INDENT>ax.fill_between(cone_bounds.index,<EOL>cone_bounds[float(std)],<EOL>cone_bounds[float(-std)],<EOL>color='<STR_LIT>', alpha=<NUM_LIT:0.5>)<EOL><DEDENT><DEDENT><DEDENT>if legend_loc is not None:<EOL><INDENT>ax.legend(loc=legend_loc, frameon=True, framealpha=<NUM_LIT:0.5>)<EOL><DEDENT>ax.axhline(<NUM_LIT:1.0>, linestyle='<STR_LIT>', color='<STR_LIT>', lw=<NUM_LIT:2>)<EOL>return ax<EOL>

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.


def plot_rolling_beta(returns, factor_returns, legend_loc='<STR_LIT>',<EOL>ax=None, **kwargs):

if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>y_axis_formatter = FuncFormatter(utils.two_dec_places)<EOL>ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))<EOL>ax.set_title("<STR_LIT>" + str(factor_returns.name))<EOL>ax.set_ylabel('<STR_LIT>')<EOL>rb_1 = timeseries.rolling_beta(<EOL>returns, factor_returns, rolling_window=APPROX_BDAYS_PER_MONTH * <NUM_LIT:6>)<EOL>rb_1.plot(color='<STR_LIT>', lw=<NUM_LIT:3>, alpha=<NUM_LIT>, ax=ax, **kwargs)<EOL>rb_2 = timeseries.rolling_beta(<EOL>returns, factor_returns, rolling_window=APPROX_BDAYS_PER_MONTH * <NUM_LIT:12>)<EOL>rb_2.plot(color='<STR_LIT>', lw=<NUM_LIT:3>, alpha=<NUM_LIT>, ax=ax, **kwargs)<EOL>ax.axhline(rb_1.mean(), color='<STR_LIT>', linestyle='<STR_LIT>', lw=<NUM_LIT:3>)<EOL>ax.axhline(<NUM_LIT:0.0>, color='<STR_LIT>', linestyle='<STR_LIT:->', lw=<NUM_LIT:2>)<EOL>ax.set_xlabel('<STR_LIT>')<EOL>ax.legend(['<STR_LIT>',<EOL>'<STR_LIT>'],<EOL>loc=legend_loc, frameon=True, framealpha=<NUM_LIT:0.5>)<EOL>ax.set_ylim((-<NUM_LIT:1.0>, <NUM_LIT:1.0>))<EOL>return ax<EOL>

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.


def plot_rolling_volatility(returns, factor_returns=None,<EOL>rolling_window=APPROX_BDAYS_PER_MONTH * <NUM_LIT:6>,<EOL>legend_loc='<STR_LIT>', ax=None, **kwargs):

if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>y_axis_formatter = FuncFormatter(utils.two_dec_places)<EOL>ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))<EOL>rolling_vol_ts = timeseries.rolling_volatility(<EOL>returns, rolling_window)<EOL>rolling_vol_ts.plot(alpha=<NUM_LIT>, lw=<NUM_LIT:3>, color='<STR_LIT>', ax=ax,<EOL>**kwargs)<EOL>if factor_returns is not None:<EOL><INDENT>rolling_vol_ts_factor = timeseries.rolling_volatility(<EOL>factor_returns, rolling_window)<EOL>rolling_vol_ts_factor.plot(alpha=<NUM_LIT>, lw=<NUM_LIT:3>, color='<STR_LIT>', ax=ax,<EOL>**kwargs)<EOL><DEDENT>ax.set_title('<STR_LIT>')<EOL>ax.axhline(<EOL>rolling_vol_ts.mean(),<EOL>color='<STR_LIT>',<EOL>linestyle='<STR_LIT>',<EOL>lw=<NUM_LIT:3>)<EOL>ax.axhline(<NUM_LIT:0.0>, color='<STR_LIT>', linestyle='<STR_LIT:->', lw=<NUM_LIT:2>)<EOL>ax.set_ylabel('<STR_LIT>')<EOL>ax.set_xlabel('<STR_LIT>')<EOL>if factor_returns is None:<EOL><INDENT>ax.legend(['<STR_LIT>', '<STR_LIT>'],<EOL>loc=legend_loc, frameon=True, framealpha=<NUM_LIT:0.5>)<EOL><DEDENT>else:<EOL><INDENT>ax.legend(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>'],<EOL>loc=legend_loc, frameon=True, framealpha=<NUM_LIT:0.5>)<EOL><DEDENT>return ax<EOL>

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.


def plot_rolling_sharpe(returns, factor_returns=None,<EOL>rolling_window=APPROX_BDAYS_PER_MONTH * <NUM_LIT:6>,<EOL>legend_loc='<STR_LIT>', ax=None, **kwargs):

if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>y_axis_formatter = FuncFormatter(utils.two_dec_places)<EOL>ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))<EOL>rolling_sharpe_ts = timeseries.rolling_sharpe(<EOL>returns, rolling_window)<EOL>rolling_sharpe_ts.plot(alpha=<NUM_LIT>, lw=<NUM_LIT:3>, color='<STR_LIT>', ax=ax,<EOL>**kwargs)<EOL>if factor_returns is not None:<EOL><INDENT>rolling_sharpe_ts_factor = timeseries.rolling_sharpe(<EOL>factor_returns, rolling_window)<EOL>rolling_sharpe_ts_factor.plot(alpha=<NUM_LIT>, lw=<NUM_LIT:3>, color='<STR_LIT>', ax=ax,<EOL>**kwargs)<EOL><DEDENT>ax.set_title('<STR_LIT>')<EOL>ax.axhline(<EOL>rolling_sharpe_ts.mean(),<EOL>color='<STR_LIT>',<EOL>linestyle='<STR_LIT>',<EOL>lw=<NUM_LIT:3>)<EOL>ax.axhline(<NUM_LIT:0.0>, color='<STR_LIT>', linestyle='<STR_LIT:->', lw=<NUM_LIT:3>)<EOL>ax.set_ylabel('<STR_LIT>')<EOL>ax.set_xlabel('<STR_LIT>')<EOL>if factor_returns is None:<EOL><INDENT>ax.legend(['<STR_LIT>', '<STR_LIT>'],<EOL>loc=legend_loc, frameon=True, framealpha=<NUM_LIT:0.5>)<EOL><DEDENT>else:<EOL><INDENT>ax.legend(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>'],<EOL>loc=legend_loc, frameon=True, framealpha=<NUM_LIT:0.5>)<EOL><DEDENT>return ax<EOL>

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.


def plot_gross_leverage(returns, positions, ax=None, **kwargs):

if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>gl = timeseries.gross_lev(positions)<EOL>gl.plot(lw=<NUM_LIT:0.5>, color='<STR_LIT>', legend=False, ax=ax, **kwargs)<EOL>ax.axhline(gl.mean(), color='<STR_LIT:g>', linestyle='<STR_LIT>', lw=<NUM_LIT:3>)<EOL>ax.set_title('<STR_LIT>')<EOL>ax.set_ylabel('<STR_LIT>')<EOL>ax.set_xlabel('<STR_LIT>')<EOL>return ax<EOL>

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.


def plot_exposures(returns, positions, ax=None, **kwargs):

if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>pos_no_cash = positions.drop('<STR_LIT>', axis=<NUM_LIT:1>)<EOL>l_exp = pos_no_cash[pos_no_cash > <NUM_LIT:0>].sum(axis=<NUM_LIT:1>) / positions.sum(axis=<NUM_LIT:1>)<EOL>s_exp = pos_no_cash[pos_no_cash < <NUM_LIT:0>].sum(axis=<NUM_LIT:1>) / positions.sum(axis=<NUM_LIT:1>)<EOL>net_exp = pos_no_cash.sum(axis=<NUM_LIT:1>) / positions.sum(axis=<NUM_LIT:1>)<EOL>ax.fill_between(l_exp.index,<EOL><NUM_LIT:0>,<EOL>l_exp.values,<EOL>label='<STR_LIT>', color='<STR_LIT>', alpha=<NUM_LIT:0.5>)<EOL>ax.fill_between(s_exp.index,<EOL><NUM_LIT:0>,<EOL>s_exp.values,<EOL>label='<STR_LIT>', color='<STR_LIT>', alpha=<NUM_LIT:0.5>)<EOL>ax.plot(net_exp.index, net_exp.values,<EOL>label='<STR_LIT>', color='<STR_LIT>', linestyle='<STR_LIT>')<EOL>ax.set_xlim((returns.index[<NUM_LIT:0>], returns.index[-<NUM_LIT:1>]))<EOL>ax.set_title("<STR_LIT>")<EOL>ax.set_ylabel('<STR_LIT>')<EOL>ax.legend(loc='<STR_LIT>', frameon=True, framealpha=<NUM_LIT:0.5>)<EOL>ax.set_xlabel('<STR_LIT>')<EOL>return ax<EOL>

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.


positions_alloc = positions_alloc.copy()<EOL>positions_alloc.columns = positions_alloc.columns.map(utils.format_asset)<EOL>df_top_long, df_top_short, df_top_abs = pos.get_top_long_short_abs(<EOL>positions_alloc)<EOL>if show_and_plot == <NUM_LIT:1> or show_and_plot == <NUM_LIT:2>:<EOL><INDENT>utils.print_table(pd.DataFrame(df_top_long * <NUM_LIT:100>, columns=['<STR_LIT>']),<EOL>float_format='<STR_LIT>'.format,<EOL>name='<STR_LIT>')<EOL>utils.print_table(pd.DataFrame(df_top_short * <NUM_LIT:100>, columns=['<STR_LIT>']),<EOL>float_format='<STR_LIT>'.format,<EOL>name='<STR_LIT>')<EOL>utils.print_table(pd.DataFrame(df_top_abs * <NUM_LIT:100>, columns=['<STR_LIT>']),<EOL>float_format='<STR_LIT>'.format,<EOL>name='<STR_LIT>')<EOL><DEDENT>if show_and_plot == <NUM_LIT:0> or show_and_plot == <NUM_LIT:2>:<EOL><INDENT>if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>positions_alloc[df_top_abs.index].plot(<EOL>title='<STR_LIT>',<EOL>alpha=<NUM_LIT:0.5>, ax=ax, **kwargs)<EOL>if legend_loc == '<STR_LIT>':<EOL><INDENT>box = ax.get_position()<EOL>ax.set_position([box.x0, box.y0 + box.height * <NUM_LIT:0.1>,<EOL>box.width, box.height * <NUM_LIT>])<EOL>ax.legend(loc='<STR_LIT>', frameon=True, framealpha=<NUM_LIT:0.5>,<EOL>bbox_to_anchor=(<NUM_LIT:0.5>, -<NUM_LIT>), ncol=<NUM_LIT:5>)<EOL><DEDENT>else:<EOL><INDENT>ax.legend(loc=legend_loc)<EOL><DEDENT>ax.set_xlim((returns.index[<NUM_LIT:0>], returns.index[-<NUM_LIT:1>]))<EOL>ax.set_ylabel('<STR_LIT>')<EOL>if hide_positions:<EOL><INDENT>ax.legend_.remove()<EOL><DEDENT>return ax<EOL><DEDENT>

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

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.
show_and_plot : int, 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_positions : bool, optional
    If True, will not output any symbol names.
legend_loc : matplotlib.loc, optional
    The location of the legend on the plot.
    By default, the legend will display below the plot.
ax : matplotlib.Axes, optional
    Axes upon which to plot.
**kwargs, optional
    Passed to plotting function.

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


def plot_max_median_position_concentration(positions, ax=None, **kwargs):

if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>alloc_summary = pos.get_max_median_position_concentration(positions)<EOL>colors = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>alloc_summary.plot(linewidth=<NUM_LIT:1>, color=colors, alpha=<NUM_LIT>, ax=ax)<EOL>ax.legend(loc='<STR_LIT>', frameon=True, framealpha=<NUM_LIT:0.5>)<EOL>ax.set_ylabel('<STR_LIT>')<EOL>ax.set_title('<STR_LIT>')<EOL>return ax<EOL>

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.


def plot_sector_allocations(returns, sector_alloc, ax=None, **kwargs):

if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>sector_alloc.plot(title='<STR_LIT>',<EOL>alpha=<NUM_LIT:0.5>, ax=ax, **kwargs)<EOL>box = ax.get_position()<EOL>ax.set_position([box.x0, box.y0 + box.height * <NUM_LIT:0.1>,<EOL>box.width, box.height * <NUM_LIT>])<EOL>ax.legend(loc='<STR_LIT>', frameon=True, framealpha=<NUM_LIT:0.5>,<EOL>bbox_to_anchor=(<NUM_LIT:0.5>, -<NUM_LIT>), ncol=<NUM_LIT:5>)<EOL>ax.set_xlim((sector_alloc.index[<NUM_LIT:0>], sector_alloc.index[-<NUM_LIT:1>]))<EOL>ax.set_ylabel('<STR_LIT>')<EOL>ax.set_xlabel('<STR_LIT>')<EOL>return ax<EOL>

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.


def plot_return_quantiles(returns, live_start_date=None, ax=None, **kwargs):

if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>is_returns = returns if live_start_date is Noneelse returns.loc[returns.index < live_start_date]<EOL>is_weekly = ep.aggregate_returns(is_returns, '<STR_LIT>')<EOL>is_monthly = ep.aggregate_returns(is_returns, '<STR_LIT>')<EOL>sns.boxplot(data=[is_returns, is_weekly, is_monthly],<EOL>palette=["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"],<EOL>ax=ax, **kwargs)<EOL>if live_start_date is not None:<EOL><INDENT>oos_returns = returns.loc[returns.index >= live_start_date]<EOL>oos_weekly = ep.aggregate_returns(oos_returns, '<STR_LIT>')<EOL>oos_monthly = ep.aggregate_returns(oos_returns, '<STR_LIT>')<EOL>sns.swarmplot(data=[oos_returns, oos_weekly, oos_monthly], ax=ax,<EOL>color="<STR_LIT>",<EOL>marker="<STR_LIT:d>", **kwargs)<EOL>red_dots = matplotlib.lines.Line2D([], [], color="<STR_LIT>", marker="<STR_LIT:d>",<EOL>label="<STR_LIT>",<EOL>linestyle='<STR_LIT>')<EOL>ax.legend(handles=[red_dots], frameon=True, framealpha=<NUM_LIT:0.5>)<EOL><DEDENT>ax.set_xticklabels(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>'])<EOL>ax.set_title('<STR_LIT>')<EOL>return ax<EOL>

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.


def plot_turnover(returns, transactions, positions,<EOL>legend_loc='<STR_LIT>', ax=None, **kwargs):

if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>y_axis_formatter = FuncFormatter(utils.two_dec_places)<EOL>ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))<EOL>df_turnover = txn.get_turnover(positions, transactions)<EOL>df_turnover_by_month = df_turnover.resample("<STR_LIT:M>").mean()<EOL>df_turnover.plot(color='<STR_LIT>', alpha=<NUM_LIT:1.0>, lw=<NUM_LIT:0.5>, ax=ax, **kwargs)<EOL>df_turnover_by_month.plot(<EOL>color='<STR_LIT>',<EOL>alpha=<NUM_LIT:0.5>,<EOL>lw=<NUM_LIT:2>,<EOL>ax=ax,<EOL>**kwargs)<EOL>ax.axhline(<EOL>df_turnover.mean(), color='<STR_LIT>', linestyle='<STR_LIT>', lw=<NUM_LIT:3>, alpha=<NUM_LIT:1.0>)<EOL>ax.legend(['<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'],<EOL>loc=legend_loc, frameon=True, framealpha=<NUM_LIT:0.5>)<EOL>ax.set_title('<STR_LIT>')<EOL>ax.set_xlim((returns.index[<NUM_LIT:0>], returns.index[-<NUM_LIT:1>]))<EOL>ax.set_ylim((<NUM_LIT:0>, <NUM_LIT:2>))<EOL>ax.set_ylabel('<STR_LIT>')<EOL>ax.set_xlabel('<STR_LIT>')<EOL>return ax<EOL>

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.


def plot_slippage_sweep(returns, positions, transactions,<EOL>slippage_params=(<NUM_LIT:3>, <NUM_LIT:8>, <NUM_LIT:10>, <NUM_LIT:12>, <NUM_LIT:15>, <NUM_LIT:20>, <NUM_LIT:50>),<EOL>ax=None, **kwargs):

if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>slippage_sweep = pd.DataFrame()<EOL>for bps in slippage_params:<EOL><INDENT>adj_returns = txn.adjust_returns_for_slippage(returns, positions,<EOL>transactions, bps)<EOL>label = str(bps) + "<STR_LIT>"<EOL>slippage_sweep[label] = ep.cum_returns(adj_returns, <NUM_LIT:1>)<EOL><DEDENT>slippage_sweep.plot(alpha=<NUM_LIT:1.0>, lw=<NUM_LIT:0.5>, ax=ax)<EOL>ax.set_title('<STR_LIT>')<EOL>ax.set_ylabel('<STR_LIT>')<EOL>ax.legend(loc='<STR_LIT>', frameon=True, framealpha=<NUM_LIT:0.5>)<EOL>return ax<EOL>

Plots equity curves at different per-dollar slippage assumptions.

Parameters
----------
returns : pd.Series
    Timeseries of portfolio returns to be adjusted for various
    degrees of slippage.
positions : pd.DataFrame
    Daily net position values.
     - 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.
slippage_params: tuple
    Slippage pameters to apply to the return time series (in
    basis points).
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.


def plot_slippage_sensitivity(returns, positions, transactions,<EOL>ax=None, **kwargs):

if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>avg_returns_given_slippage = pd.Series()<EOL>for bps in range(<NUM_LIT:1>, <NUM_LIT:100>):<EOL><INDENT>adj_returns = txn.adjust_returns_for_slippage(returns, positions,<EOL>transactions, bps)<EOL>avg_returns = ep.annual_return(adj_returns)<EOL>avg_returns_given_slippage.loc[bps] = avg_returns<EOL><DEDENT>avg_returns_given_slippage.plot(alpha=<NUM_LIT:1.0>, lw=<NUM_LIT:2>, ax=ax)<EOL>ax.set_title('<STR_LIT>')<EOL>ax.set_xticks(np.arange(<NUM_LIT:0>, <NUM_LIT:100>, <NUM_LIT:10>))<EOL>ax.set_ylabel('<STR_LIT>')<EOL>ax.set_xlabel('<STR_LIT>')<EOL>return ax<EOL>

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

Parameters
----------
returns : pd.Series
    Timeseries of portfolio returns to be adjusted for various
    degrees of slippage.
positions : pd.DataFrame
    Daily net position values.
     - 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.
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.


def plot_daily_turnover_hist(transactions, positions,<EOL>ax=None, **kwargs):

if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>turnover = txn.get_turnover(positions, transactions)<EOL>sns.distplot(turnover, ax=ax, **kwargs)<EOL>ax.set_title('<STR_LIT>')<EOL>ax.set_xlabel('<STR_LIT>')<EOL>return ax<EOL>

Plots a histogram of daily turnover rates.

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


def plot_daily_volume(returns, transactions, ax=None, **kwargs):

if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>daily_txn = txn.get_txn_vol(transactions)<EOL>daily_txn.txn_shares.plot(alpha=<NUM_LIT:1.0>, lw=<NUM_LIT:0.5>, ax=ax, **kwargs)<EOL>ax.axhline(daily_txn.txn_shares.mean(), color='<STR_LIT>',<EOL>linestyle='<STR_LIT>', lw=<NUM_LIT:3>, alpha=<NUM_LIT:1.0>)<EOL>ax.set_title('<STR_LIT>')<EOL>ax.set_xlim((returns.index[<NUM_LIT:0>], returns.index[-<NUM_LIT:1>]))<EOL>ax.set_ylabel('<STR_LIT>')<EOL>ax.set_xlabel('<STR_LIT>')<EOL>return ax<EOL>

Plots trading volume per day vs. date.

Also displays 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.
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.


def plot_txn_time_hist(transactions, bin_minutes=<NUM_LIT:5>, tz='<STR_LIT>',<EOL>ax=None, **kwargs):

if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>txn_time = transactions.copy()<EOL>txn_time.index = txn_time.index.tz_convert(pytz.timezone(tz))<EOL>txn_time.index = txn_time.index.map(lambda x: x.hour * <NUM_LIT> + x.minute)<EOL>txn_time['<STR_LIT>'] = (txn_time.amount * txn_time.price).abs()<EOL>txn_time = txn_time.groupby(level=<NUM_LIT:0>).sum().reindex(index=range(<NUM_LIT>, <NUM_LIT>))<EOL>txn_time.index = (txn_time.index / bin_minutes).astype(int) * bin_minutes<EOL>txn_time = txn_time.groupby(level=<NUM_LIT:0>).sum()<EOL>txn_time['<STR_LIT>'] = txn_time.index.map(lambda x:<EOL>str(datetime.time(int(x / <NUM_LIT>),<EOL>x % <NUM_LIT>))[:-<NUM_LIT:3>])<EOL>trade_value_sum = txn_time.trade_value.sum()<EOL>txn_time.trade_value = txn_time.trade_value.fillna(<NUM_LIT:0>) / trade_value_sum<EOL>ax.bar(txn_time.index, txn_time.trade_value, width=bin_minutes, **kwargs)<EOL>ax.set_xlim(<NUM_LIT>, <NUM_LIT>)<EOL>ax.set_xticks(txn_time.index[::int(<NUM_LIT:30> / bin_minutes)])<EOL>ax.set_xticklabels(txn_time.time_str[::int(<NUM_LIT:30> / bin_minutes)])<EOL>ax.set_title('<STR_LIT>')<EOL>ax.set_ylabel('<STR_LIT>')<EOL>ax.set_xlabel('<STR_LIT>')<EOL>return ax<EOL>

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

Parameters
----------
transactions : pd.DataFrame
    Prices and amounts of executed trades. One row per trade.
     - See full explanation in tears.create_full_tear_sheet.
bin_minutes : float, optional
    Sizes of the bins in minutes, defaults to 5 minutes.
tz : str, optional
    Time zone to plot against. Note that if the specified
    zone does not apply daylight savings, the distribution
    may be partially offset.
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.


drawdown_df = timeseries.gen_drawdown_table(returns, top=top)<EOL>utils.print_table(<EOL>drawdown_df.sort_values('<STR_LIT>', ascending=False),<EOL>name='<STR_LIT>',<EOL>float_format='<STR_LIT>'.format,<EOL>)<EOL>

Prints information about the worst drawdown periods.

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

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 5).


def plot_monthly_returns_timeseries(returns, ax=None, **kwargs):

def cumulate_returns(x):<EOL><INDENT>return ep.cum_returns(x)[-<NUM_LIT:1>]<EOL><DEDENT>if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>monthly_rets = returns.resample('<STR_LIT:M>').apply(lambda x: cumulate_returns(x))<EOL>monthly_rets = monthly_rets.to_period()<EOL>sns.barplot(x=monthly_rets.index,<EOL>y=monthly_rets.values,<EOL>color='<STR_LIT>')<EOL>locs, labels = plt.xticks()<EOL>plt.setp(labels, rotation=<NUM_LIT>)<EOL>xticks_coord = []<EOL>xticks_label = []<EOL>count = <NUM_LIT:0><EOL>for i in monthly_rets.index:<EOL><INDENT>if i.month == <NUM_LIT:1>:<EOL><INDENT>xticks_label.append(i)<EOL>xticks_coord.append(count)<EOL>ax.axvline(count, color='<STR_LIT>', ls='<STR_LIT>', alpha=<NUM_LIT>)<EOL><DEDENT>count += <NUM_LIT:1><EOL><DEDENT>ax.axhline(<NUM_LIT:0.0>, color='<STR_LIT>', ls='<STR_LIT:->')<EOL>ax.set_xticks(xticks_coord)<EOL>ax.set_xticklabels(xticks_label)<EOL>return ax<EOL>

Plots monthly returns as a timeseries.

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.


def plot_round_trip_lifetimes(round_trips, disp_amount=<NUM_LIT:16>, lsize=<NUM_LIT>, ax=None):

if ax is None:<EOL><INDENT>ax = plt.subplot()<EOL><DEDENT>symbols_sample = round_trips.symbol.unique()<EOL>np.random.seed(<NUM_LIT:1>)<EOL>sample = np.random.choice(round_trips.symbol.unique(), replace=False,<EOL>size=min(disp_amount, len(symbols_sample)))<EOL>sample_round_trips = round_trips[round_trips.symbol.isin(sample)]<EOL>symbol_idx = pd.Series(np.arange(len(sample)), index=sample)<EOL>for symbol, sym_round_trips in sample_round_trips.groupby('<STR_LIT>'):<EOL><INDENT>for _, row in sym_round_trips.iterrows():<EOL><INDENT>c = '<STR_LIT:b>' if row.long else '<STR_LIT:r>'<EOL>y_ix = symbol_idx[symbol] + <NUM_LIT><EOL>ax.plot([row['<STR_LIT>'], row['<STR_LIT>']],<EOL>[y_ix, y_ix], color=c,<EOL>linewidth=lsize, solid_capstyle='<STR_LIT>')<EOL><DEDENT><DEDENT>ax.set_yticks(range(disp_amount))<EOL>ax.set_yticklabels([utils.format_asset(s) for s in sample])<EOL>ax.set_ylim((-<NUM_LIT:0.5>, min(len(sample), disp_amount) - <NUM_LIT:0.5>))<EOL>blue = patches.Rectangle([<NUM_LIT:0>, <NUM_LIT:0>], <NUM_LIT:1>, <NUM_LIT:1>, color='<STR_LIT:b>', label='<STR_LIT>')<EOL>red = patches.Rectangle([<NUM_LIT:0>, <NUM_LIT:0>], <NUM_LIT:1>, <NUM_LIT:1>, color='<STR_LIT:r>', label='<STR_LIT>')<EOL>leg = ax.legend(handles=[blue, red], loc='<STR_LIT>',<EOL>frameon=True, framealpha=<NUM_LIT:0.5>)<EOL>leg.get_frame().set_edgecolor('<STR_LIT>')<EOL>ax.grid(False)<EOL>return ax<EOL>

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

Parameters
----------
round_trips : pd.DataFrame
    DataFrame with one row per round trip trade.
    - See full explanation in round_trips.extract_round_trips
ax : matplotlib.Axes, optional
    Axes upon which to plot.

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


total_pnl = round_trips['<STR_LIT>'].sum()<EOL>pnl_attribution = round_trips.groupby('<STR_LIT>')['<STR_LIT>'].sum() / total_pnl<EOL>pnl_attribution.name = '<STR_LIT>'<EOL>pnl_attribution.index = pnl_attribution.index.map(utils.format_asset)<EOL>utils.print_table(<EOL>pnl_attribution.sort_values(<EOL>inplace=False,<EOL>ascending=False,<EOL>),<EOL>name='<STR_LIT>',<EOL>float_format='<STR_LIT>'.format,<EOL>)<EOL>

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

Parameters
----------
round_trips : pd.DataFrame
    DataFrame with one row per round trip trade.
    - See full explanation in round_trips.extract_round_trips
ax : matplotlib.Axes, optional
    Axes upon which to plot.

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


x = np.linspace(<NUM_LIT:0>, <NUM_LIT:1.>, <NUM_LIT>)<EOL>round_trips['<STR_LIT>'] = round_trips.pnl > <NUM_LIT:0><EOL>dist = sp.stats.beta(round_trips.profitable.sum(),<EOL>(~round_trips.profitable).sum())<EOL>y = dist.pdf(x)<EOL>lower_perc = dist.ppf(<NUM_LIT>)<EOL>upper_perc = dist.ppf(<NUM_LIT>)<EOL>lower_plot = dist.ppf(<NUM_LIT>)<EOL>upper_plot = dist.ppf(<NUM_LIT>)<EOL>if ax is None:<EOL><INDENT>ax = plt.subplot()<EOL><DEDENT>ax.plot(x, y)<EOL>ax.axvline(lower_perc, color='<STR_LIT>')<EOL>ax.axvline(upper_perc, color='<STR_LIT>')<EOL>ax.set_xlabel('<STR_LIT>')<EOL>ax.set_ylabel('<STR_LIT>')<EOL>ax.set_xlim(lower_plot, upper_plot)<EOL>ax.set_ylim((<NUM_LIT:0>, y.max() + <NUM_LIT:1.>))<EOL>return ax<EOL>

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

Parameters
----------
round_trips : pd.DataFrame
    DataFrame with one row per round trip trade.
    - See full explanation in round_trips.extract_round_trips
ax : matplotlib.Axes, optional
    Axes upon which to plot.

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


def plot_cones(name, bounds, oos_returns, num_samples=<NUM_LIT:1000>, ax=None,<EOL>cone_std=(<NUM_LIT:1.>, <NUM_LIT>, <NUM_LIT>), random_seed=None, num_strikes=<NUM_LIT:3>):

if ax is None:<EOL><INDENT>fig = figure.Figure(figsize=(<NUM_LIT:10>, <NUM_LIT:8>))<EOL>FigureCanvasAgg(fig)<EOL>axes = fig.add_subplot(<NUM_LIT>)<EOL><DEDENT>else:<EOL><INDENT>axes = ax<EOL><DEDENT>returns = ep.cum_returns(oos_returns, starting_value=<NUM_LIT:1.>)<EOL>bounds_tmp = bounds.copy()<EOL>returns_tmp = returns.copy()<EOL>cone_start = returns.index[<NUM_LIT:0>]<EOL>colors = ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]<EOL>for c in range(num_strikes + <NUM_LIT:1>):<EOL><INDENT>if c > <NUM_LIT:0>:<EOL><INDENT>tmp = returns.loc[cone_start:]<EOL>bounds_tmp = bounds_tmp.iloc[<NUM_LIT:0>:len(tmp)]<EOL>bounds_tmp = bounds_tmp.set_index(tmp.index)<EOL>crossing = (tmp < bounds_tmp[float(-<NUM_LIT>)].iloc[:len(tmp)])<EOL>if crossing.sum() <= <NUM_LIT:0>:<EOL><INDENT>break<EOL><DEDENT>cone_start = crossing.loc[crossing].index[<NUM_LIT:0>]<EOL>returns_tmp = returns.loc[cone_start:]<EOL>bounds_tmp = (bounds - (<NUM_LIT:1> - returns.loc[cone_start]))<EOL><DEDENT>for std in cone_std:<EOL><INDENT>x = returns_tmp.index<EOL>y1 = bounds_tmp[float(std)].iloc[:len(returns_tmp)]<EOL>y2 = bounds_tmp[float(-std)].iloc[:len(returns_tmp)]<EOL>axes.fill_between(x, y1, y2, color=colors[c], alpha=<NUM_LIT:0.5>)<EOL><DEDENT><DEDENT>label = '<STR_LIT>'.format((returns.iloc[-<NUM_LIT:1>] - <NUM_LIT:1>) * <NUM_LIT:100>)<EOL>axes.plot(returns.index, returns.values, color='<STR_LIT>', lw=<NUM_LIT>,<EOL>label=label)<EOL>if name is not None:<EOL><INDENT>axes.set_title(name)<EOL><DEDENT>axes.axhline(<NUM_LIT:1>, color='<STR_LIT>', alpha=<NUM_LIT>)<EOL>axes.legend(frameon=True, framealpha=<NUM_LIT:0.5>)<EOL>if ax is None:<EOL><INDENT>return fig<EOL><DEDENT>else:<EOL><INDENT>return axes<EOL><DEDENT>

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
----------
name : str
    Account name to be used as figure title.
bounds : pandas.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_returns : pandas.core.frame.DataFrame
    Non-cumulative out-of-sample returns.
num_samples : int
    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.
ax : matplotlib.Axes, optional
    Axes upon which to plot.
cone_std : 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.
random_seed : int
    Seed for the pseudorandom number generator used by the pandas
    sample method.
num_strikes : int
    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.

ax : matplotlib.Axes
    The axes that were plotted on.
fig : matplotlib.figure
    The figure instance which contains all the plot elements.


return values.divide(<EOL>values.sum(axis='<STR_LIT>'),<EOL>axis='<STR_LIT>'<EOL>)<EOL>

Determines a portfolio's allocations.

Parameters
----------
values : pd.DataFrame
    Contains position values or amounts.

Returns
-------
allocations : pd.DataFrame
    Positions and their allocations.


positions = positions.drop('<STR_LIT>', axis='<STR_LIT>')<EOL>df_max = positions.max()<EOL>df_min = positions.min()<EOL>df_abs_max = positions.abs().max()<EOL>df_top_long = df_max[df_max > <NUM_LIT:0>].nlargest(top)<EOL>df_top_short = df_min[df_min < <NUM_LIT:0>].nsmallest(top)<EOL>df_top_abs = df_abs_max.nlargest(top)<EOL>return df_top_long, df_top_short, df_top_abs<EOL>

Finds the top long, short, and absolute positions.

Parameters
----------
positions : pd.DataFrame
    The positions that the strategy takes over time.
top : int, optional
    How many of each to find (default 10).

Returns
-------
df_top_long : pd.DataFrame
    Top long positions.
df_top_short : pd.DataFrame
    Top short positions.
df_top_abs : pd.DataFrame
    Top absolute positions.


expos = get_percent_alloc(positions)<EOL>expos = expos.drop('<STR_LIT>', axis=<NUM_LIT:1>)<EOL>longs = expos.where(expos.applymap(lambda x: x > <NUM_LIT:0>))<EOL>shorts = expos.where(expos.applymap(lambda x: x < <NUM_LIT:0>))<EOL>alloc_summary = pd.DataFrame()<EOL>alloc_summary['<STR_LIT>'] = longs.max(axis=<NUM_LIT:1>)<EOL>alloc_summary['<STR_LIT>'] = longs.median(axis=<NUM_LIT:1>)<EOL>alloc_summary['<STR_LIT>'] = shorts.median(axis=<NUM_LIT:1>)<EOL>alloc_summary['<STR_LIT>'] = shorts.min(axis=<NUM_LIT:1>)<EOL>return alloc_summary<EOL>

Finds the max and median long and short position concentrations
in each time period specified by the index of positions.

Parameters
----------
positions : pd.DataFrame
    The positions that the strategy takes over time.

Returns
-------
pd.DataFrame
    Columns are max long, max short, median long, and median short
    position concentrations. Rows are timeperiods.


positions = positions.copy()<EOL>positions['<STR_LIT>'] = positions.amount * positions.last_sale_price<EOL>cash.name = '<STR_LIT>'<EOL>values = positions.reset_index().pivot_table(index='<STR_LIT:index>',<EOL>columns='<STR_LIT>',<EOL>values='<STR_LIT>')<EOL>if ZIPLINE:<EOL><INDENT>for asset in values.columns:<EOL><INDENT>if type(asset) in [Equity, Future]:<EOL><INDENT>values[asset] = values[asset] * asset.price_multiplier<EOL><DEDENT><DEDENT><DEDENT>values = values.join(cash).fillna(<NUM_LIT:0>)<EOL>values.columns.name = '<STR_LIT>'<EOL>return values<EOL>

Extract position values from backtest object as returned by
get_backtest() on the Quantopian research platform.

Parameters
----------
positions : pd.DataFrame
    timeseries containing one row per symbol (and potentially
    duplicate datetime indices) and columns for amount and
    last_sale_price.
cash : pd.Series
    timeseries containing cash in the portfolio.

Returns
-------
pd.DataFrame
    Daily net position values.
     - See full explanation in tears.create_full_tear_sheet.


cash = positions['<STR_LIT>']<EOL>positions = positions.drop('<STR_LIT>', axis=<NUM_LIT:1>)<EOL>unmapped_pos = np.setdiff1d(positions.columns.values,<EOL>list(symbol_sector_map.keys()))<EOL>if len(unmapped_pos) > <NUM_LIT:0>:<EOL><INDENT>warn_message = """<STR_LIT>""".format(<EOL>"<STR_LIT:U+002CU+0020>".join(map(str, unmapped_pos)))<EOL>warnings.warn(warn_message, UserWarning)<EOL><DEDENT>sector_exp = positions.groupby(<EOL>by=symbol_sector_map, axis=<NUM_LIT:1>).sum()<EOL>sector_exp['<STR_LIT>'] = cash<EOL>return sector_exp<EOL>

Sum position exposures by sector.

Parameters
----------
positions : pd.DataFrame
    Contains position values or amounts.
    - Example
        index         'AAPL'         'MSFT'        'CHK'        cash
        2004-01-09    13939.380     -15012.993    -403.870      1477.483
        2004-01-12    14492.630     -18624.870    142.630       3989.610
        2004-01-13    -13853.280    13653.640     -100.980      100.000
symbol_sector_map : dict or pd.Series
    Security identifier to sector mapping.
    Security ids as keys/index, sectors as values.
    - Example:
        {'AAPL' : 'Technology'
         'MSFT' : 'Technology'
         'CHK' : 'Natural Resources'}

Returns
-------
sector_exp : pd.DataFrame
    Sectors and their allocations.
    - Example:
        index         'Technology'    'Natural Resources' cash
        2004-01-09    -1073.613       -403.870            1477.4830
        2004-01-12    -4132.240       142.630             3989.6100
        2004-01-13    -199.640        -100.980            100.0000


pos_wo_cash = positions.drop('<STR_LIT>', axis=<NUM_LIT:1>)<EOL>longs = pos_wo_cash[pos_wo_cash > <NUM_LIT:0>].sum(axis=<NUM_LIT:1>).fillna(<NUM_LIT:0>)<EOL>shorts = pos_wo_cash[pos_wo_cash < <NUM_LIT:0>].sum(axis=<NUM_LIT:1>).fillna(<NUM_LIT:0>)<EOL>cash = positions.cash<EOL>net_liquidation = longs + shorts + cash<EOL>df_pos = pd.DataFrame({'<STR_LIT>': longs.divide(net_liquidation, axis='<STR_LIT:index>'),<EOL>'<STR_LIT>': shorts.divide(net_liquidation,<EOL>axis='<STR_LIT:index>')})<EOL>df_pos['<STR_LIT>'] = df_pos['<STR_LIT>'] + df_pos['<STR_LIT>']<EOL>return df_pos<EOL>

Determines the long and short allocations in a portfolio.

Parameters
----------
positions : pd.DataFrame
    The positions that the strategy takes over time.

Returns
-------
df_long_short : pd.DataFrame
    Long and short allocations as a decimal
    percentage of the total net liquidation


def model_returns_t_alpha_beta(data, bmark, samples=<NUM_LIT>, progressbar=True):

data_bmark = pd.concat([data, bmark], axis=<NUM_LIT:1>).dropna()<EOL>with pm.Model() as model:<EOL><INDENT>sigma = pm.HalfCauchy(<EOL>'<STR_LIT>',<EOL>beta=<NUM_LIT:1>)<EOL>nu = pm.Exponential('<STR_LIT>', <NUM_LIT:1.> / <NUM_LIT>)<EOL>X = data_bmark.iloc[:, <NUM_LIT:1>]<EOL>y = data_bmark.iloc[:, <NUM_LIT:0>]<EOL>alpha_reg = pm.Normal('<STR_LIT>', mu=<NUM_LIT:0>, sd=<NUM_LIT>)<EOL>beta_reg = pm.Normal('<STR_LIT>', mu=<NUM_LIT:0>, sd=<NUM_LIT:1>)<EOL>mu_reg = alpha_reg + beta_reg * X<EOL>pm.StudentT('<STR_LIT>',<EOL>nu=nu + <NUM_LIT:2>,<EOL>mu=mu_reg,<EOL>sd=sigma,<EOL>observed=y)<EOL>trace = pm.sample(samples, progressbar=progressbar)<EOL><DEDENT>return model, trace<EOL>

Run Bayesian alpha-beta-model with T distributed returns.

This model estimates intercept (alpha) and slope (beta) of two
return sets. Usually, these will be algorithm returns and
benchmark returns (e.g. S&P500). The data is assumed to be T
distributed and thus is robust to outliers and takes tail events
into account.  If a pandas.DataFrame is passed as a benchmark, then
multiple linear regression is used to estimate alpha and beta.

Parameters
----------
returns : pandas.Series
    Series of simple returns of an algorithm or stock.
bmark : pandas.DataFrame
    DataFrame of benchmark returns (e.g., S&P500) or risk factors (e.g.,
    Fama-French SMB, HML, and UMD).
    If bmark has more recent returns than returns_train, these dates
    will be treated as missing values and predictions will be
    generated for them taking market correlations into account.
samples : int (optional)
    Number of posterior samples to draw.

Returns
-------
model : pymc.Model object
    PyMC3 model containing all random variables.
trace : pymc3.sampling.BaseTrace object
    A PyMC3 trace object that contains samples for each parameter
    of the posterior.


def model_returns_normal(data, samples=<NUM_LIT>, progressbar=True):

with pm.Model() as model:<EOL><INDENT>mu = pm.Normal('<STR_LIT>', mu=<NUM_LIT:0>, sd=<NUM_LIT>, testval=data.mean())<EOL>sigma = pm.HalfCauchy('<STR_LIT>', beta=<NUM_LIT:1>, testval=data.std())<EOL>returns = pm.Normal('<STR_LIT>', mu=mu, sd=sigma, observed=data)<EOL>pm.Deterministic(<EOL>'<STR_LIT>',<EOL>returns.distribution.variance**<NUM_LIT> *<EOL>np.sqrt(<NUM_LIT>))<EOL>pm.Deterministic(<EOL>'<STR_LIT>',<EOL>returns.distribution.mean /<EOL>returns.distribution.variance**<NUM_LIT> *<EOL>np.sqrt(<NUM_LIT>))<EOL>trace = pm.sample(samples, progressbar=progressbar)<EOL><DEDENT>return model, trace<EOL>

Run Bayesian model assuming returns are normally distributed.

Parameters
----------
returns : pandas.Series
    Series of simple returns of an algorithm or stock.
samples : int (optional)
    Number of posterior samples to draw.

Returns
-------
model : pymc.Model object
    PyMC3 model containing all random variables.
trace : pymc3.sampling.BaseTrace object
    A PyMC3 trace object that contains samples for each parameter
    of the posterior.


def model_returns_t(data, samples=<NUM_LIT>, progressbar=True):

with pm.Model() as model:<EOL><INDENT>mu = pm.Normal('<STR_LIT>', mu=<NUM_LIT:0>, sd=<NUM_LIT>, testval=data.mean())<EOL>sigma = pm.HalfCauchy('<STR_LIT>', beta=<NUM_LIT:1>, testval=data.std())<EOL>nu = pm.Exponential('<STR_LIT>', <NUM_LIT:1.> / <NUM_LIT>, testval=<NUM_LIT>)<EOL>returns = pm.StudentT('<STR_LIT>', nu=nu + <NUM_LIT:2>, mu=mu, sd=sigma,<EOL>observed=data)<EOL>pm.Deterministic('<STR_LIT>',<EOL>returns.distribution.variance**<NUM_LIT> * np.sqrt(<NUM_LIT>))<EOL>pm.Deterministic('<STR_LIT>', returns.distribution.mean /<EOL>returns.distribution.variance**<NUM_LIT> *<EOL>np.sqrt(<NUM_LIT>))<EOL>trace = pm.sample(samples, progressbar=progressbar)<EOL><DEDENT>return model, trace<EOL>

Run Bayesian model assuming returns are Student-T distributed.

Compared with the normal model, this model assumes returns are
T-distributed and thus have a 3rd parameter (nu) that controls the
mass in the tails.

Parameters
----------
returns : pandas.Series
    Series of simple returns of an algorithm or stock.
samples : int, optional
    Number of posterior samples to draw.

Returns
-------
model : pymc.Model object
    PyMC3 model containing all random variables.
trace : pymc3.sampling.BaseTrace object
    A PyMC3 trace object that contains samples for each parameter
    of the posterior.