Quantopian has a built-in library called Pyfolio (also open sourced Github page) that quickly creates "tear-sheets" and useful information plots easily.
import pyfolio as pf
import matplotlib.pyplot as plt
import empyrical
def initialize(context):
context.spy = sid(8554)
set_max_leverage(1.01)
schedule_function(rebalance,date_rules.every_day(),time_rules.market_open())
def rebalance(context,data):
order_target_percent(context.spy,1)
Run the above algo in Quantopian platform (full backtest) and grab the backtest_id
# Get benchmark returns
benchmark_rets = get_backtest('5986c511c94d014fc81acf7b')
bm_returns = benchmark_rets.daily_performance['returns']
bm_positions = benchmark_rets.pyfolio_positions
bm_transactions = benchmark_rets.pyfolio_transactions
Make sure the period matches
# Use same algo as in the Leverage Lecture!
bt = get_backtest('5986b969dbab994fa4264696')
bt_returns = bt.daily_performance['returns']
bt_positions = bt.pyfolio_positions
bt_transactions = bt.pyfolio_transactions
bt_returns.plot()
There are many built-in info e.g. sharpe_ratio
empyrical.beta(bt_returns,bm_returns)
Make sure we don't mess up with the backtest_id
benchmark_rets = bm_returns
# Cumulative Returns
plt.subplot(2,1,1)
pf.plotting.plot_rolling_returns(bt_returns, benchmark_rets)
# Daily, Non-Cumulative Returns
plt.subplot(2,1,2)
pf.plotting.plot_returns(bt_returns)
plt.tight_layout()
fig = plt.figure(1)
plt.subplot(1,3,1)
pf.plot_annual_returns(bt_returns)
plt.subplot(1,3,2)
pf.plot_monthly_returns_dist(bt_returns)
plt.subplot(1,3,3)
pf.plot_monthly_returns_heatmap(bt_returns)
plt.tight_layout()
fig.set_size_inches(15,5)
Annual returns: for 2016, we actually have negative returns
Monthly return heatmap: allow you to see which month you did the best/worst
pf.plot_return_quantiles(bt_returns);
pf.plot_rolling_beta(bt_returns, benchmark_rets);
Rolling Beta: the dotted line is the average
pf.plot_rolling_sharpe(bt_returns);
pf.plot_rolling_fama_french(bt_returns);
pf.plot_drawdown_periods(bt_returns);
Underwater plot is kind of like drawdown plot but in reverse. You can see the actual percentage of drawn down as a factor of time
pf.plot_drawdown_underwater(bt_returns);
pf.plot_gross_leverage(bt_returns, bt_positions);
pos_percent = pf.pos.get_percent_alloc(bt_positions)
pf.plotting.show_and_plot_top_positions(bt_returns, pos_percent);
pf.plot_turnover(bt_returns, bt_transactions, bt_positions);
pf.plotting.plot_daily_turnover_hist(bt_transactions, bt_positions);
pf.plotting.plot_daily_volume(bt_returns, bt_transactions);
pf.create_round_trip_tear_sheet(bt_returns, bt_positions, bt_transactions);