示例#1
0
p_colors = p_colors.T

plt.xticks(dates[date_tick], fontsize=14)
plt.yticks(fontsize=14)
plt.xlim([min(dates), max(dates)])
plt.scatter(dates,
            epsi[:, i_plot - 1],
            s=30,
            c=p_colors,
            marker='.',
            cmap=color_map)
plt.title(db_invariants_series.columns[i_plot - 1] + ' observation weighting',
          fontweight='bold',
          fontsize=20)
ax3.xaxis.set_major_formatter(myFmt)
add_logo(fig1, location=1, set_fig_size=False)
fig1.tight_layout()

# marginal distributions

n_bins = 10 * np.log(t_)

hfp = plt.figure(figsize=(1280.0 / 72.0, 720.0 / 72.0), dpi=72.0)
ax = hfp.add_subplot(111)

if i_plot - 1 in ind_parametric:
    # HFP histogram
    f_eps, x_eps = histogram_sp(epsi_bonds[:, i_plot - 1],
                                p=p_bonds,
                                k_=n_bins)
    bar_width = x_eps[1] - x_eps[0]
示例#2
0
plt.ylabel('Carry')
plt.title('Carry in currencies')
# Yield to maturity curves
plt.sca(ax[1])
plt.axis([
    0, 1,
    min(np.min(yield_curve_b), np.min(yield_curve_l)),
    max(np.max(yield_curve_b), np.max(yield_curve_l))
])
plt.xticks(np.arange(0, 1.1, 0.1))
plt.grid(True)
# yield curve (base currency)
plt.plot(maturities, yield_curve_b, color=blue, lw=1)
plt.plot([maturities[i], maturities[i]], [yield_curve_b[i], yield_curve_b[i]],
         color='r',
         marker='.',
         markersize=15)
plt.text(maturities[i], yield_curve_b[i - 15] + 0.002, '$y_{t}^{b}$')
# yield curve (local currency)
plt.plot(maturities, yield_curve_l, color=blue, lw=1)
plt.plot([maturities[i], maturities[i]], [yield_curve_l[i], yield_curve_l[i]],
         color='r',
         marker='.',
         markersize=15)
plt.text(maturities[i], yield_curve_l[i - 15] + 0.002, '$y_{t}^{l}$')
plt.xlabel('Time to Maturity (years)')
plt.ylabel('Yield')
plt.title('Yield to maturity curves')
add_logo(fig)
plt.tight_layout()
示例#3
0
nok_stock_long = df_nokia_stock[(df_nokia_stock.date_tmstmp >= t_first) &
                                (df_nokia_stock.date_tmstmp < t_last)]
nok_dividends = df_nok_dividends[(df_nok_dividends.date_tmstmp >= t_first) &
                                 (df_nok_dividends.date_tmstmp < t_last)]
# extract values
dates = nok_stock_long.date_tmstmp.values
r = nok_dividends.date_tmstmp.values
cf_r = nok_dividends.dividends.values
v_stock = nok_stock_long.close.values
# -

# ## [Step 1](https://www.arpm.co/lab/redirect.php?permalink=s_elltest_compret-implementation-step01): Dividend-adjusted values and invariant series

v_adj = adjusted_value(v_stock, dates, cf_r, r, fwd)
epsi = np.diff(np.log(v_adj))

# ## [Step 2](https://www.arpm.co/lab/redirect.php?permalink=s_elltest_compret-implementation-step02): Ellipsoid test

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

# perform and show ellipsoid test for invariance
rho, conf_int = \
    invariance_test_ellipsoid(epsi, l_,
                              conf_lev=conf_lev, fit=0, r=2,
                              title='Invariance test on daily yield changes')
fig = plt.gcf()
add_logo(fig, set_fig_size=False, size_frac_x=1/8)


示例#4
0
plt.plot(np.linspace(min(min1, min2), max(max1, max2)),
         np.linspace(min(min1, min2), max(max1, max2)),
         color='black',
         lw=2)
plt.title('General case', fontsize=20, fontweight='bold')
plt.xlabel(r'$X_2$', fontsize=17)
plt.ylabel(r'$X_1$', fontsize=17)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
ax[0].spines['top'].set_visible(False)
ax[0].spines['right'].set_visible(False)

# create subplot of strong dominance: x_2 versus x_3
plt.sca(ax[1])
plt.scatter(x_2, x_3, marker='.')
plt.axis([min2, max2 + 4, min2, max2 + 4])
plt.plot(np.linspace(min2, max2 + 4),
         np.linspace(min2, max2 + 4),
         color='black',
         lw=2)
plt.title('Strong dominance', fontsize=20, fontweight='bold')
plt.xlabel(r'$X_2$', fontsize=17)
plt.ylabel(r'$X_3$', fontsize=17)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
ax[1].spines['top'].set_visible(False)
ax[1].spines['right'].set_visible(False)

