# Real-Time Risk (`risk_rt`)

This folder contains the real-time inflation-risk estimation, density decomposition exercises, and the comparison with structural oil-market shocks (Main Paper & Online Appendix).

---

## Running for All Inflation Aggregates

All risk scripts are configured by default for **Core PCE (excl. food & energy)** but can be run for any of the four aggregates. Pre-processed data files for all four aggregates are included in `data/`:

| Aggregate | Data file |
|---|---|
| Core PCE (excl. food & energy) | `data_for_server_20250429_risk_PCEx.mat` *(default)* |
| Headline PCE | `data_for_server_20250429_risk_PCE.mat` |
| Core CPI (excl. food & energy) | `data_for_server_20250429_risk_CPIx.mat` |
| Headline CPI | `data_for_server_20250429_risk_CPI.mat` |

To switch aggregates, change the `load(...)` statement and the `meas` string variable at the top of each script. Output file names, figures, and decomposition labels adapt automatically.

---

## Main Scripts & Execution Order

### 0. `download_Baumeister_shocks.m` *(optional — pre-cached data included)*

| Aspect | Detail |
|---|---|
| **Downloads** | Baumeister & Hamilton oil supply and demand shock series from Google Drive |
| **Saves** | `data/BH_shocks.mat` (already included in the repo) |
| **Note** | Only re-run if you need the latest vintage of the shock series |

### 1. Miranda-Agrippino Monetary Policy Shock Update *(optional — pre-cached data included)*

See the dedicated section below. The updated shocks (`shocksnew.mat`) are used as the monetary policy indicator in the risk decompositions.

### 2. `risk_measures_RT_annualized_rate_unstan_h4.m` — 4-Quarter-Ahead Risk

| Aspect | Detail |
|---|---|
| **Loads** | `data/data_for_server_20250429_risk_PCEx.mat` |
| **Method** | Expanding-window estimation (50 % burn-in). Three models per vintage: **(1)** Bayesian DR, **(2)** QR Mitchell, **(3)** UC-SV. Full model outputs stored in `res` struct. Decompositions use clamped background data (`clampid = 80`). |
| **Saves** | `results/results_realtime_decompositions_h4_PCEx.mat`, ``,  |
| **Then runs** | SHAP-based density decomposition for selected target quarters (2021Q1, 2022Q4) with grouped features |
| **Saves** | `results/density_decomposition_h4_PCEx_random_clamped_1.mat` |
| **Then runs** | SHAP-based loss decomposition for balance-of-risk measures |
| **Saves** | `results/loss_decomposition_h4_clamped_1_PCEx_22_random_.mat` |
| **Generates** | Corresponding h=4 density decomposition, loss decomposition, balance-of-risk, and density estimate figures (`Main_Figure1_*`, `Main_Figure3_*`, `Main_Figure4_*`, `Main_Figure5_*`, `OS_Figure11_*`) |

### 3. `risk_measures_RT_annualized_rate_unstan_h1.m` — 1-Quarter-Ahead Risk

| Aspect | Detail |
|---|---|
| **Loads** | `data/data_for_server_20250429_risk_PCEx.mat` (swap for other aggregates) |
| **Method** | Expanding-window estimation (50 % burn-in). Three models per vintage: **(1)** Bayesian DR, **(2)** QR Mitchell, **(3)** UC-SV. Full model outputs stored in `res` struct. Decompositions use clamped background data (`clampid = 80`). |
| **Saves** | `results/results_realtime_decompositions_h1_PCEx.mat` — complete estimation output |
| **Then runs** | SHAP-based density decomposition for selected target quarters (2021Q1, 2022Q4) with grouped features |
| **Saves** | `results/density_decomposition_h1_PCEx_random_clamped_1.mat` |
| **Then runs** | SHAP-based loss decomposition for balance-of-risk measures |
| **Saves** | `results/loss_decomposition_h1_clamped_1_PCEx_22_random_.mat` |
| **Generates** | Density decomposition bar charts (`shap_dens_decomposition_plot_*.{pdf,eps}`), loss decomposition bar charts (`shap_decomposition_loss_plot_*.{pdf,eps}`), balance-of-risk time series (`OS_Figure4_RMchart_*.{pdf,eps}`), and risk-neutral risk measure charts (`RMchart_RiskNeutral_*.{pdf,eps}`) |

