Exemplo n.º 1
0
# Fitted surface
ax3 = plt.subplot2grid((3, 4), (1, 2), colspan=2, rowspan=2, projection='3d')
step = 0.01
zz1, zz2 = np.meshgrid(np.arange(-2, 2, step), np.arange(-2, 2, step))
zz = poly.fit_transform(np.c_[zz1.ravel(), zz2.ravel()])
xx = reg.predict(zz)
ax3.plot_surface(zz1,
                 zz2,
                 xx.reshape((zz1.shape)),
                 color=lightgreen,
                 alpha=0.7,
                 label='Fitted surface')

ax3.scatter3D(z_in[idxx, 0],
              z_in[idxx, 1],
              reg.predict(z_inter_in)[idxx],
              s=10,
              color=lightgreen,
              alpha=1,
              label='$(Z_1,Z_2, \hat{X})$')
ax3.set_xlabel('$Z_1$')
ax3.set_ylabel('$Z_2$')
ax3.set_zlabel('$\hat{X}$')
ax3.set_title('Fitted surface', fontweight='bold')
ax3.set_xlim([-2, 2])
ax3.set_ylim([-2, 2])

add_logo(fig, axis=ax1)
plt.tight_layout()
Exemplo n.º 2
0
ax5 = plt.subplot2grid((4, 4), (1, 2), colspan=2, rowspan=1)
ax5.fill([0.15, 0.15, 0.35, 0.35], [0, cm_ann[0, 1], cm_ann[0, 1], 0],
         facecolor=grfalse,
         edgecolor=grhatch,
         hatch='//',
         alpha=0.7)
ax5.fill([0.15, 0.15, 0.35, 0.35], [cm_ann[0, 1], 1, 1, cm_ann[0, 1]],
         facecolor=grfalse,
         alpha=0.7)
ax5.fill([0.45, 0.45, 0.65, 0.65], [0, cm_ann[1, 1], cm_ann[1, 1], 0],
         facecolor=grtrue,
         alpha=0.7)
ax5.fill([0.45, 0.45, 0.65, 0.65], [cm_ann[1, 1], 1, 1, cm_ann[1, 1]],
         facecolor=grtrue,
         edgecolor=grhatch,
         hatch='\\\\',
         alpha=0.7)
ax5.set_ylim([0, 1])
ax5.legend(['fpr', 'tnr', 'tpr', 'fnr'],
           bbox_to_anchor=(0.001, -0.07, 1., .1),
           facecolor='white',
           loc=1,
           ncol=5,
           mode="expand")
ax5.set_title('Confusion matrix', fontweight='bold')
ax5.set_xticks([])
ax5.grid(False)

add_logo(fig, axis=ax1, size_frac_x=1 / 6)
plt.tight_layout()
Exemplo n.º 3
0
ax9 = plt.subplot2grid((20, 16), (19, 9), colspan=7, rowspan=1, sharex=ax7)
ax9.set_yticks([])
ax9.set_facecolor('none')
ax9.grid(False)
ax9.xaxis.set_ticks_position('none')
plt.setp(ax9.get_xticklabels(), visible=False)
ax9.set_xlim([0, 2 * upper_limit])
ax9.invert_yaxis()
plt.box(False)
l3, = ax9.plot(x_grid,
               logn_pdf(
                   x_grid, mu_xz[0] + 0.5 * (1 - rho_xz**2) * sig_x**2 -
                   mu_xz[1] * rho_xz * sig_x / sig_z, abs(rho_xz * sig_x)),
               c=light_green_1,
               lw=2)

l1 = Rectangle((0, 0), 1, 1, color=light_green_2, ec='none')
l2 = Rectangle((0, 0), 1, 1, color=teal, ec='none')
l4 = Rectangle((0, 0), 1, 1, color=colf, ec='none')
fig.legend(
    (l1, l2, l3, l4, l5, l6),
    ('Input', 'Output', 'Predictor', 'Residual', 'Cond. exp.', 'Arb. func.'),
    'upper right',
    prop={
        'size': '17',
        'weight': 'bold'
    },
    facecolor='none',
    edgecolor='none')