add_logo(f, location=4, set_fig_size=False)
plt.tight_layout()
示例#5
0
# Scores
plt.sca(ax12)
plt.hist(s_0_lg, 80, density=True, alpha=0.7, color='r')
plt.hist(s_1_lg, 80, density=True, alpha=0.7, color='b')
plt.legend(['S | 0', 'S | 1'])
plt.title('Scores distribution')

# Confusion matrix
plt.sca(ax13)
cax_1 = plt.bar([0, 1], [cm_lg[0, 1]/np.sum(x_test == 0),
                         cm_lg[1, 0]/np.sum(x_test == 1)])
plt.ylim([0, 1.1])
plt.xticks([0, 1], ('$fpr$', '$fnr$'))
plt.title('Confusion matrix')
add_logo(fig1, location=1, size_frac_x=1/8)
plt.tight_layout()
# -

# ## 2) Logistic regression with interactions

# +
fig2 = plt.figure()
ax31 = plt.subplot2grid((2, 2), (0, 0), rowspan=2)
ax32 = plt.subplot2grid((2, 2), (0, 1))
ax33 = plt.subplot2grid((2, 2), (1, 1))

# out of sample ROC curve
plt.sca(ax31)
plt.plot([0, 1], [0, 1], 'k--', lw=1)
plt.plot([0, 0, 1], [0, 1, 1], 'g')
示例#6
0
u = np.random.rand(j_)

# ## [Step 2](https://www.arpm.co/lab/redirect.php?permalink=s_uniform_to_gamma-implementation-step02): Apply inverse transform sampling

x = stats.gamma.ppf(u, k , theta)

# ## [Step 3](https://www.arpm.co/lab/redirect.php?permalink=s_uniform_to_gamma-implementation-step03): Compute the empirical histogram of the pdf of the new sample

k_bar = np.round(5*np.log(j_))
[f_hist, xi] = histogram_sp(x, k_=k_bar)

# ## Plots

plt.style.use('arpm')
fig = plt.figure(figsize=(1280.0/72.0, 720.0/72.0), dpi=72.0)
plt.title('Uniform-to-gamma mapping', fontsize=20, fontweight='bold')
# empirical pdf
plt.bar(xi, f_hist, width=xi[1]-xi[0], facecolor=[.7, .7, .7],
        edgecolor='k',  label='empirical pdf')
# analytical pdf
plt.plot(xi, stats.gamma.pdf(xi, k , theta),
         color='red', lw=5, label='gamma pdf')
plt.grid(True)
plt.ylim([0, 1.1*np.max(f_hist)])
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.legend(fontsize=17)
add_logo(fig, location=2, set_fig_size=False)
plt.tight_layout()
del out
# -

# ## Plots

# +
plt.style.use('arpm')
fig = plt.figure()
X, Y = np.meshgrid(m_moneyness, tau_implvol)
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X,
                       Y,
                       implvol_m_moneyness[-1, :, :],
                       linewidth=0,
                       antialiased=False)
add_logo(fig)
plt.tight_layout()

fig1 = plt.figure()
label1 = 'Time to expiry '+str(round(tau_implvol[2], 3)) + \
    'y, m_moneyness ' + str(round(m_moneyness[1], 3))
label2 = 'Time to expiry '+str(round(tau_implvol[4], 3)) + \
    'y, m_moneyness ' + str(round(m_moneyness[1], 3))
plt.plot(implvol_m_moneyness[:, 2, 1], 'r')
plt.plot(implvol_m_moneyness[:, 4, 1])
plt.gca().legend((label1, label2))
add_logo(fig1)
plt.tight_layout()

fig2 = plt.figure()
X, Y = np.meshgrid(delta_moneyness, tau_implvol)
示例#8
0
out.to_csv(path + 'db_invariants_p_credit.csv', index=None)
del out
# -

# ## [Step 7](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step02-implementation-step07): Perform invariance tests

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

invar = db_invariants[i_plot - 1][~np.isnan(db_invariants[i_plot - 1])]

_ = invariance_test_ellipsoid(invar, lag_)
fig_ellipsoid = plt.gcf()
fig_ellipsoid.set_dpi(72.0)
fig_ellipsoid.set_size_inches(1280.0 / 72.0, 720.0 / 72.0)
add_logo(fig_ellipsoid, set_fig_size=False)
plt.show()

invariance_test_ks(invar)
fig_ks = plt.gcf()
fig_ks.set_dpi(72.0)
fig_ks.set_size_inches(1280.0 / 72.0, 720.0 / 72.0)
add_logo(fig_ks, set_fig_size=False)
plt.tight_layout()

_ = invariance_test_copula(invar, lag_)
fig_cop = plt.gcf()
fig_cop.set_dpi(72.0)
fig_cop.set_size_inches(1280.0 / 72.0, 720.0 / 72.0)
plt.tight_layout()
示例#9
0
plt.yticks(fontsize=9)