Most of these results are not reported in the paper, which focuses on h=4.

### 4. `Compare_BH_shocks.m` — Oil Shock Comparison (Main Paper, Figure 6)

| Aspect | Detail |
|---|---|
| **Loads** | `data/BH_shocks.mat` (Baumeister & Hamilton shock series); `results/loss_decomposition_for_BH_comparison.mat` (pre-computed loss decompositions with energy-specific grouping) |
| **Processing** | Correlates SHAP-based commodity-price risk contributions (from DR and QR) with structural oil supply/demand shocks; fits scatter regressions |
| **Generates** | `Main_Figure6_scatter_comparison_oil_DR.{pdf,eps}`, `Main_Figure6_scatter_comparison_oil_QR.{pdf,eps}`, `Main_Figure6_scatter_comparison_activity_DR.{pdf,eps}`, `Main_Figure6_scatter_comparison_activity_QR.{pdf,eps}` |

---

## Miranda-Agrippino Monetary Policy Shock Update

The monetary policy shock series used in the risk decompositions is based on Miranda-Agrippino (2016) and was **updated using the code in `miranda_aggripino_ricco/`**.

### Folder structure

```
miranda_aggripino_ricco/
├── adjusted/                         ← Modified code with extended sample
│   ├── MAIN_SVARIV_proxySVAR.m       ← Updated main script (sample extended to 2025M3)
│   ├── MAIN_SVARIV_proxySVAR_old.m   ← Previous version for reference
│   ├── CRBI_constructed_new.xlsx     ← Updated commodity price index data
│   ├── datafolder/                   ← Updated FRED-MD and instrument data
│   ├── subroutines/                  ← VAR estimation and identification subroutines
│   ├── shocksnew.mat                 ← OUTPUT: quarterly-aggregated GK and MAR shocks
│   ├── IRFs_6914.{mat,pdf}           ← IRFs for 1969M1–2014M12
│   ├── IRFs_6919.{mat,pdf}           ← IRFs for 1969M1–2019M12
│   └── IRFs_6925.{mat,pdf}           ← IRFs for 1969M1–2025M3 (extended)
└── miranda_aggripino_ricco_RAW/      ← Original unmodified replication code
    ├── MAIN_SVARIV_proxySVAR.m       ← Original script (sample ends 2019M12)
    ├── datafolder/
    ├── subroutines/
    └── IRFs_6914.{mat,pdf}
```

### Key changes in the adjusted version

| Change | Detail |
|---|---|
| **Sample extension** | `dataSetSpec.endSetFull` extended from 2019M12 to **2025M3** |
| **New data field** | Added `dataSetSpec.beginSetFull` and `dataSetSpec.endSetFull` to allow full-sample shock extraction beyond the VAR estimation window |
| **Updated commodity index** | `CRBI_constructed_new.xlsx` provides extended commodity price data |
| **Shock export** | The adjusted script aggregates the monthly structural shocks (Gertler–Karadi and Miranda-Agrippino orthogonal proxy) to **quarterly frequency** and saves them as `shocksnew.mat` — this file is then loaded by the risk application via the `data/` folder |
| **Multiple sample windows** | Pre-computed IRF outputs are provided for three sample endpoints: 2014, 2019, and 2025 |

The original, unmodified Miranda-Agrippino code is preserved in `miranda_aggripino_ricco_RAW/` so users can verify the changes.

---

## Data Files (`data/`)