add_logo(fig, axis=ax1, location=5, size_frac_x=1 / 12)
Exemplo n.º 4
0
def invariance_test_copula(epsi,
                           lag_,
                           k_=None,
                           title='Copula invariance test'):
    """For details, see here.

    Parameters
    ----------
        epsi : array, shape (t_,)
        lag_ : scalar
        k_: int
        title : string

    Returns
    -------
        sw: array, shape(lag_,)

    """

    t_ = epsi.shape[0]

    # Step 1: Compute Schweizer-Wolff dependence for lags
    sw = np.zeros(lag_)
    for l in range(lag_):
        sw[l] = schweizer_wolff(
            np.column_stack((epsi[(l + 1):], epsi[:-(l + 1)])))

    # Step 2: Compute grades scenarios
    x_lag = epsi[:-lag_]
    y_lag = epsi[lag_:]
    # compute grades
    u, _, _ = cop_marg_sep(np.column_stack((x_lag, y_lag)))

    # Step 3: Calculate normalized histogram
    if k_ is None:
        k_ = np.floor(np.sqrt(7 * np.log(t_)))
    f, xi_1, xi_2 = histogram2d_sp(u, k_=k_)

    # Plots
    plt.style.use('arpm')
    fig = plt.figure(figsize=(1280.0 / 72.0, 720.0 / 72.0), dpi=72.0)

    # 2D histogram
    ax = plt.subplot2grid((3, 3), (0, 0),
                          rowspan=3,
                          colspan=2,
                          projection='3d')
    plt.sca(ax)
    ax.view_init(30, 45)

    # adjust bin centers to left edges for plotting
    dx = xi_1[1] - xi_1[0]
    dy = xi_2[1] - xi_2[0]
    xpos, ypos = np.meshgrid(xi_1 - dx / 2, xi_2 - dy / 2)
    xpos = xpos.flatten('F')
    ypos = ypos.flatten('F')

    ax.bar3d(xpos, ypos, np.zeros_like(xpos), dx, dy, f.flatten())
    plt.xticks(fontsize=14)
    plt.yticks(fontsize=14)
    ax.zaxis.set_tick_params(labelsize=14)
    ax.xaxis.set_major_formatter(FormatStrFormatter('%.1f'))
    ax.yaxis.set_major_formatter(FormatStrFormatter('%.1f'))
    ax.zaxis.set_major_formatter(FormatStrFormatter('%.1f'))
    ax.invert_xaxis()

    plt.xlabel('Grade obs.', labelpad=10, fontsize=17)
    plt.ylabel('Grade lagged obs.', labelpad=10, fontsize=17)
    plt.title(title, fontsize=20, fontweight='bold', y=1.02)

    # dependence plot
    orange = [.9, .4, 0]
    ax = plt.subplot2grid((3, 3), (1, 2))
    plt.sca(ax)
    xx = range(1, lag_ + 1)
    plt.bar(xx, sw, 0.5, faceColor=[.8, .8, .8], edgecolor='k')
    plt.bar(xx[lag_ - 1], sw[lag_ - 1], 0.5, facecolor=orange,
            edgecolor='k')  # highlighting the last bar
    plt.xlabel('Lag', fontsize=17)
    plt.ylabel('Dependence', fontsize=17)
    plt.ylim([0, 1])
    plt.xticks(np.arange(1, lag_ + 1), fontsize=14)
    plt.yticks(fontsize=14)
    plt.grid(False)
    add_logo(fig, set_fig_size=False)
    plt.tight_layout()

    return sw
Exemplo n.º 5
0
         label='BMS call option current value')
plt.plot(s,
         np.squeeze(bs_curve_current + delta_bms * (s - v_stock_u[0, 0])),
         color='r',
         label='BMS hedge')
plt.plot(s,
         np.squeeze(bs_curve_current + delta_fod * (s - v_stock_u[0, 0])),
         color='b',
         label='FoD hedge')
plt.plot(s, bs_payoff.flatten(), color='k')
plt.legend()
plt.ylabel('call option value')
plt.xlabel('underlying')
plt.title('Time to horizon: ' + str(m_) + ' days')