ax2 = plt.subplot2grid((2, 4), (1, 2), colspan=1)
ax2 = sns.heatmap(sig2_glasso[:n_plot, :n_plot],
                  cmap='BrBG',
                  center=0,
                  xticklabels=stocks_names[:n_plot],
                  yticklabels=stocks_names[:n_plot],
                  vmin=minncov,
                  vmax=maxxcov,
                  square=True)
plt.title('Glasso corr.', fontweight='bold', fontsize=20)
plt.xticks(fontsize=9)
plt.yticks(fontsize=9)

ax22 = plt.subplot2grid((2, 4), (1, 3), colspan=1)
ax22 = sns.heatmap(phi2_glasso[: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.title('Glasso inv. corr.', fontweight='bold', fontsize=20)
plt.xticks(fontsize=9)
plt.yticks(fontsize=9)

add_logo(fig, axis=ax, set_fig_size=False)
plt.tight_layout()
示例#10
0
p3 = plt.plot([tick_time[1:i_], tick_time[1:i_]],
              [p_last_k[1:i_], p_last_k[1:i_]],
              c='b',
              marker='.',
              label='traded price')

p2 = plt.plot(tick_time, p_mic, color=orange, label='microprice')
plt.legend(handles=[p3[0], p2[0], p1[0], p0[0]])

# signal, trade sign series and buy/sell triggers
plt.sca(ax[1])
plt.xlabel('Tick time')
plt.ylabel('Trade sign EWMA')
plt.title('Trade autocorrelation signal')
for i in range(i_):
    p4 = plt.plot([tick_time[i], tick_time[i]],
                  [s_trade_sign[i], s_trade_sign[i]],
                  color='k',
                  marker='.')
    p5 = plt.plot([tick_time[i], tick_time[i]],
                  [delta_sgn_p[k_0 + i], delta_sgn_p[k_0 + i]],
                  color='b',
                  marker='.')

plt.xlim([1, i_])
plt.xticks(xtick)
plt.yticks(np.arange(-1, 1.5, 0.5))
plt.legend(['signal', 'trade sign'])
add_logo(fig, axis=ax[0], location=8)
plt.tight_layout()
示例#11
0
    drift_hor_sel[1] + 2 * np.sqrt(sig2_hor_sel[1, 1])
],
         color=orange,
         lw=2)  # 2 z-score
plt.plot(0.5,
         x[-1, idx_tau[1]],
         color='k',
         marker='.',
         markersize=10,
         markerfacecolor='k')  # initial position
plt.plot(0.5,
         drift_hor_sel[1],
         color='g',
         marker='.',
         markersize=10,
         markerfacecolor='g')  # mean
leg = plt.legend(handles=[l1[0], l2[0], l3[0], l4[0], l5[0], hs[0]],
                 labels=[
                     'Pdf', 'Stationary distribution', '2 z-score',
                     'Current value', 'Mean', 'Horizon scenarios'
                 ],
                 bbox_to_anchor=(1, -0.5))

add_logo(fig, axis=ax[1, 1], size_frac_x=1 / 8, location=1)
# -

t_m.shape
t_m[-1]

t_now
示例#12
0
# rescaled random sample
h02 = ax1.plot(x_rs[:, 0],
               x_rs[:, 1],
               x_rs[:, 2],
               '.',
               color='b',
               markersize=3,
               label='Target variables')
ax1.grid(False)
ax1.set_xlabel(r'$X_{1}$')
ax1.set_ylabel(r'$X_{2}$')
ax1.set_zlabel(r'$X_{3}$')
ax1.legend(handles=[h00, h01[0], h02[0]])

add_logo(fig1, size_frac_x=1 / 8)

fig2, ax2 = plot_ellipsoid(np.zeros(3),
                           sig_inv @ sig2_x @ sig_inv,
                           r=scale,
                           plot_axes=False,
                           ellip_color=(.8, .8, .8),
                           ellip_alpha=0.3,
                           n_points=0)

