Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions pyfolio/plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -1323,7 +1323,7 @@ def plot_return_quantiles(returns, live_start_date=None, ax=None, **kwargs):
return ax


def plot_turnover(returns, transactions, positions,
def plot_turnover(returns, transactions, positions, turnover_denom='AGB',
legend_loc='best', ax=None, **kwargs):
"""
Plots turnover vs. date.
Expand All @@ -1345,6 +1345,9 @@ def plot_turnover(returns, transactions, positions,
positions : pd.DataFrame
Daily net position values.
- 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.
legend_loc : matplotlib.loc, optional
The location of the legend on the plot.
ax : matplotlib.Axes, optional
Expand All @@ -1364,7 +1367,7 @@ def plot_turnover(returns, transactions, positions,
y_axis_formatter = FuncFormatter(utils.two_dec_places)
ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))

df_turnover = txn.get_turnover(positions, transactions)
df_turnover = txn.get_turnover(positions, transactions, turnover_denom)
df_turnover_by_month = df_turnover.resample("M").mean()
df_turnover.plot(color='steelblue', alpha=1.0, lw=0.5, ax=ax, **kwargs)
df_turnover_by_month.plot(
Expand Down Expand Up @@ -1517,7 +1520,7 @@ def plot_capacity_sweep(returns, transactions, market_data,
return ax


def plot_daily_turnover_hist(transactions, positions,
def plot_daily_turnover_hist(transactions, positions, turnover_denom='AGB',
ax=None, **kwargs):
"""
Plots a histogram of daily turnover rates.
Expand All @@ -1530,6 +1533,9 @@ def plot_daily_turnover_hist(transactions, positions,
positions : pd.DataFrame
Daily net position values.
- 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.
ax : matplotlib.Axes, optional
Axes upon which to plot.
**kwargs, optional
Expand All @@ -1543,7 +1549,7 @@ def plot_daily_turnover_hist(transactions, positions,

if ax is None:
ax = plt.gca()
turnover = txn.get_turnover(positions, transactions)
turnover = txn.get_turnover(positions, transactions, turnover_denom)
sns.distplot(turnover, ax=ax, **kwargs)
ax.set_title('Distribution of daily turnover rates')
ax.set_xlabel('Turnover rate')
Expand Down
47 changes: 27 additions & 20 deletions pyfolio/tears.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,6 @@ def create_full_tear_sheet(returns,
cone_std=(1.0, 1.5, 2.0),
bootstrap=False,
unadjusted_returns=None,
style_factors=None,
sectors=None,
caps=None,
shares_held=None,
volumes=None,
percentile=None,
turnover_denom='AGB',
set_context=True,
factor_returns=None,
Expand Down Expand Up @@ -402,6 +396,7 @@ def create_simple_tear_sheet(returns,
plotting.plot_turnover(returns,
transactions,
positions,
turnover_denom=turnover_denom,
ax=ax_turnover)

plotting.plot_txn_time_hist(transactions, ax=ax_txn_timings)
Expand Down Expand Up @@ -603,8 +598,8 @@ def create_returns_tear_sheet(returns, positions=None,
@plotting.customize
def create_position_tear_sheet(returns, positions,
show_and_plot_top_pos=2, hide_positions=False,
return_fig=False, sector_mappings=None,
transactions=None, estimate_intraday='infer'):
sector_mappings=None, transactions=None,
estimate_intraday='infer', return_fig=False):
"""
Generate a number of plots for analyzing a
strategy's positions and holdings.
Expand All @@ -627,8 +622,6 @@ def create_position_tear_sheet(returns, positions,
hide_positions : bool, optional
If True, will not output any symbol names.
Overrides show_and_plot_top_pos to 0 to suppress text output.
return_fig : boolean, optional
If True, returns the figure that was plotted on.
sector_mappings : dict or pd.Series, optional
Security identifier to sector mapping.
Security ids as keys, sectors as values.
Expand All @@ -638,6 +631,8 @@ def create_position_tear_sheet(returns, positions,
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,
Expand Down Expand Up @@ -697,8 +692,8 @@ def create_position_tear_sheet(returns, positions,

@plotting.customize
def create_txn_tear_sheet(returns, positions, transactions,
unadjusted_returns=None, estimate_intraday='infer',
return_fig=False):
turnover_denom='AGB', unadjusted_returns=None,
estimate_intraday='infer', return_fig=False):
"""
Generate a number of plots for analyzing a strategy's transactions.

Expand All @@ -715,6 +710,9 @@ def create_txn_tear_sheet(returns, positions, transactions,
transactions : pd.DataFrame
Prices and amounts of executed trades. One row per trade.
- See full explanation in create_full_tear_sheet.
turnover_denom : str, optional
Either AGB or portfolio_value, default AGB.
- See full explanation in txn.get_turnover.
unadjusted_returns : pd.Series, optional
Daily unadjusted returns of the strategy, noncumulative.
Will plot additional swippage sweep analysis.
Expand Down Expand Up @@ -743,12 +741,15 @@ def create_txn_tear_sheet(returns, positions, transactions,
returns,
transactions,
positions,
turnover_denom=turnover_denom,
ax=ax_turnover)

plotting.plot_daily_volume(returns, transactions, ax=ax_daily_volume)

try:
plotting.plot_daily_turnover_hist(transactions, positions,
plotting.plot_daily_turnover_hist(transactions,
positions,
turnover_denom=turnover_denom,
ax=ax_turnover_hist)
except ValueError:
warnings.warn('Unable to generate turnover plot.', UserWarning)
Expand Down Expand Up @@ -956,7 +957,8 @@ def create_capacity_tear_sheet(returns, positions, transactions,
trade_daily_vol_limit=0.05,
last_n_days=utils.APPROX_BDAYS_PER_MONTH * 6,
days_to_liquidate_limit=1,
estimate_intraday='infer'):
estimate_intraday='infer',
return_fig=False):
"""
Generates a report detailing portfolio size constraints set by
least liquid tickers. Plots a "capacity sweep," a curve describing
Expand Down Expand Up @@ -993,6 +995,8 @@ def create_capacity_tear_sheet(returns, positions, transactions,
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,
Expand Down Expand Up @@ -1046,14 +1050,17 @@ def create_capacity_tear_sheet(returns, positions, transactions,
llt[llt['max_pct_bar_consumed'] > trade_daily_vol_limit * 100])

bt_starting_capital = positions.iloc[0].sum() / (1 + returns.iloc[0])
_, ax_capacity_sweep = plt.subplots(figsize=(14, 6))
fig, ax_capacity_sweep = plt.subplots(figsize=(14, 6))
plotting.plot_capacity_sweep(returns, transactions, market_data,
bt_starting_capital,
min_pv=100000,
max_pv=300000000,
step_size=1000000,
ax=ax_capacity_sweep)

if return_fig:
return fig


@plotting.customize
def create_perf_attrib_tear_sheet(returns,
Expand All @@ -1062,8 +1069,8 @@ def create_perf_attrib_tear_sheet(returns,
factor_loadings,
transactions=None,
pos_in_dollars=True,
return_fig=False,
factor_partitions=FACTOR_PARTITIONS):
factor_partitions=FACTOR_PARTITIONS,
return_fig=False):
"""
Generate plots and tables for analyzing a strategy's performance.

Expand Down Expand Up @@ -1093,15 +1100,15 @@ def create_perf_attrib_tear_sheet(returns,
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', ... ]}

return_fig : boolean, optional
If True, returns the figure that was plotted on.
"""
portfolio_exposures, perf_attrib_data = perf_attrib.perf_attrib(
returns, positions, factor_returns, factor_loadings, transactions,
Expand Down