add_logo(fig)
plt.tight_layout()

fig = plt.figure()
f_hist, x_hist = histogram_sp(r_call[:, index], k_=100)
plt.bar(x_hist,
        f_hist.flatten(), (max(x_hist) - min(x_hist)) / (len(x_hist) - 1),
        color=lgray,
        edgecolor=lgray,
        linewidth=2)
f1_hist, x1_hist = histogram_sp(r_bms, k_=100)
plt.plot(x1_hist, f1_hist.flatten(), color='r', label='BMS hedged pdf')
f2_hist, x2_hist = histogram_sp(r_fod, k_=100)
plt.plot(x2_hist, f2_hist.flatten(), color='b', label='FoD hedged pdf')
plt.legend()
plt.title('Repriced call option return')
Exemplo n.º 6
0
fig1 = plt.figure()
heps = plt.plot(x, f_epsi, color=blue, lw=1.5)
plt.plot([mu, mu], [0, 0],
         color=green,
         marker='o',
         markersize=6,
         markerfacecolor=green)
plt.xlabel('$\epsilon$')
plt.title('TRUE (UNKNOWN) DISTRIBUTION')
epsT = '$\mu$ =  % 3.2f' % mu
plt.text(np.min(x) + 0.1,
         np.max(f_epsi) * 0.95 - 0.001,
         '$\epsilon_{t} \sim$ N(%s,$\sigma^2$ = 1)' % epsT,
         color='k',
         horizontalalignment='left')
add_logo(fig1, location=1)
plt.tight_layout()

# histograms of estimators
fig2, ax = plt.subplots(1, 3)
# sample mean
plt.sca(ax[0])
hm = plt.bar(m_x,
             m_hist,
             width=m_x[1] - m_x[0],
             facecolor=colhist,
             edgecolor='k')
plt.plot([exp_m, exp_m], [0, 0],
         color=orange,
         marker='o',
         markersize=6,
Exemplo n.º 7
0
plt.text(x_max, (0.475 + p)*y_max, pi_string, color=red,
         horizontalalignment='right')
k_string = \
    'Constant robust error( % s$_{t}\sim$%s(%s=%3.2f,%s=%3.2f)): %3.2f' % \
    (epsi_string, dist_string[i_k], m_hat_string[i_k], location[i_k],
     ss2_string[i_k], dispersion[i_k], er_rob_k)
plt.text(x_max, (0.6 + p)*y_max, k_string, color='b',
         horizontalalignment='right')
ax1.set_xlim([-0.25, x_max])

# parameters plot
plt.sca(ax[1, 0])
plt.scatter(mu, sigma2, 3, 'k', '.')
plt.xlabel('$\mu$')
plt.ylabel('$\sigma^2$')
plt.axis('equal')
plt.xlim([np.min(mu), np.max(mu)])
plt.ylim([0, 1.1*np.max(sigma2)])
plt.title('Normal parameters')

plt.sca(ax[1, 1])
plt.scatter(m, s2, 3, 'k', '.')
plt.axis('equal')
plt.xlabel('m')
plt.ylabel('$s^2$')
plt.xlim([np.min(m), np.max(m)])
plt.ylim([0, 1.1*np.max(s2)])
plt.title('LogNormal parameters')
add_logo(fig, location=1, size_frac_x=1/8)
plt.tight_layout()
Exemplo n.º 8
0
# ## Plots

# +
plt.style.use('arpm')

# pdf of Sigma2
fig = plt.figure()
plt.plot(y, f_sigma2, lw=1.5, color='b')
text = r'$\Sigma^{2} \sim InvWishart(\nu_{pri},  \nu_{pri}\sigma^2_{pri})$' + \
        '\n\n' + \
        r'$\nu_{pri}$=%3.0f, $\sigma_{pri}^2$=%3.1f' % (v_pri, sigma2_pri)
plt.text(0.7 * (y[-1] - y[0]) + y[0], 0.7 * np.max(f_sigma2), text, color='b')
plt.xlabel('$\Sigma^2$')

add_logo(fig, location=1)
plt.tight_layout()

# pdf of M
fig = plt.figure()
plt.plot(x, f_m, lw=1.5, color='g')
text = r'$M \sim t (\nu_{pri},  \mu_{pri},  \sigma_{pri}^2 / t_{pri})$' + \
        '\n\n' + \
        r'$\nu_{pri}$=%3.0f, $t_{pri}$=%3.0f' % (v_pri, t_pri) + '\n' + \
        r'$\mu_{pri}$=%3.1f, $\sigma_{pri}^2$=%3.1f' % (mu_pri, sigma2_pri)
plt.text(0.7 * (x[-1] - x[0]) + x[0], 0.7 * np.max(f_m), text, color='g')
plt.xlabel('$M$')

add_logo(fig, location=1)
plt.tight_layout()
Exemplo n.º 9
0
            square=True)