# plot plane
ax2.view_init(30, -140)
ax2.plot_surface(plane[0],
                 plane[1],
                 plane[2],
                 color=[.8, .8, .8],
示例#13
0
plt.plot(mu[i1], mu[i2], 'o', markerfacecolor='k')
plt.plot(mu_shrink[i1], mu_shrink[i2], 'o', markerfacecolor='g')
plt.plot([mu_sample[i1], mu[i1]], [mu_sample[i2], mu[i2]], color=c1)
plt.plot([mu_shrink[i1], mu[i1]], [mu_shrink[i2], mu[i2]], color='g')
plt.legend([
    'sample scenarios (%3.0f)' % t_,
    'out-of-sample scenarios (%3.0f)' %
    (t_global - t_), 'sample mean', 'global mean', 'shrinkage mean'
],
           bbox_to_anchor=(0., .8, 1.2, .102),
           frameon=True,
           facecolor='white')
plt.xlabel(names_select[0])
plt.ylabel(names_select[1])

add_logo(fig1)

fig2, ax = plt.subplots(2, 1)
plt.sca(ax[0])
plt.bar(1, loss_sample, 0.4, facecolor=c1, edgecolor=c1)
plt.bar(2, loss_shrink, 0.4, facecolor='g', edgecolor='g')
plt.xlim([0.5, 2.5])
plt.ylim([0, max([loss_sample, loss_shrink])])
plt.title('Loss')
plt.xticks([1, 2], ['sample', 'shrinkage'])

plt.sca(ax[1])
plt.bar(2, w_shrink[0] + w_shrink[1], 0.4, facecolor='g', edgecolor='g')
plt.bar(1, w_sample[0] + w_sample[1], 0.4, facecolor=c1, edgecolor=c1)
plt.bar(2, w_shrink[0], 0.4, facecolor='w', edgecolor='g')
plt.bar(1, w_sample[0], 0.4, facecolor='w', edgecolor=c1)
示例#14
0
# +
delta_theta = np.diff(theta, axis=0)
# -

# ## [Step 2](https://www.arpm.co/lab/redirect.php?permalink=s_kolmsmirn_ytm_ns-implementation-step02): Kolmogorov-Smirnov tests

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

# names of figures
name = {}
name[0] = r'Kolmogorov-Smirnov test(increments of level parameter $\theta_1$)'
name[1] = r'Kolmogorov-Smirnov test(increments of slope parameter $\theta_2$)'
name[
    2] = r'Kolmogorov-Smirnov test(increments of curvature parameter $\theta_3$)'
name[
    3] = r'Kolmogorov-Smirnov test(increments of decay parameter $\theta_4^2$)'

z_ks = np.zeros(4)
z = np.zeros(4)
# perform and show ellipsoid test for invariance on NS parameters
for k in range(4):
    fig = plt.figure()
    z_ks, z = invariance_test_ks(delta_theta[:, k],
                                 conf_lev=conf_lev,
                                 title=name[k])
    fig_ks = plt.gcf()
    fig_ks.set_dpi(72.0)
    fig_ks.set_size_inches(1280.0 / 72.0, 720.0 / 72.0)
    add_logo(fig_ks, set_fig_size=False)
示例#15
0
# +
plt.style.use('arpm')
u_color = [60 / 255, 149 / 255, 145 / 255]

# set figure specification
f = plt.figure(1, figsize=(1280.0 / 72.0, 720.0 / 72.0), dpi=72.0)

ax1 = plt.axes([0.10, 0.5, 0.35, 0.35], projection='3d')
ax1.plot_surface(u_1, u_2, pdf_u.T, facecolor='k', edgecolor=u_color)
ax1.view_init(30, -120)
plt.xlabel('Grade $U_1$', labelpad=5)
plt.ylabel('Grade $U_2$', labelpad=5)
ax1.set_zlabel('Normal copula pdf')
str = r'$\rho_{1,2}$ = % .2f' % rho
plt.title(str)

ax2 = plt.axes([0.55, 0.5, 0.35, 0.35], projection='3d')
ax2.plot_surface(u_1, u_2, cdf_u.T, facecolor='k', edgecolor=u_color)
ax2.view_init(30, -120)
plt.xlabel('Grade $U_1$', labelpad=5)
plt.ylabel('Grade $U_2$', labelpad=5)
ax2.set_zlabel('Normal copula cdf')

ax3 = plt.axes([0.35, 0.1, 0.3, 0.3])
plt.gca().set_aspect('equal', adjustable='box')
ax3.scatter(u1, u2, s=10, color=u_color, marker='*')
plt.xlabel('Grade $U_1$', labelpad=5)
plt.ylabel('Grade $U_2$', labelpad=5)

add_logo(f, axis=ax1, location=4, set_fig_size=False)
示例#16
0
plt.legend(handles=[p3[0], p2[0], p4[0], p1[0], p0[0]],
           bbox_to_anchor=(0., .85, 1., .102),
           loc=3,
           ncol=5,
           mode="expand")

# signal and triggers
plt.sca(ax[1])
ymin_2 = np.min(s_ord_imb) - 0.11
ymax_2 = np.max(s_ord_imb) + 0.2
ytick_2 = np.arange(-0.6, 0.6 + 0.3, 0.3)
plt.axis([np.min(tick_time), np.max(tick_time), ymin_2, ymax_2])
plt.xticks(xtick)
plt.yticks(ytick_2)
for i in range(i_):
    plt.plot([tick_time[i], tick_time[i]], [s_ord_imb[i], s_ord_imb[i]],
             color='k',
             marker='.')

p5 = plt.plot(tick_time,
              np.tile(0.3, i_),
              color=dred,
              label='cross the spread (buy order) trigger')
plt.legend(loc=3)
plt.ylabel('Signal')
plt.xlabel('Tick time')
plt.title('Order imbalance signal')
plt.grid(True)
add_logo(fig, location=1)
plt.tight_layout()
示例#17
0
ax3.set_zlabel('$X$')

ax3.view_init(10, ax3.azim)

dummy_legend_lines = [
    Line2D([0], [0],
           marker='o',
           markerfacecolor='b',
           color='w',
           lw=4,
           markersize=8),
    Line2D([0], [0],
           marker='o',
           markerfacecolor='g',
           color='w',
           lw=4,
           markersize=8),
    Line2D([0], [0],
           marker="s",
           markerfacecolor=[220 / 250, 220 / 250, 220 / 250],
           lw=4,
           color='w',
           markersize=8)
]

plt.legend(dummy_legend_lines,
           ['Scenarios', 'Predicted scenarios', 'Regression plane'])

add_logo(fig, size_frac_x=1 / 8)
plt.tight_layout()
示例#18
0
for i in range(2 * dt, len(t_ms_dt) - dt, dt):
    plt.plot([t_ms_dt[i], t_ms_dt[i]], [h_bid_res[i], p_bid[i] - 0.0007],
             color=[.8, .8, .8],
             linestyle='-')
    plt.plot([t_ms_dt[i], t_ms_dt[i]], [p_ask[i] + 0.0007, h_ask_res[i]],
             color=[.8, .8, .8],
             linestyle='-')

ax1 = plt.subplot(212)
ax1.yaxis.label.set_color('red')
ax1.set_ylabel('Cumulative volume')
ax1.set_xlabel('time')
ymax_2 = np.max(q[range(k_0, k_1)]) + 30
ymin_2 = np.min(q[range(k_0, k_1)])
ax1.set_xlim(min(t_ms_dt), max(t_ms_dt))
ax1.set_ylim(ymin_2, ymax_2)
ax1.step(trans_time, q[range(k_0, k_1)], color='r', where='post')
ax1.plot(trans_time, q[range(k_0, k_1)], '.', color='r', markersize=10)

ax2 = ax1.twinx()
ax2.yaxis.label.set_color('green')
ax2.set_ylabel("Cumulative sign")
ymax_3 = np.max(sgn[range(k_0, k_1)]) + 1
ymin_3 = np.min(sgn[range(k_0, k_1)])
ax2.set_ylim(ymin_3, ymax_3)
ax2.set_xlim(min(t_ms_dt), max(t_ms_dt))
ax2.step(trans_time, sgn[range(k_0, k_1)], color='g', where='post')
ax2.plot(trans_time, sgn[range(k_0, k_1)], '.', color='g', markersize=10)
add_logo(fig, location=5)
plt.tight_layout()
示例#19
0
# HFP std of long-short portfolio
s_2_hat = np.sqrt(w2.T @ s2_x_hat @ w2)
# truncated std of long-short portfolio
s_2_trunc = np.sqrt(w2.T @ s2_x_trunc @ w2)
# -

# ## [Step 10](https://www.arpm.co/lab/redirect.php?permalink=s_pca_truncated_lfm-implementation-step10): Define data used for ploting of the histogram

[f_l, xi_l] = histogram_sp(c2_u_hat[np.triu_indices(c2_u_hat.shape[0], 1)])

# ## Plots

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

# Histogram: correlations among residuals

fig = plt.figure()
mydpi = 72.0
fig = plt.figure(figsize=(1280.0 / mydpi, 720.0 / mydpi), dpi=mydpi)
h = plt.bar(xi_l,
            f_l,
            width=xi_l[1] - xi_l[0],
            facecolor=[.7, .7, .7],
            edgecolor='k')
plt.text(0.3, 7, r'$\mathbb{C}$' + r'$r$' + r'$\{U_m, U_n\}$', fontsize=30)
plt.xlabel(r'Correlation values', fontsize=17)
plt.ylabel(r'Frequency', fontsize=17)
add_logo(fig, location=4)
示例#20
0
                 cmap=plt.cm.RdYlBu, alpha=0.7)

