Forecasting out-of-sample discrete_markov_chain.ipynb

Plotting code:

def shade_background(ppc, ax, var_name, x_grid, palette="cividis", hdi_min=0.5, hdi_max=0.99, color_grid_size=100):
    palette = palette
    cmap = plt.get_cmap(palette)
    hdi_probs = np.linspace(hdi_min, hdi_max, color_grid_size)[::-1]
    probs_scaled = (hdi_probs - hdi_min) / (hdi_max - hdi_min)
    colors = map(cmap, probs_scaled)
    
    for color_val, hdi_prob in zip(colors, hdi_probs):
        hdi = az.hdi(ppc.posterior_predictive[var_name], hdi_prob=hdi_prob)[var_name]
        ax.fill_between(x_grid, *hdi.values.T, color=color_val, alpha=0.25, 
        )

fig, ax = plt.subplots(figsize=(14, 4), dpi=144)
[spine.set_visible(False) for spine in ax.spines.values()]
ax.grid(ls='--', lw=0.5, zorder=0)

ax.plot(dta_hamilton.index, dta_hamilton.values)
shade_background(idata_forecast, ax, 'forecast', coords['forecast_dates'], palette='Reds_r')
forecast_mu = idata_forecast.posterior_predictive.forecast.mean(dim=['chain', 'draw'])
ax.plot(coords['forecast_dates'], forecast_mu, ls='--', c='k', lw=2)
fig.set_facecolor('w')
plt.show()

There was actually an error in the code that made the graph I posted, so here’s a corrected output:

1 Like