plt.title('$\sigma_U^{2MLFP}$', fontweight='bold', fontsize=20)

ax4 = plt.subplot2grid((1, 3), (0, 2))
sns.heatmap(beta_mlfp_norm[:n_plot, :],
            cmap='bwr',
            xticklabels=sector_names[:k_],
            yticklabels=stocks_names[:n_plot],
            vmin=minnbeta,
            vmax=maxxbeta,
            center=0)
plt.title('$b^{MLFP}$\n$r2 = $ %f' % r2_mlfp_norm,
          fontweight='bold',
          fontsize=20)

add_logo(fig1, axis=ax4, set_fig_size=False, size_frac_x=1 / 10)
plt.tight_layout()

# Student t discriminant regression and mixed approach
# compute ellipse grids
ell_mlfp = plot_ellipse(np.zeros(2),
                        sig2_u_mlfp_t[:2, :2],
                        r=2,
                        display_ellipse=False)
ell_rmlfp = plot_ellipse(np.zeros(2),
                         sig2_u_rmlfp[:2, :2],
                         r=2,
                         display_ellipse=False)
# limits in colorbars
minncov = np.min(np.c_[sig2_u_mlfp_t[:n_plot, :n_plot],
                       sig2_u_rmlfp[:n_plot, :n_plot]])
Exemplo n.º 10
0
                  yticklabels=stocks_names[:n_plot],
                  vmin=minncov,
                  vmax=maxxcov,
                  square=True)

plt.xticks(fontsize=7)
plt.yticks(fontsize=7)
plt.title('Bayes posterior corr.\n$t_{pri} = \\nu_{pri} = %d*t\_$' % pri_t_,
          fontweight='bold',
          fontsize=20)

ax22 = plt.subplot2grid((2, 4), (1, 3), colspan=1)
ax22 = sns.heatmap(phi2_pos[:n_plot, :n_plot],
                   cmap='BrBG',
                   center=0,
                   xticklabels=stocks_names[:n_plot],
                   yticklabels=stocks_names[:n_plot],
                   vmin=minncorr,
                   vmax=maxxcorr,
                   square=True)

plt.xticks(fontsize=7)
plt.yticks(fontsize=7)
plt.title('Bayes posterior inv. corr.\n$t_{pri} = \\nu_{pri} = %d*t\_$' %
          pri_t_,
          fontweight='bold',
          fontsize=20)

add_logo(fig, axis=ax, set_fig_size=False, size_frac_x=1 / 12)
plt.tight_layout()
Exemplo n.º 11
0
plt.style.use('arpm')
fig = plt.figure(figsize=(1280 / 72, 720 / 72), dpi=72)

# pdf
plt.plot(x_grid, pdf, 'k')

# uncertainty bands
plt.plot(np.linspace(min(u_x_r_1[0], u_x_r_2[0]), max(u_x_r_1[1], u_x_r_2[1]),
                     10),
         np.zeros(10),
         'g-',
         lw=5,
         label='Uncertainty band r = %.1f' % max(r_1, r_2))

plt.plot(np.linspace(max(u_x_r_1[0], u_x_r_2[0]), min(u_x_r_1[1], u_x_r_2[1]),
                     10),
         np.zeros(10),
         'b-',
         lw=7,
         label='Uncertainty band r = %.1f' % min(r_1, r_2))