# Scatter plot
for i, color in zip(range(n_classes), plot_colors):
    idx = np.intersect1d(np.where(x == i), idxx)
    ax2.scatter3D(psi_z[idx, 0], psi_z[idx, 1], x[idx], c=color,
                  label=['0', '1'][i],
                  cmap=plt.cm.RdYlBu, s=10, alpha=1)
ax2.view_init(30, -90)
ax2.set_xlabel('$\psi_1(Z)$')
ax2.set_ylabel('$\psi_2(Z)$')
ax2.set_zlabel('$X$')
ax2.set_title('Surface fitted with linear classifier', fontweight='bold')
ax2.set_xlim([-2, 2])
ax2.set_ylim([-2, 2])
add_logo(fig, axis=ax2, location=2, size_frac_x=1/8)
plt.tight_layout()

# Regions plot
ax3 = plt.subplot2grid((4, 4), (2, 2), colspan=2, rowspan=2)
xx_pred = chi_alphabeta(np.c_[psi_zz1.ravel(), psi_zz2.ravel()])
# Put the result into a color plot
xx_pred = xx_pred.reshape(psi_zz1.shape)
ax3.contourf(psi_zz1, psi_zz2, xx_pred, cmap=plt.cm.RdYlBu, alpha=0.5)
# Scatter plot
for i, color in zip(range(n_classes), plot_colors):
    idx = np.where(x == i)
    ax3.scatter(psi_z[idx, 0], psi_z[idx, 1], c=color,
                label=['0', '1'][i],
                cmap=plt.cm.RdYlBu, edgecolor='black', s=15, alpha=0.7)