| File | Description |
|---|---|
| `data_for_server_20250429_risk_PCEx.mat` | Core PCE excl. food & energy, risk-application version |
| `data_for_server_20250429_risk_PCE.mat` | Headline PCE variant |
| `data_for_server_20250429_risk_CPI.mat` | Headline CPI variant |
| `data_for_server_20250429_risk_CPIx.mat` | Core CPI variant |
| `BH_shocks.mat` | Baumeister & Hamilton oil supply/demand shocks |
| `BH2_supply_shocks.xlsx` | Raw supply shock data |
| `shocks.mat` | Additional structural shock series |
| `FREDQD_new.xlsx` | FRED-QD quarterly database |
| `data.xlsx`, `indices.xlsx` | Raw series and commodity/financial indices |
| `frbsf_pce.csv` | FRBSF PCE data (placeholder) |
| `mydata.xlsx` | Intermediate download from Baumeister website |
| `load_data.m` | Helper to reconstruct `.mat` from raw sources |
| `viridis.m` | Viridis colormap for MATLAB figures |

---

## Feature Grouping for Decompositions

The 13 predictor columns (4 lags + 8 indicators + constant) are grouped as follows for interpretability:

| Group ID | Label | Predictor columns |
|---|---|---|
| 1 | Dynamic Persistence | Lags 1–4 |
| 2 | Domestic Business Cycle | Domestic Business Cycle Factor |
| 3 | Global Business Cycle | OECD Industrial Production |
| 4 | Commodity Prices | Energy, Food, Metals |
| 5 | Financial Conditions | EBP  |
| 6 | Monetary Policy |  DFF / MARn |
| 7 | Inflation Expectations | SPF linked 1-year expectations + PTR long-run inflation expectations |

---

## Key Estimation Settings

| Parameter | Value | Meaning |
|---|---|---|
| `H_max` | 5 | Max mixture components |
| `init_method` | `'cluster'` | K-means initialisation |
| `prior_mixing` | 2 | Horseshoe prior |
| `prior_kernel` | 0 | Normal prior |
| `max_iter` | 10 000 | Max VB iterations |
| `tol` | 1e-6 | Convergence tolerance |
| `R` | 1 000 | Posterior simulation draws |
| `M` | 1 000 | Decomposition draws |

---

## Active Local Dependencies (`functions/`)

- Core estimators: `VB_BDR_pipe`, `VBTVPQR`, `VB_DVS`
- Distribution helpers: `QuantilesInterpolation`, `QR1_adjusted`, `rskt`, `pskt`, `dskt`, `qskt`, `pmskt`
- Decomposition: `shap_dens_comp3`, `shap_loss_comp3`
- Loss functions: `f_loss_DR`, `f_loss_QR`, `f_loss_TVPSV`
- Density functions: `f_DR`, `f_QR3`, `f_QR3_illust`, `f_TVPSV`
- Shared utilities: `f_simul_VB`, `shade`
- External: `miranda_aggripino_ricco/adjusted/` (updated monetary policy shock identification)

---

## Computational Notes

- **Individual scripts run efficiently** thanks to the variational Bayes implementation. The core estimation loop in each risk script (h=1 or h=4) for a single aggregate completes in **15–30 minutes** on a modern workstation.
- **The SHAP-based decompositions** (density and loss) are the most time-consuming part of each script, adding roughly **30–60 minutes** depending on the number of target vintages, the background data size, and whether clamping is used.
- **`Compare_BH_shocks.m`** is fast (< 5 minutes).
- **Total replication time** for the full risk application across both horizons and all four aggregates amounts to **several hours**.
- **Parallelism:** Several loops use `parfor`. The Parallel Computing Toolbox is recommended but not required.
- **Memory:** 16 GB+ RAM recommended — the `res` struct stores full model output for every evaluation period.
- All scripts can be re-run for the three other inflation aggregates by swapping the `load(...)` call and updating `meas`. Pre-processed data for all four aggregates is included.