# expectation
plt.plot(exp_x, 0, 'r.', ms=11, label='Expectation')

plt.legend(prop={'size': 17})
plt.title('Lognormal distribution: uncertainty bands',
          fontweight='bold',
          fontsize=20)
add_logo(fig, location=4, size_frac_x=1 / 16, set_fig_size=False)
plt.tight_layout()
Exemplo n.º 12
0
plt.sca(ax[0])
for k in range(k_):
    plt.plot(lambdagrid_ridge,
             b_r_plot[:, k],
             color=to_rgb(col[k].squeeze()),
             lw=1.5)

plt.xlabel('$\lambda_{ridge}$')
plt.ticklabel_format(style='sci', scilimits=(0, 0), axis='x')
plt.ylabel('Ridge loadings')
plt.grid(True)
plt.xlim(np.array([lambdagrid_ridge[0], lambdagrid_ridge[-1]]))
plt.ylim([mmin, mmax])

plt.sca(ax[1])

for k in range(k_):
    plt.plot(lambdagrid_lasso,
             b_l_plot[:, k],
             color=to_rgb(col[k].squeeze()),
             lw=1.5)

plt.xlabel('$\lambda_{lasso}$')
plt.ticklabel_format(style='sci', scilimits=(0, 0), axis='x')
plt.ylabel('Lasso loadings')
plt.grid(True)
plt.xlim([lambdagrid_lasso[0], lambdagrid_lasso[-1]])
plt.ylim([mmin, mmax])
add_logo(fig, axis=ax[0], location=1)
plt.tight_layout()
Exemplo n.º 13
0
         '.',
         markersize=15,
         color='k')
plt.legend(['Efficient frontier', 'Optimal holdings'])
plt.ylabel('$E\{Y_{h}\}$')
plt.xlabel('$Sd\{Y_{h}\}$')
plt.xlim(xlim)
str_opt = '$p =$ %1.2f %%' % np.float(100 * p_span[-1])
plt.text(0.8,
         0.1,
         str_opt,
         horizontalalignment='center',
         verticalalignment='center',
         transform=ax21.transAxes)
plt.title('Robust mean-variance efficient frontier', fontweight='bold')
add_logo(fig, axis=ax21, location=5, size_frac_x=1 / 8)
plt.tight_layout()

ax22 = plt.subplot2grid((2, 4), (1, 2), colspan=2, rowspan=1)
colors = cm.get_cmap('Spectral')(np.arange(n_) / n_)[:, :3]
for n in range(n_):
    if n == 0:
        plt.fill_between(np.sqrt(sig2_h_lambda[:, -1]),
                         w_lambda[n, :, -1],
                         np.zeros(v_),
                         color=colors[n, :])
    else:
        plt.fill_between(np.sqrt(sig2_h_lambda[:, -1]),
                         np.sum(w_lambda[:n + 1, :, -1], axis=0),
                         np.sum(w_lambda[:n, :, -1], axis=0),
                         color=colors[n, :])
Exemplo n.º 14
0
cum_z_KF = np.cumsum(z_KF[:, :2], axis=0)

# ## Plots

# +
plt.style.use('arpm')

fig1 = plt.figure()
plt.plot(tau, y_KF, 'b', tau, y[t_-1, :], 'r.')
plt.axis([min(tau), max(tau), np.min(y_KF), np.max(y_KF)])
plt.xlabel('Time to Maturity')
plt.ylabel('Rate')
plt.legend(['Fit', 'Rates'])
plt.grid(True)

add_logo(fig1)
plt.tight_layout()

t_plot = t_ - 1
# colors settings
c0 = [1, 0.4, 0.1]
c2 = [0, 0, 0.4]
# tick and labels for the time axes
dates = np.arange(1., t_)
date_tick = np.arange(10, t_plot, 75)
fig2, ax = plt.subplots(2, 1)

# axes for the first hidden factor and first principal component
plt.sca(ax[0])
plt.ylabel('cumulated $z_1$')
plt.plot(dates, cum_z_KF[:, 0], color=c2, lw=0.5)