ax3.set_xlabel('$\psi_1(Z)$')
示例#21
0
文件: s_dcc_fit.py 项目: s0ap/arpmRes
# Scatter plot
xi_plot = xi[:, [i_1, i_2]]
fig = plt.figure()
plt.scatter(xi[:, i_1], xi[:, i_2], 2, marker='o', linewidths=1)
plt.axis('equal')
plt.axis([
    np.percentile(xi_plot[:, 0], 2),
    np.percentile(xi_plot[:, 0], 98),
    np.percentile(xi_plot[:, 1], 2),
    np.percentile(xi_plot[:, 1], 98)
])
plt.xlabel('$\Xi_{%1.f}$' % (i_1 + 1))
plt.ylabel('$\Xi_{%1.f}$' % (i_2 + 1))
plt.ticklabel_format(style='sci', scilimits=(0, 0))

# Ellipsoids
mu_plot = np.zeros(2)
rho2_plot = rho2[np.ix_([i_1, i_2], [i_1, i_2])]
r2_t_plot = r2_t_nextstep[np.ix_([i_1, i_2], [i_1, i_2])]
ell_unc = plot_ellipse(mu_plot, rho2_plot, color='b')
ell_cond = plot_ellipse(mu_plot, r2_t_plot, color='tomato')

plt.legend([
    'Unconditional correlation: $rho^{2}$=%1.2f %%' % (100 * rho2_plot[0, 1]),
    'Conditional correlation: $r^{2}_{t+1}$=%1.2f %%' %
    (100 * r2_t_plot[0, 1]), 'Quasi-invariants'
])
plt.title('Dynamic conditional correlation')
add_logo(fig, location=2)
                  lw=1)

f, xp = histogram_sp(x_proj[:, -1, d_plot - 1], k_=10 * np.log(j_))
f1 = plt.barh(xp,
              f / 10,
              height=xp[1] - xp[0],
              left=t_ + 1 + m_,
              facecolor=[.3, .3, .3],
              edgecolor='k')
plt.title('Projected path: ' + risk_drivers_names[d_plot - 1],
          fontweight='bold',
          fontsize=20)
plt.xlabel('t (days)', fontsize=17)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
add_logo(fig1, set_fig_size=False)
fig1.tight_layout()

# plot projected ratings
# select paths with rating changes
ind_j_plot_GE = np.zeros(1)
ind_j_plot_GE[0] = 0
k = 0
while k < num_plot:
    k = k + 1
    for j in range(j_):
        if (j not in ind_j_plot_GE
                and ratings_proj[j, -1, 0] != ratings_proj[k, -1, 0]):
            ind_j_plot_GE = np.append(ind_j_plot_GE, j)
            break
示例#23
0
ax2 = plt.subplot(g[0, 0])
ax2.bar(omega,
        lambda2_hat[:k_] / lambda2_hat[0],
        width=omega[1] - omega[0],
        facecolor=lightgrey,
        label=r'empirical')
ax2.plot(omega,
         lambda2_omega / lambda2_omega[0],
         color=darkred,
         lw=1.5,
         label=r'theoretical')
ax2.set_ylim([0, 1.1])
plt.legend()
ax2.set_title('Eigenvalues')
ax2.set_xlabel('frequences')

ax3 = plt.subplot(g[0, 1])
ax3.bar(omega,
        r2_omega[:k_],
        facecolor=lightgrey,
        width=omega[1] - omega[0],
        label=r'empirical')
ax3.plot(omega, r2_omega, color=darkred, lw=1.5, label=r'theoretical')
ax3.set_ylim([0, 1.1])
plt.legend()
ax3.set_title('$\mathcal{R}^2$')
ax3.set_xlabel('frequences')

add_logo(f, location=4)
plt.tight_layout()
示例#24
0
# signal: exponential moving average of the traded volume with a fast decay
plt.subplot2grid((2, 1), (1, 0))
plt.axis([min(tick_time), max(tick_time), 0, 155])
plt.xticks(xtick)
plt.yticks(np.arange(0, 200, 50))

