Esempio n. 1
0
# 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)
Esempio n. 2
0
# ## [Step 1](https://www.arpm.co/lab/redirect.php?permalink=s_display_corr_norm_ellips-implementation-step01): Compute eigenvalue and eigenvectors

e, lambda2 = pca_cov(sigma2_x)

# ## [Step 2](https://www.arpm.co/lab/redirect.php?permalink=s_display_corr_norm_ellips-implementation-step02): Compute simulations of the target and factors

x = simulate_normal(mu_x, sigma2_x, j_)
z = (x - mu_x) @ e

# ## [Step 3](https://www.arpm.co/lab/redirect.php?permalink=s_display_corr_norm_ellips-implementation-step03): Perform computations for plots

x_bar = plot_ellipse(mu_x,
                     sigma2_x,
                     r=r,
                     display_ellipse=False,
                     plot_axes=True,
                     plot_tang_box=True,
                     color='k')
[f_z1, xi_z1] = histogram_sp(z[:, 0], k_=300)
[f_z2, xi_z2] = histogram_sp(z[:, 1], k_=300)

# ## Plots

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

mydpi = 72.0
f = plt.figure(figsize=(1280.0 / mydpi, 720.0 / mydpi), dpi=mydpi)

# setup range
Esempio n. 3
0
sigma2_rescaled = n_ * sigma2

# ## [Step 3](https://www.arpm.co/lab/redirect.php?permalink=s_min_vol_ellips-implementation-step03): Generate location and dispersion to satisfy Mah distance constraint

# +
m = mu + np.random.rand(2)
a = np.random.rand(2, 2)
s2 = a @ a.T  # generate symmetric covariance matrix
mah_dist2 = np.zeros(j_)

for j in range(j_):
    mah_dist2[j] = (mahalanobis_dist(x[[j], :], m, s2))**2
r2 = np.mean(mah_dist2)  # average square Mahalanobis distance
s2 = s2 * r2
# -

# ## Plot

plt.style.use('arpm')
grey = [.5, .5, .5]
fig = plt.figure()
plt.plot([], [], color='r', lw=2)  # dummy plot for legend
plt.plot([], [], color='b', lw=2)  # dummy plot for legend
plot_ellipse(mu, sigma2_rescaled, r=1, color='r', line_width=2)
plot_ellipse(m, s2, r=1, color='b', line_width=2)
plt.scatter(x[:, 0], x[:, 1], s=5, color=grey)
plt.legend(('expectation-(rescaled)covariance ellipsoid',
            'generic ellipsoid (expected square Mah. distance = 1)'))
add_logo(fig)
plt.tight_layout()
Esempio n. 4
0
orange = [0.94, 0.35, 0]  # orange

jsel = 15

fig, ax = plt.subplots(2, 2)

# joint distribution
plt.sca(ax[0, 1])
hs = plt.plot(x_t_now_t_hor[:200, -1, idx_tau[0]],
              x_t_now_t_hor[:200, -1, idx_tau[1]],
              'k.',
              markersize=3)  # projected scenarios
plot_ellipse(drift_stat_sel,
             sig2_stat_sel,
             r=2,
             plot_axes=0,
             plot_tang_box=0,
             color=dgrey,
             line_width=1.5)  # stationary ellipsoid
plot_ellipse(drift_hor_sel,
             sig2_hor_sel,
             r=2,
             plot_axes=0,
             plot_tang_box=0,
             color=orange,
             line_width=1.5)  # selected hor ellipsoid
plt.plot(x[-1, idx_tau[0]],
         x[-1, idx_tau[1]],
         marker='o',
         color='k',
         markerfacecolor='k',
Esempio n. 5
0
x_max = np.ceil(max(x[:, ind[0]]) * 100) / 100
y_min = np.floor(min(x[:, ind[1]]) * 100) / 100
y_max = np.ceil(max(x[:, ind[1]]) * 100) / 100
x_lim = ([x_min, x_max])
y_lim = ([y_min, y_max])
plt.xticks()
plt.yticks()
plt.grid(True)

# next-step ellipsoid
plt.plot([x[-1, ind[0]], x[-1, ind[0]]], [x[-1, ind[1]], x[-1, ind[1]]],
         color=[1, 0.6, 0],
         marker='.',
         markersize=8,
         linestyle='none')
plot_ellipse(mu_select_ns,
             sig2_select_ns,
             r=2.4,
             plot_axes=0,
             plot_tang_box=0,
             color='b',
             line_width=1.5)
plt.gca().yaxis.set_major_formatter(
    FuncFormatter(lambda y, _: '{:.0%}'.format(y)))
plt.gca().xaxis.set_major_formatter(
    FuncFormatter(lambda y, _: '{:.2%}'.format(y)))
plt.legend(
    ['Past observations', 'Current observation', 'Next-step prediction'])
add_logo(fig2)
# -
Esempio n. 6
0
                     lambda_phi=lambda_phi)

# compute residuals and r-squared
u_rmlfp = x - alpha_rmlfp - z @ beta_rmlfp.T
r2_rmlfp = multi_r2(sig2_u_rmlfp, sig2_hat)
# -

