plt.tight_layout() fig.set_size_inches(15, 5) ############################ # Candle Plot # # frequency = D/W/M # # Returns # ############################ pf.plot_return_quantiles(backtest_returns) ############################ # Rolling Plot # # frequency = M/Y # # BETA # ############################ pf.plot_rolling_beta(backtest_returns, benchmark_returns) ############################ # Rolling Plot # # frequency = M/Y # # SHARPE RATIO # ############################ pf.plot_rolling_sharpe(backtest_returns) ############################ # Top 10 Drawdown Periods # # frequency = M/Y # ############################ pf.plot_drawdown_periods(backtest_returns) ############################
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) plt.savefig(PATH + 'returns_charts.png', dpi=300) plt.close() pf.plot_return_quantiles(bt_returns) plt.savefig(PATH + 'quantiles.png', dpi=300) plt.close() pf.plot_rolling_beta(bt_returns, benchmark_rets) plt.savefig(PATH + 'roll_beta.png', dpi=300) plt.close() pf.plot_rolling_sharpe(bt_returns) plt.savefig(PATH + 'roll_sharpe.png', dpi=300) plt.close() pf.plot_rolling_fama_french(bt_returns) plt.savefig(PATH + 'fama_french.png', dpi=300) plt.close() pf.plot_drawdown_periods(bt_returns) plt.savefig(PATH + 'drawdown.png', dpi=300) plt.close()
warnings.filterwarnings('ignore') # **2 - Obtendo e tratando os dados** tickers = ["ABEV3.SA", "ITSA4.SA", "USIM5.SA", "VALE3.SA", "WEGE3.SA", '^BVSP'] dados_yahoo = web.get_data_yahoo(tickers, period="5y")["Adj Close"] dados_yahoo retorno = dados_yahoo.pct_change() retorno retorno_acumulado = (1 + retorno).cumprod() retorno_acumulado.iloc[0] = 1 retorno_acumulado carteira = 10000*retorno_acumulado.iloc[:,:5] carteira["saldo"] = carteira.sum(axis=1) carteira["retorno"] = carteira["saldo"].pct_change() carteira # **3 - Resultados** pf.create_full_tear_sheet(carteira["retorno"], benchmark_rets=retorno["^BVSP"]) fig, ax1 = plt.subplots(figsize=(16,8)) pf.plot_rolling_beta(carteira["retorno"], factor_returns=retorno["^BVSP"], ax=ax1) plt.ylim((0.8, 1.8))
def plot_performance( returns, benchmark_prices, plot_stats=False, startcash=None, log_returns=False, save_dir=None ): """ :param returns: pd.Series, return data :param benchmark_prices: pd.Series, benchmark return data :param startcash: int, rebase the benchmark if provided :return: None """ if save_dir and not os.path.exists(save_dir): os.makedirs(save_dir) # Rebase benchmark prices, the same as portfolio prices if startcash is not None: benchmark_prices = (benchmark_prices / benchmark_prices.iloc[0]) * startcash benchmark_rets = pyp.expected_returns.returns_from_prices(benchmark_prices) if log_returns: portfolio_value = returns.cumsum().apply(np.exp) * startcash else: portfolio_value = (1 + returns).cumprod() * startcash # Performance statistics if plot_stats: pf.show_perf_stats(returns) pf.show_perf_stats(benchmark_rets) # Fig 1: price and return fig, ax = plt.subplots(2, 1, sharex=True, figsize=[14, 8]) portfolio_value.plot(ax=ax[0], label='Portfolio') benchmark_prices.plot(ax=ax[0], label='Benchmark') ax[0].set_ylabel('Price') ax[0].grid(True) ax[0].legend() returns.plot(ax=ax[1], label='Portfolio', alpha=0.5) benchmark_rets.plot(ax=ax[1], label='Benchmark', alpha=0.5) ax[1].set_ylabel('Return') fig.suptitle('Black–Litterman Portfolio Optimization', fontsize=16) plt.grid(True) plt.legend() plt.show() if save_dir: fig.savefig(os.path.join(save_dir, 'price_and_return'), dpi=300) # Fig 2: return performance fig, ax = plt.subplots(nrows=2, ncols=2, figsize=(16, 9), constrained_layout=False) axes = ax.flatten() pf.plot_rolling_beta(returns=returns, factor_returns=benchmark_rets, ax=axes[0]) pf.plot_return_quantiles(returns=returns, ax=axes[1]) pf.plot_annual_returns(returns=returns, ax=axes[2]) pf.plot_monthly_returns_heatmap(returns=returns, ax=axes[3]) axes[0].grid(True) axes[1].grid(True) axes[2].grid(True) fig.suptitle('Return performance', fontsize=16, y=1.0) plt.tight_layout() if save_dir: fig.savefig(os.path.join(save_dir, 'return_performance'), dpi=300) # Fig 3: risk performance fig, ax = plt.subplots(nrows=2, ncols=2, figsize=(14, 8), constrained_layout=False) axes = ax.flatten() pf.plot_drawdown_periods(returns=returns, ax=axes[0]) pf.plot_rolling_volatility(returns=returns, factor_returns=benchmark_rets, ax=axes[1]) pf.plot_drawdown_underwater(returns=returns, ax=axes[2]) pf.plot_rolling_sharpe(returns=returns, ax=axes[3]) axes[0].grid(True) axes[1].grid(True) axes[2].grid(True) axes[3].grid(True) fig.suptitle('Risk performance', fontsize=16, y=1.0) plt.tight_layout() if save_dir: fig.savefig(os.path.join(save_dir, 'risk_performance'), dpi=300)