p4 = plt.plot(tick_time,
              delta_q[k_0:k_1 + 1],
              color='c',
              marker='.',
              label='traded volume')
maxticktime = len(tick_time) - 1
p5 = plt.plot([tick_time[:maxticktime], tick_time[:maxticktime]],
              [s_vol_clus[:maxticktime], s_vol_clus[:maxticktime]],
              lw=1,
              color='k',
              marker='.',
              label='signal')

p6 = plt.plot(tick_time,
              np.tile(30, i_),
              color=dred,
              label='increase order trigger')

plt.legend(handles=[p4[0], p5[0], p6[0]])
plt.ylabel('Volume')
plt.xlabel('Tick time')
plt.title('Signal: exponential moving average of the traded volume')
add_logo(fig, location=6)
plt.tight_layout()
示例#25
0
c0_bl = [0.27, 0.4, 0.9]
c1_or = [1, 0.5, 0.1]

# spectrum plot
fig1 = plt.figure()
plt.bar(np.arange(i_), np.log(lambda2_hat), facecolor=c0_bl,
        label='sample spectrum')
plt.plot(np.arange(k_), np.log(lambda2_bar[:k_]), color=c1_or, lw=2)
plt.plot(np.arange(k_, i_), np.log(lambda2_bar[k_:i_]), color=c1_or, lw=2,
         label='filtered spectrum')
plt.legend()
plt.title('Spectrum')
plt.ylabel('log-eigenvalues')
plt.xlabel('stocks')
add_logo(fig1, location=5)

# spectrum distribution
fig2 = plt.figure()
density, xbin = histogram_sp(lambda2_hat, k_=10*i_)
pp1 = plt.bar(xbin, density, width=xbin[1]-xbin[0], facecolor=c0_bl,
              edgecolor='none', label='sample eigenvalues below threshold')
pp2 = plt.plot(x_mp, y_mp*(1 - k_ / i_), color='g', lw=2,
               label='Marchenko-Pastur fit')
x_filtered = lambda2_bar[:k_ + 2]
density_filtered = np.r_['-1', np.ones((1, k_+1)), np.array([[i_ - k_]])]
pp3 = plt.plot(np.r_[x_filtered.reshape(1, -1), x_filtered.reshape(1, -1)],
               np.r_[np.zeros((1, k_ + 2)), density_filtered], color=c1_or,
               lw=2, label='filtered spectrum')
plt.xlim([0, 3*np.max(x_mp)])
plt.ylim([0, max([np.max(y_mp*(1 - k_ / i_)), np.max(density)])])
axes[0].plot(t_plot, x[t_plot, 0], 'b')
axes[0].plot(t_plot, x[t_plot, 0], 'r--')
axes[0].set_xlabel('$t$')
axes[0].set_ylabel('$x_1$')
axes[0].set_xlim(xlim)
axes[0].set_ylim(ylim)
axes[0].legend(['Process', 'Predicted process'])

axes[1].plot(t_plot, x[t_plot, 1], 'b')
axes[1].plot(t_plot, x[t_plot, 1], 'r--')
axes[1].set_xlabel('$t$')
axes[1].set_ylabel('$x_2$')
axes[1].set_xlim(xlim)
axes[1].set_ylim(ylim)
axes[1].legend(['Process', 'Predicted process'])
add_logo(fig1, size_frac_x=1 / 8)
plt.tight_layout()

fig2 = plt.figure()
gs = gridspec.GridSpec(1, 3, width_ratios=[1, 3, 1])
ax0 = plt.subplot(gs[0])
ax0.plot(ylim, ylim, 'k')
ax0.plot(x[t_plot, 0], x_pc_bar[t_plot, 0], 'r.')
ax0.set_xlabel('$x_1$')
ax0.set_ylabel('$\overline{x}_{1}^{pc}$')
ax0.set_xlim(ylim)
ax0.set_ylim(ylim)

ax1 = plt.subplot(gs[1])
ax1.plot(t_plot, z_pc[t_plot, 0], 'b')
ax1.set_xlabel('$t$')
示例#27
0
# ## Plots

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

# pdf of Sigma2
fig1 = plt.figure()
plt.plot(s, 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 * (s[-1] - s[0]) + s[0], 0.7 * np.max(f_sigma2), text, color='b')
plt.xlabel('$\Sigma^2$')

add_logo(fig1, location=1)

# pdf of M
fig2 = plt.figure()
plt.plot(b, f_beta, lw=1.5, color='g')