# ## Plots

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

# Normal GLM
# compute ellipse grids
ell = plot_ellipse(np.zeros(2),
                   sig2_u_mlfp_norm[:2, :2],
                   r=2,
                   display_ellipse=False)

# limits in colorbars
minncov = np.min(sig2_u_mlfp_norm[:n_plot, :n_plot])
maxxcov = np.max(sig2_u_mlfp_norm[:n_plot, :n_plot])
minnbeta = np.min(beta_mlfp_norm[:n_plot, :])
maxxbeta = np.max(beta_mlfp_norm[:n_plot, :])

xlimu = [
    np.percentile(u_mlfp_norm[:, 0], 5),
    np.percentile(u_mlfp_norm[:, 0], 95)
]
ylimu = [
    np.percentile(u_mlfp_norm[:, 1], 5),
    np.percentile(u_mlfp_norm[:, 1], 95)
Esempio n. 7
0
r_theta = np.array([[np.cos(theta), -np.sin(theta)],
                    [np.sin(theta), np.cos(theta)]])  # rotation matrix
r = 2  # radius of ellipsoids
j_ = 5000  # number of scenarios

# ## [Step 1](https://www.arpm.co/lab/redirect.php?permalink=s_chebyshev_ineq-implementation-step01): Compute the square dispersion of the generic ellipsoid via rotation

s2 = r_theta @ sigma2 @ r_theta.T

# ## [Step 2](https://www.arpm.co/lab/redirect.php?permalink=s_chebyshev_ineq-implementation-step02): Perform computations for the plot

x = simulate_normal(mu, sigma2, j_)
x_ec = plot_ellipse(mu,
                    sigma2,
                    r=r,
                    display_ellipse=False,
                    plot_axes=True,
                    plot_tang_box=True,
                    color='orange')
x_g = plot_ellipse(m,
                   s2,
                   r=r,
                   display_ellipse=False,
                   plot_axes=True,
                   plot_tang_box=True,
                   color='b')

# ## Plots

# +
plt.style.use('arpm')
x = np.random.binomial(1, p, j_)
z_given_0 = np.random.multivariate_normal(mu_z_0, sig2_z_0, j_)
z_given_1 = np.random.multivariate_normal(mu_z_1, sig2_z_1, j_)

z = np.empty_like(z_given_0)
for j in range(j_):
    z[j] = (1 - x[j]) * z_given_0[j] + x[j] * z_given_1[j]

x_bar = np.empty_like(x)
for j in range(j_):
    x_bar[j] = chi(z[j])
# -

# ## [Step 5](https://www.arpm.co/lab/redirect.php?permalink=s_supervised_classification-implementation-step05): Generate mean/covariance ellipses

ellipse_0 = plot_ellipse(mu_z_0, sig2_z_0, r=2, display_ellipse=False)
ellipse_1 = plot_ellipse(mu_z_1, sig2_z_1, r=2, display_ellipse=False)

# ## Plots

# +
green = [0, 0.5, 0]
teal = [0.2344, 0.5820, 0.5664]
light_teal = [0.2773, 0.7031, 0.6836]
light_green_1 = [0.8398, 0.9141, 0.8125]
light_green_2 = [0.6, 0.8008, 0.5039]
grey = [0.5, 0.5, 0.5]
colf = [0, 0.5412, 0.9020]
darkgrey = [0.3, 0.3, 0.3]
color_multiplier = 0.6
x_colors = np.empty_like(x)
Esempio n. 9
0
# -

# ## Plots

# +
col_darkgrey = [.6, .6, .6]
col_orange = [.9, .6, 0]
col_reddishpurple = [.8, .6, .7]
col_skyblue = [.35, .7, .9]
spot = [0, 1]

plt.style.use('arpm')
fig = plt.figure(figsize=(10, 8))

plot_ellipse(mu_hat_r[spot],
             sig2_hat_r[np.ix_(spot, spot)],
             color=col_darkgrey,
             line_width=1.3)
plot_ellipse(mu_m_pril[spot],
             cv_pri_pred[np.ix_(spot, spot)],
             color='k',
             line_width=1.3)
plot_ellipse(mu_m_pos[spot],
             cv_pos_pred[np.ix_(spot, spot)],
             color='b',
             line_width=1.3)
plot_ellipse(mu_r_sure_bl[spot],
             sig2_r_sure_bl[np.ix_(spot, spot)],
             color=col_skyblue,
             line_width=2)
plot_ellipse(mu_r_mre[spot],
             0.98 * sig2_r_mre[np.ix_(spot, spot)],
Esempio n. 10
0
    np.percentile(epsi_25[:, 1], 5),
    np.percentile(epsi_25[:, 1], 95)
])
plt.xlabel('2yr rate daily changes')
plt.ylabel('5yr rate daily changes')
plt.ticklabel_format(style='sci', scilimits=(0, 0))

