Skip to content

Commit

Permalink
Merge branch 'pr/174'
Browse files Browse the repository at this point in the history
  • Loading branch information
twiecki committed Oct 21, 2015
2 parents 151f61e + cd6f6fa commit 15663a6
Show file tree
Hide file tree
Showing 3 changed files with 118 additions and 34 deletions.
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,9 @@ docs/_build/

# PyBuilder
target/

# VIM
*.sw?

# IPython notebook checkpoints
.ipynb_checkpoints/
84 changes: 51 additions & 33 deletions pyfolio/examples/bayesian.ipynb

Large diffs are not rendered by default.

62 changes: 61 additions & 1 deletion pyfolio/tears.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,16 @@
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import seaborn as sns
from time import time

def timer(msg_body, previous_time):

current_time = time()
run_time = current_time - previous_time
message = "\nFinished " + msg_body + " (required {:.2f} seconds)."
print(message.format(run_time))

return current_time


def create_full_tear_sheet(returns, positions=None, transactions=None,
Expand Down Expand Up @@ -534,7 +544,7 @@ def create_interesting_times_tear_sheet(
@plotting_context
def create_bayesian_tear_sheet(returns, benchmark_rets=None,
live_start_date=None, samples=2000,
return_fig=False):
return_fig=False, stoch_vol=False):
"""
Generate a number of Bayesian distributions and a Bayesian
cone plot of returns.
Expand All @@ -560,6 +570,8 @@ def create_bayesian_tear_sheet(returns, benchmark_rets=None,
If True, returns the figure that was plotted on.
set_context : boolean, optional
If True, set default plotting style context.
stoch_vol : boolean, optional
If True, run and plot the stochastic volatility model
"""

if live_start_date is None:
Expand All @@ -577,13 +589,21 @@ def create_bayesian_tear_sheet(returns, benchmark_rets=None,
df_test = returns.loc[returns.index >= live_start_date]

# Run T model with missing data
print("Running T model")
previous_time = time()
# track the total run time of the Bayesian tear sheet
start_time = previous_time

trace_t = bayesian.run_model('t', df_train, returns_test=df_test,
samples=samples)
previous_time = timer("T model", previous_time)

# Compute BEST model
print("\nRunning BEST model")
trace_best = bayesian.run_model('best', df_train,
returns_test=df_test,
samples=samples)
previous_time = timer("BEST model", previous_time)

# Plot results

Expand All @@ -598,6 +618,7 @@ def create_bayesian_tear_sheet(returns, benchmark_rets=None,
bayesian.plot_bayes_cone(df_train, df_test,
trace=trace_t,
ax=ax_cone)
previous_time = timer("plotting Bayesian cone", previous_time)

# Plot BEST results
row += 1
Expand All @@ -614,6 +635,7 @@ def create_bayesian_tear_sheet(returns, benchmark_rets=None,
axs.append(plt.subplot(gs[row, :]))

bayesian.plot_best(trace=trace_best, axs=axs)
previous_time = timer("plotting BEST results", previous_time)

# Compute Bayesian predictions
row += 1
Expand All @@ -631,6 +653,8 @@ def create_bayesian_tear_sheet(returns, benchmark_rets=None,
verticalalignment='bottom',
horizontalalignment='right',
transform=ax_ret_pred_day.transAxes)
previous_time = timer("computing Bayesian predictions", previous_time)

# Plot Bayesian VaRs
week_pred = (
np.cumprod(trace_t['returns_missing'][:, :5] + 1, 1) - 1)[:, -1]
Expand All @@ -645,12 +669,15 @@ def create_bayesian_tear_sheet(returns, benchmark_rets=None,
verticalalignment='bottom',
horizontalalignment='right',
transform=ax_ret_pred_week.transAxes)
previous_time = timer("plotting Bayesian VaRs estimate", previous_time)

# Run alpha beta model
print("\nRunning alpha beta model")
benchmark_rets = benchmark_rets.loc[df_train.index]
trace_alpha_beta = bayesian.run_model('alpha_beta', df_train,
bmark=benchmark_rets,
samples=samples)
previous_time = timer("running alpha beta model", previous_time)

# Plot alpha and beta
row += 1
Expand All @@ -662,6 +689,39 @@ def create_bayesian_tear_sheet(returns, benchmark_rets=None,
sns.distplot(trace_alpha_beta['beta'][100:], ax=ax_beta)
ax_beta.set_xlabel('Beta')
ax_beta.set_ylabel('Belief')
previous_time = timer("plotting alpha beta model", previous_time)

if stoch_vol:
# run stochastic volatility model
print("\nRunning stochastic volatility model on most recent 400 days of returns")
returns_cutoff = 400
if df_train.size > returns_cutoff:
df_train_truncated = df_train[-returns_cutoff:]
trace_stoch_vol = bayesian.model_stoch_vol(df_train_truncated)
previous_time = timer("running stochastic volatility model", previous_time)

# plot log(sigma) and log(nu)
print("\nPlotting stochastic volatility model")
row += 1
ax_sigma_log = plt.subplot(gs[row, 0])
ax_nu_log = plt.subplot(gs[row, 1])
sigma_log = trace_stoch_vol['sigma_log']
sns.distplot(sigma_log, ax=ax_sigma_log)
ax_sigma_log.set_xlabel('log(Sigma)')
ax_sigma_log.set_ylabel('Belief')
nu_log = trace_stoch_vol['nu_log']
sns.distplot(nu_log, ax=ax_nu_log)
ax_nu_log.set_xlabel('log(nu)')
ax_nu_log.set_ylabel('Belief')

# plot latent volatility
row += 1
ax_volatility = plt.subplot(gs[row, :])
bayesian.plot_stoch_vol(df_train_truncated, trace=trace_stoch_vol, ax=ax_volatility)
previous_time = timer("plotting stochastic volatility model", previous_time)

total_time = time() - start_time
print("\nTotal runtime was {:.2f} seconds.").format(total_time)

gs.tight_layout(fig)

Expand Down

0 comments on commit 15663a6

Please sign in to comment.