text = r'$B \sim t (\nu_{pri},\beta_{pri},\sigma_{pri}^2,' + \
        '(t_{pri}\sigma^2_{Z,pri})^{-1})$' + '\n\n' + \
        r'$\nu_{pri}$=%3.0f, $t_{pri}$=%3.0f' % (v_pri, t_pri) + '\n' + \
        r'$\beta_{pri}$=%3.1f, $\sigma_{pri}^2$=%3.1f, $\sigma_{Z, pri}^2$=%3.1f' % (beta_pri, sigma2_pri, sigma2_zpri)

plt.text(0.7 * (b[-1] - b[0]) + b[0], 0.7 * np.max(f_beta), text, color='g')
plt.xlabel('$B$')

add_logo(fig2, location=1)
示例#28
0
txt5 = 'Half-life (days): % 3.0f' % tau_hl
plt.title('Exponential decay probabilities\n'+txt1+txt5,
          fontsize=20, fontweight='bold')

# scatter plot color-coded
plt.sca(ax[1])
plt.xlim(min(spx.date[1:]), max(spx.date[1:]))
plt.ylim(-0.15, 0.15)
plt.scatter(np.array(spx.date[1:]), epsi, s=3, c=p_colors, marker='*',
            cmap=color_map)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
ax[1].xaxis.set_major_formatter(myFmt)
plt.ylabel(r'invariant $\epsilon_t$', fontsize=17)
plt.title('S&P 500', fontsize=20, fontweight='bold')
add_logo(f, set_fig_size=False)
plt.tight_layout()

# HFP histogram
hfp = plt.figure(figsize=(1280.0/72.0, 720.0/72.0), dpi=72.0)
ax = hfp.add_subplot(111)
plt.xlim(-0.15, 0.15)
bar_width = x_eps[1] - x_eps[0]
ax.bar(x_eps, f_eps, width=bar_width, fc=[0.7, 0.7, 0.7],
       edgecolor=[0.5, 0.5, 0.5])
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
ax.set_title('HFP distribution', fontsize=20, fontweight='bold')
add_logo(hfp, set_fig_size=False)
plt.tight_layout()
示例#29
0
ax1 = plt.subplot(gs[1])
ax1.scatter(x[:, 0], x[:, 1], color=[.8, .8, .8], marker='.', s=40)
plot_ellipse(mu_x,
             sigma2_x,
             r=r,
             display_ellipse=True,
             plot_axes=False,
             plot_tang_box=True,
             color='k')
ax1.plot(u_axes0[0], u_axes0[1], linewidth=2.0, color='red')
ax1.plot(u_axes1[0], u_axes1[1], linewidth=2.0, color='blue')
ax1.set_xlim(x_range)
ax1.tick_params(axis='y', colors='None')
ax1.tick_params(axis='x', colors='None')
ax1.set_ylim(x_range)
ax1.set_xlabel('$X_1$', labelpad=-1, fontsize=12)
ax1.set_ylabel('$X_2$', labelpad=-20, fontsize=12)

ax2 = plt.subplot(gs[3])
plt.bar(xi_z1, f_z1, facecolor=[.7, .7, .7])
ax2.set_xlim(x_range)
ax2.plot([-r * np.sqrt(lambda2[0]), r * np.sqrt(lambda2[0])], [0, 0],
         linewidth=5.0,
         color='red')
ax2.set_xlabel('$Z_1^{PC}$', fontsize=14)

plt.tight_layout()
add_logo(f, location=1, size_frac_x=1 / 12)
# -
示例#30
0
fig1 = plt.figure(figsize=(1280.0/72.0, 720.0/72.0), dpi = 72.0)
f, xp = histogram_sp(y_h, p=p, k_=30)
xp = xp*1e-6
plt.bar(xp, f, width=xp[1]-xp[0], facecolor=[.3, .3, .3], edgecolor='k',
       label = 'Current holdings')
f, xp = histogram_sp(y_h_es_qsi, p=p, k_=30)
xp = xp*1e-6
plt.bar(xp, f, width=xp[1]-xp[0], facecolor=[.6, .6, .6, .9],
        edgecolor='k', label = 'Optimal holdings')
plt.title('Optimized portfolio ex-ante P&L distribution',
         fontsize=20, fontweight='bold')
plt.xlabel(r'$Y_h$ (million USD)', fontsize=17)
plt.legend(fontsize=17)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
add_logo(fig1, set_fig_size=False)

fig2, [ax1, ax2] = plt.subplots(2, 1,
                                figsize=(1280.0/72.0, 720.0/72.0), dpi = 72.0)
xlim = [np.min(variance), np.max(variance)]

plt.sca(ax1)
plt.plot(variance, expectation, lw=1, label='Efficient frontier')
plt.plot(variance[ind_lambda_star], expectation[ind_lambda_star],
         'ro', label ='Optimal holdings')
plt.title('Mean-variance efficient frontier',
         fontsize=20, fontweight='bold')
plt.xlabel('Variance', fontsize=17)
plt.ylabel('Expectation', fontsize=17)
plt.xlim(xlim)
plt.legend(fontsize=17)