# Ellipsoids
mu_25 = mu[[1, 3]]  # select invariants expectations
mu_dl_25 = mu_dl[[1, 3]]
mu_trunc_25 = mu_trunc[[1, 3]]
s2_25 = s2[np.ix_([1, 3], [1, 3])]  # select invariants covariance
s2_dl_25 = s2_dl[np.ix_([1, 3], [1, 3])]
s2_trunc_25 = s2_trunc[np.ix_([1, 3], [1, 3])]

ell = plot_ellipse(mu_25, s2_25, color='b')
ell1 = plot_ellipse(mu_dl_25, s2_dl_25, color='tomato')
ell2 = plot_ellipse(mu_trunc_25, s2_trunc_25, color='g')

# legend
leg = plt.legend([
    'MLFP - complete series', 'MLFP - different len',
    'MLFP - truncated series', 'Dropped observations'
])

# bottom plot: highlight missing observations in the dataset as white spots
ax1 = plt.subplot2grid((4, 1), (3, 0))
plot_dates = np.array(y_db.dates)
na = np.ones(epsi.T.shape)
# na=1: not-available data (2y and 5y series are placed as last two entries)
na[-2:, :r] = 0
Esempio n. 11
0
sigma2 = np.array([[3, 1.5], [1.5, 1]])  # dispersion of the ellipsoid
j_ = 1000  # number of scenarios

# ## [Step 1](https://www.arpm.co/lab/redirect.php?permalink=s_simulate_unif_in_ellipse-implementation-step01): Generate scenarios

x, r, y = simulate_unif_in_ellips(mu, sigma2, j_)
ry = r * y

# ## Plots

# +
plt.style.use('arpm')
fig = plt.figure()

# Unit circle
unitcircle = plot_ellipse(np.zeros(2), np.eye(2), color='b', line_width=0.5)

# Ellipse(mu, sigma2)
ellipse, ellpoints, *_ = plot_ellipse(mu, sigma2, color='r', line_width=0.5)

# Plot scenarios of the uniform component Y
ply = plt.plot(y[:, 0],
               y[:, 1],
               markersize=3,
               markerfacecolor='b',
               marker='o',
               linestyle='none',
               label='$\mathbf{Y}$: uniform on the unit circle')

# Plot scenarios of the component RY
plry = plt.plot(ry[:, 0],
Esempio n. 12
0
# -

# ## [Step 2](https://www.arpm.co/lab/redirect.php?permalink=s_uncorr_no_indep-implementation-step02): Compute sample mean and covariance

# +
# sample expecation and covariance
e_xy, cv_xy = meancov_sp(np.c_[x, y])

cv_x_y = meancov_sp(np.c_[x, y])
# -

# ## [Step 3](https://www.arpm.co/lab/redirect.php?permalink=s_uncorr_no_indep-implementation-step03): Generate mean/covariance ellipse

# +
# points of expectation-covariance ellipsoid
ellipse = plot_ellipse(e_xy, cv_xy, r=1, display_ellipse=False)
# -

# ## Plots

# +
plt.style.use('arpm')
dark_grey = [100/256, 100/256, 100/256]
fig = plt.figure()
# ellipse and scatter
plt.plot(ellipse[:, 0], ellipse[:, 1], c='k', lw=1, label='Expactation/covariance ellipsoid')
plt.scatter(x, y, facecolor='none', color=dark_grey, label='Scatter plot')
# axes of ellipse
e, lambda2 = pca_cov(cv_xy)
diag_lambda = np.diagflat(np.sqrt(np.maximum(lambda2, 0)))
plt.plot([e_xy[0] - diag_lambda[0][0]*e[0][0], e_xy[0] + diag_lambda[0][0]*e[0][0]],
Esempio n. 13
0
# +
plt.style.use('arpm')

plot_dates = np.array(stocks.index)
cm, c = colormap_fp(p, None, None, np.arange(0, 0.81, 0.01), 0, 1, [0.6, 0.2])

fig, ax = plt.subplots(2, 1)

# scatter plot with MLFP ellipsoid superimposed
plt.sca(ax[0])
plt.scatter(epsi[:, 0], epsi[:, 1], 15, c=c, marker='.', cmap=cm)
plt.axis('equal')
plt.xlim(np.percentile(epsi[:, 0], 100 * np.array([0.01, 0.99])))
plt.ylim(np.percentile(epsi[:, 1], 100 * np.array([0.01, 0.99])))
plt.xlabel('$\epsilon_1$')
plt.ylabel('$\epsilon_2$')
plot_ellipse(mu_mlfp, sig2_mlfp, color='r')
plt.legend(['MLFP ellipsoid'])
plt.title('MLFP ellipsoid of Student t GARCH(1,1) residuals')

# Flexible probabilities profile
plt.sca(ax[1])
plt.bar(plot_dates[1:], p, color='gray', width=1)
plt.yticks([])
plt.ylabel('$p_t$')
ens_plot = 'Eff. num. of scenarios =  % 3.0f' % ens
plt.title('Exponential decay flexible probabilities.  ' + ens_plot)
add_logo(fig, axis=ax[0])
plt.tight_layout()