VAR and VECM: several series together
Forecast several series from each other's past, trace how a shock spreads, and add long-run relationships when the series are cointegrated.
What runs in CodeSplash
- VAR / VECM Verified in Python and R
You will be able to
- Describe a VAR and choose its lag order
- Read an impulse response and a forecast error variance decomposition, and say what they assume
- Decide between a VAR in levels, a VAR in differences and a VECM
Everyone predicts everyone
ReadA vector autoregressionVector autoregressionEach series is regressed on the lags of all the series, so they forecast each other. The lag order is chosen by an information criterion. treats each series as an outcome, explained by the lags of all of them:
There is no "dependent variable" to pick, and each extra lag adds coefficients. With three series and four lags, that's 36, plus the constants.
Choose the lag order
PredictPredict first
Lag order offers several criteria, including AIC and Schwarz (BIC). Which picks larger models?
Reveal
AIC tends to pick more lags, since its penalty is lighter. On this simulated data, AIC picks 2. The largest root has a modulus of 0.65. Below 1 means the VAR is stable, so shocks fade. The portmanteau check on residuals gives p = .458: little sign of leftover dependence.
Read the card
In the appVAR(2): 6-step forecasts of y1 (monthly data, 240 observations). Backtest MAE 1.33 over 2 origins.
- MAE
- 1.329
- RMSE
- 1.580
- MAPE
- 0.4174
Plots
View data
| hi_80 | hi_95 | kind | lo_80 | lo_95 | month | y1 |
|---|---|---|---|---|---|---|
| — | — | actual | — | — | 946,684,800,000 | 1.490 |
| — | — | actual | — | — | 949,363,200,000 | 0.4667 |
| — | — | actual | — | — | 951,868,800,000 | −0.7308 |
| — | — | actual | — | — | 954,547,200,000 | 0.5103 |
| — | — | actual | — | — | 957,139,200,000 | 1.109 |
| — | — | actual | — | — | 959,817,600,000 | 0.5950 |
| — | — | actual | — | — | 962,409,600,000 | 1.229 |
| — | — | actual | — | — | 965,088,000,000 | 3.016 |
| — | — | actual | — | — | 967,766,400,000 | 2.634 |
| — | — | actual | — | — | 970,358,400,000 | −0.2967 |
| — | — | actual | — | — | 973,036,800,000 | −0.1389 |
| — | — | actual | — | — | 975,628,800,000 | 0.3949 |
| — | — | actual | — | — | 978,307,200,000 | 1.686 |
| — | — | actual | — | — | 980,985,600,000 | 3.459 |
| — | — | actual | — | — | 983,404,800,000 | 2.717 |
| — | — | actual | — | — | 986,083,200,000 | 1.220 |
| — | — | actual | — | — | 988,675,200,000 | 1.473 |
| — | — | actual | — | — | 991,353,600,000 | 0.6684 |
| — | — | actual | — | — | 993,945,600,000 | −0.1410 |
| — | — | actual | — | — | 996,624,000,000 | −0.6870 |
| — | — | actual | — | — | 999,302,400,000 | −0.3557 |
| — | — | actual | — | — | 1,001,894,400,000 | 1.117 |
| — | — | actual | — | — | 1,004,572,800,000 | −0.3429 |
| — | — | actual | — | — | 1,007,164,800,000 | 1.032 |
| — | — | actual | — | — | 1,009,843,200,000 | 3.144 |
| — | — | actual | — | — | 1,012,521,600,000 | 1.903 |
| — | — | actual | — | — | 1,014,940,800,000 | 2.239 |
| — | — | actual | — | — | 1,017,619,200,000 | 2.363 |
| — | — | actual | — | — | 1,020,211,200,000 | 2.291 |
| — | — | actual | — | — | 1,022,889,600,000 | 2.483 |
| — | — | actual | — | — | 1,025,481,600,000 | 1.154 |
| — | — | actual | — | — | 1,028,160,000,000 | 1.490 |
| — | — | actual | — | — | 1,030,838,400,000 | 2.713 |
| — | — | actual | — | — | 1,033,430,400,000 | 4.160 |
| — | — | actual | — | — | 1,036,108,800,000 | 3.233 |
| — | — | actual | — | — | 1,038,700,800,000 | 2.103 |
| — | — | actual | — | — | 1,041,379,200,000 | 2.278 |
| — | — | actual | — | — | 1,044,057,600,000 | 0.4014 |
| — | — | actual | — | — | 1,046,476,800,000 | −1.533 |
| — | — | actual | — | — | 1,049,155,200,000 | 0.6342 |
| — | — | actual | — | — | 1,051,747,200,000 | 2.731 |
| — | — | actual | — | — | 1,054,425,600,000 | 1.632 |
| — | — | actual | — | — | 1,057,017,600,000 | −0.8263 |
| — | — | actual | — | — | 1,059,696,000,000 | 0.7748 |
| — | — | actual | — | — | 1,062,374,400,000 | 0.4315 |
| — | — | actual | — | — | 1,064,966,400,000 | 2.176 |
| — | — | actual | — | — | 1,067,644,800,000 | 2.361 |
| — | — | actual | — | — | 1,070,236,800,000 | 4.135 |
| — | — | actual | — | — | 1,072,915,200,000 | 2.901 |
| — | — | actual | — | — | 1,075,593,600,000 | 0.4129 |
| — | — | actual | — | — | 1,078,099,200,000 | 3.961 |
| — | — | actual | — | — | 1,080,777,600,000 | 1.131 |
| — | — | actual | — | — | 1,083,369,600,000 | 0.7565 |
| — | — | actual | — | — | 1,086,048,000,000 | 0.3064 |
| — | — | actual | — | — | 1,088,640,000,000 | 3.654 |
| — | — | actual | — | — | 1,091,318,400,000 | 3.362 |
| — | — | actual | — | — | 1,093,996,800,000 | 1.992 |
| — | — | actual | — | — | 1,096,588,800,000 | 4.333 |
| — | — | actual | — | — | 1,099,267,200,000 | 2.406 |
| — | — | actual | — | — | 1,101,859,200,000 | −0.4051 |
First 60 of 246 rows.
View data
| error | horizon | origin |
|---|---|---|
| 1.310 | 1 | 2018-12-01 |
| 0.4401 | 2 | 2018-12-01 |
| 1.489 | 3 | 2018-12-01 |
| 2.099 | 4 | 2018-12-01 |
| 1.054 | 5 | 2018-12-01 |
| 1.202 | 6 | 2018-12-01 |
| −0.3094 | 1 | 2019-06-01 |
| 1.819 | 2 | 2019-06-01 |
| 0.7921 | 3 | 2019-06-01 |
| 0.2739 | 4 | 2019-06-01 |
| 1.726 | 5 | 2019-06-01 |
| 3.431 | 6 | 2019-06-01 |
View data
| ACF | bound | lag |
|---|---|---|
| 0.0036 | 0.1270 | 1 |
| 0.0238 | 0.1270 | 2 |
| −0.0290 | 0.1270 | 3 |
| 0.0584 | 0.1270 | 4 |
| 0.0064 | 0.1270 | 5 |
| −0.0627 | 0.1270 | 6 |
| 0.1212 | 0.1270 | 7 |
| −0.0087 | 0.1270 | 8 |
| −0.0539 | 0.1270 | 9 |
| −0.0366 | 0.1270 | 10 |
| 0.1084 | 0.1270 | 11 |
| 0.0066 | 0.1270 | 12 |
| 0.0663 | 0.1270 | 13 |
| −0.0001 | 0.1270 | 14 |
| 0.0186 | 0.1270 | 15 |
| −0.0547 | 0.1270 | 16 |
| 0.0031 | 0.1270 | 17 |
| 0.1256 | 0.1270 | 18 |
| −0.0705 | 0.1270 | 19 |
| 0.0677 | 0.1270 | 20 |
| 0.0760 | 0.1270 | 21 |
| 0.0298 | 0.1270 | 22 |
| −0.0077 | 0.1270 | 23 |
| 0.0300 | 0.1270 | 24 |
View data
| steps | high | low | responding series | shock | response |
|---|---|---|---|---|---|
| 0 | 1.203 | 1.051 | y1 | y1 | 1.143 |
| 0 | 0 | 0 | y1 | y2 | 0 |
| 0 | 0 | 0 | y1 | y3 | 0 |
| 0 | 0.5309 | 0.3343 | y2 | y1 | 0.4454 |
| 0 | 0.9204 | 0.7947 | y2 | y2 | 0.8640 |
| 0 | 0 | 0 | y2 | y3 | 0 |
| 0 | 0.2536 | 0.0930 | y3 | y1 | 0.1765 |
| 0 | 0.3352 | 0.1784 | y3 | y2 | 0.2670 |
| 0 | 0.8283 | 0.7170 | y3 | y3 | 0.7847 |
| 1 | 0.7391 | 0.5360 | y1 | y1 | 0.6506 |
| 1 | 0.2070 | −0.0032 | y1 | y2 | 0.0810 |
| 1 | −0.0131 | −0.1937 | y1 | y3 | −0.1031 |
| 1 | 0.6250 | 0.3969 | y2 | y1 | 0.5260 |
| 1 | 0.4499 | 0.2484 | y2 | y2 | 0.3642 |
| 1 | 0.0799 | −0.0876 | y2 | y3 | 0.0072 |
| 1 | 0.2075 | 0.0465 | y3 | y1 | 0.1273 |
| 1 | 0.1949 | 0.0471 | y3 | y2 | 0.1350 |
| 1 | 0.2860 | 0.1508 | y3 | y3 | 0.2273 |
| 2 | 0.3054 | 0.0993 | y1 | y1 | 0.2094 |
| 2 | 0.2862 | 0.0488 | y1 | y2 | 0.1620 |
| 2 | 0.0809 | −0.1427 | y1 | y3 | −0.0321 |
| 2 | 0.4627 | 0.2271 | y2 | y1 | 0.3674 |
| 2 | 0.2355 | 0.0186 | y2 | y2 | 0.1390 |
| 2 | 0.0888 | −0.0933 | y2 | y3 | 0.0221 |
| 2 | 0.2687 | 0.1032 | y3 | y1 | 0.1988 |
| 2 | 0.1955 | 0.0341 | y3 | y2 | 0.1156 |
| 2 | 0.3123 | 0.1397 | y3 | y3 | 0.2190 |
| 3 | 0.1407 | −0.0803 | y1 | y1 | 0.0489 |
| 3 | 0.2237 | 0.0037 | y1 | y2 | 0.1117 |
| 3 | 0.0821 | −0.1001 | y1 | y3 | −0.0056 |
| 3 | 0.2545 | 0.0265 | y2 | y1 | 0.1755 |
| 3 | 0.1777 | 0.0127 | y2 | y2 | 0.0902 |
| 3 | 0.0841 | −0.0657 | y2 | y3 | 0.0177 |
| 3 | 0.2157 | 0.0718 | y3 | y1 | 0.1517 |
| 3 | 0.1298 | 0.0316 | y3 | y2 | 0.0792 |
| 3 | 0.1780 | 0.0435 | y3 | y3 | 0.1029 |
| 4 | 0.0973 | −0.0710 | y1 | y1 | 0.0285 |
| 4 | 0.1006 | −0.0226 | y1 | y2 | 0.0463 |
| 4 | 0.0731 | −0.0571 | y1 | y3 | 0.0090 |
| 4 | 0.1454 | −0.0387 | y2 | y1 | 0.0728 |
| 4 | 0.1265 | 0.0024 | y2 | y2 | 0.0656 |
| 4 | 0.0726 | −0.0487 | y2 | y3 | 0.0194 |
| 4 | 0.1678 | 0.0437 | y3 | y1 | 0.1079 |
| 4 | 0.1035 | 0.0282 | y3 | y2 | 0.0655 |
| 4 | 0.1521 | 0.0125 | y3 | y3 | 0.0726 |
| 5 | 0.0847 | −0.0452 | y1 | y1 | 0.0248 |
| 5 | 0.0521 | −0.0197 | y1 | y2 | 0.0140 |
| 5 | 0.0432 | −0.0330 | y1 | y3 | 0.0073 |
| 5 | 0.0906 | −0.0258 | y2 | y1 | 0.0367 |
| 5 | 0.0813 | −0.0017 | y2 | y2 | 0.0380 |
| 5 | 0.0570 | −0.0306 | y2 | y3 | 0.0167 |
| 5 | 0.1103 | 0.0218 | y3 | y1 | 0.0696 |
| 5 | 0.0744 | 0.0170 | y3 | y2 | 0.0472 |
| 5 | 0.1010 | −5.391e-5 | y3 | y3 | 0.0428 |
| 6 | 0.0579 | −0.0167 | y1 | y1 | 0.0161 |
| 6 | 0.0374 | −0.0107 | y1 | y2 | 0.0063 |
| 6 | 0.0299 | −0.0231 | y1 | y3 | 0.0050 |
| 6 | 0.0650 | −0.0135 | y2 | y1 | 0.0245 |
| 6 | 0.0460 | −0.0031 | y2 | y2 | 0.0191 |
| 6 | 0.0429 | −0.0199 | y2 | y3 | 0.0125 |
First 60 of 117 rows.
View data
| steps ahead | responding series | shock | share |
|---|---|---|---|
| 1 | y1 | y1 | 1 |
| 1 | y1 | y2 | 0 |
| 1 | y1 | y3 | 0 |
| 1 | y2 | y1 | 0.2099 |
| 1 | y2 | y2 | 0.7901 |
| 1 | y2 | y3 | 0 |
| 1 | y3 | y1 | 0.0434 |
| 1 | y3 | y2 | 0.0993 |
| 1 | y3 | y3 | 0.8574 |
| 2 | y1 | y1 | 0.9902 |
| 2 | y1 | y2 | 0.0038 |
| 2 | y1 | y3 | 0.0061 |
| 2 | y2 | y1 | 0.3508 |
| 2 | y2 | y2 | 0.6492 |
| 2 | y2 | y3 | 3.800e-5 |
| 2 | y3 | y1 | 0.0589 |
| 2 | y3 | y2 | 0.1113 |
| 2 | y3 | y3 | 0.8298 |
| 3 | y1 | y1 | 0.9755 |
| 3 | y1 | y2 | 0.0180 |
| 3 | y1 | y3 | 0.0064 |
| 3 | y2 | y1 | 0.4043 |
| 3 | y2 | y2 | 0.5954 |
| 3 | y2 | y3 | 0.0004 |
| 3 | y3 | y1 | 0.0960 |
| 3 | y3 | y2 | 0.1137 |
| 3 | y3 | y3 | 0.7903 |
| 4 | y1 | y1 | 0.9689 |
| 4 | y1 | y2 | 0.0247 |
| 4 | y1 | y3 | 0.0064 |
| 4 | y2 | y1 | 0.4139 |
| 4 | y2 | y2 | 0.5855 |
| 4 | y2 | y3 | 0.0006 |
| 4 | y3 | y1 | 0.1163 |
| 4 | y3 | y2 | 0.1155 |
| 4 | y3 | y3 | 0.7682 |
| 5 | y1 | y1 | 0.9678 |
| 5 | y1 | y2 | 0.0258 |
| 5 | y1 | y3 | 0.0064 |
| 5 | y2 | y1 | 0.4147 |
| 5 | y2 | y2 | 0.5845 |
| 5 | y2 | y3 | 0.0008 |
| 5 | y3 | y1 | 0.1258 |
| 5 | y3 | y2 | 0.1174 |
| 5 | y3 | y3 | 0.7568 |
| 6 | y1 | y1 | 0.9676 |
| 6 | y1 | y2 | 0.0259 |
| 6 | y1 | y3 | 0.0064 |
| 6 | y2 | y1 | 0.4147 |
| 6 | y2 | y2 | 0.5843 |
| 6 | y2 | y3 | 0.0010 |
| 6 | y3 | y1 | 0.1296 |
| 6 | y3 | y2 | 0.1186 |
| 6 | y3 | y3 | 0.7518 |
| 7 | y1 | y1 | 0.9676 |
| 7 | y1 | y2 | 0.0259 |
| 7 | y1 | y3 | 0.0065 |
| 7 | y2 | y1 | 0.4148 |
| 7 | y2 | y2 | 0.5841 |
| 7 | y2 | y3 | 0.0011 |
First 60 of 117 rows.
Assumptions
- The system is stable — Largest root modulus 0.652.
- Residuals look uncorrelated — Adjusted portmanteau at 10 lags: p = 0.458.
Backtest accuracy (2 origins, horizon 6)
| Metric | Value |
|---|---|
| MAE | 1.329 |
| RMSE | 1.580 |
| MAPE | 0.4174 |
| sMAPE | 0.5513 |
| MASE | 0.9367 |
| WAPE | 0.4614 |
| Coverage of the 80% interval | 0.6667 |
| Coverage of the 95% interval | 0.9167 |
Lag order (lower is better)
| Lags | AIC | HQ | SC | FPE |
|---|---|---|---|---|
| 1 | −0.3640 | −0.2921 | −0.1857 | 0.6949 |
| 2 | −0.3960 | −0.2702 | −0.0840 | 0.6730 |
| 3 | −0.3694 | −0.1897 | 0.0763 | 0.6913 |
| 4 | −0.3188 | −0.0852 | 0.2606 | 0.7272 |
| 5 | −0.3003 | −0.0127 | 0.4128 | 0.7411 |
| 6 | −0.2463 | 0.0952 | 0.6006 | 0.7826 |
| 7 | −0.2068 | 0.1886 | 0.7737 | 0.8146 |
| 8 | −0.2043 | 0.2450 | 0.9099 | 0.8172 |
What drives the forecast error of y1
| Steps ahead | y1 | y2 | y3 |
|---|---|---|---|
| 1 | 1 | 0 | 0 |
| 2 | 0.9902 | 0.0038 | 0.0061 |
| 4 | 0.9689 | 0.0247 | 0.0064 |
| 6 | 0.9676 | 0.0259 | 0.0064 |
| 8 | 0.9676 | 0.0259 | 0.0065 |
| 12 | 0.9676 | 0.0259 | 0.0065 |
| 13 | 0.9676 | 0.0259 | 0.0065 |
Forecasts of the other series
| Series | Steps ahead | Forecast | SE |
|---|---|---|---|
| y2 | 1 | 3.438 | 0.9721 |
| y2 | 2 | 2.662 | 1.164 |
| y2 | 3 | 2.051 | 1.228 |
| y2 | 4 | 1.746 | 1.244 |
| y2 | 5 | 1.620 | 1.248 |
| y2 | 6 | 1.561 | 1.250 |
| y3 | 1 | 0.8958 | 0.8474 |
| y3 | 2 | 0.8147 | 0.8968 |
| y3 | 3 | 0.5316 | 0.9514 |
| y3 | 4 | 0.3142 | 0.9721 |
| y3 | 5 | 0.1498 | 0.9830 |
| y3 | 6 | 0.0446 | 0.9875 |
Do one series' lags help predict another? (predictive, not causal)
| Lags of | Predicting | F | df | p |
|---|---|---|---|---|
| y2 | y1 | 2.272 | 231 | 0.1054 |
| y3 | y1 | 1.025 | 231 | 0.3605 |
| y1 | y2 | 11.928 | 231 | 1.175e-5 |
| y3 | y2 | 0.3823 | 231 | 0.6827 |
| y1 | y3 | 1.174 | 231 | 0.3108 |
| y2 | y3 | 0.5356 | 231 | 0.5860 |
Forecast
| month | Forecast | 80% low | 80% high | 95% low | 95% high |
|---|---|---|---|---|---|
| 2020-01-01 | 3.338 | 1.873 | 4.803 | 1.097 | 5.578 |
| 2020-02-01 | 2.219 | 0.5252 | 3.913 | −0.3715 | 4.810 |
| 2020-03-01 | 1.815 | 0.0870 | 3.543 | −0.8277 | 4.458 |
| 2020-04-01 | 1.722 | −0.0133 | 3.457 | −0.9318 | 4.375 |
| 2020-05-01 | 1.677 | −0.0599 | 3.413 | −0.9792 | 4.332 |
| 2020-06-01 | 1.638 | −0.0992 | 3.375 | −1.019 | 4.294 |
The exact R script · R R version 4.5.1 (2025-06-13)
# VAR / VECM
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.var 1.0.0 · spec 1f4b7a8e32837d9f
# Dataset: f7_var_sim (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
TIME <- "month"
VALUE <- "y1"
SERIES <- NULL
H <- 6
LEVELS <- as.numeric(c(80, 95))
SEASON <- NULL # NULL = from the time steps (12 monthly, 4 quarterly, 7 daily …)
WINDOWS <- 2
STEP <- NULL # NULL = the horizon
OFFSETS <- NULL # the host's BacktestPlan: distance of each origin from the end of the series; NULL = windows and step
TRAIN_WINDOW <- NULL # NULL = train on all values before each origin
TRAIN_START <- NULL # rows before this time are left out (for example, before a structural break)
SEED <- 42
XREG <- c("y2", "y3")
PARAMS <- list(
model = "var",
lag_select = "aic",
lags = 2,
max_lags = 8,
deterministic = "const",
seasonal_dummies = FALSE,
rank = NULL,
irf_horizon = 12,
irf_boot = 50,
irf_level = 90
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/f7_var_sim.parquet", col_select = unique(c(TIME, VALUE, SERIES, XREG))))
cs_check_finite_columns(df, c(TIME, VALUE, XREG)) # infinite values stop with CS_E_NOT_FINITE, naming the column
if (nrow(df) == 0) cs_error("CS_E_NO_ROWS")
warnings <- list()
td <- cs_ml_fc_to_days(df[[TIME]])
times_all <- td$values
TEMPORAL <- td$temporal
values_all <- suppressWarnings(as.numeric(df[[VALUE]]))
x_all <- if (length(XREG)) do.call(cbind, lapply(XREG, function(c) suppressWarnings(as.numeric(df[[c]])))) else NULL
n_early <- 0L
if (!is.null(TRAIN_START)) {
cut <- cs_ml_fc_parse_time(TRAIN_START, TEMPORAL)
early <- !is.na(times_all) & times_all < cut
n_early <- sum(early)
if (n_early > 0) {
warnings <- c(warnings, sprintf("%d rows before %s were left out of training.", n_early, as.character(TRAIN_START)))
times_all[early] <- NA
}
}
keys_all <- if (!is.null(SERIES)) as.character(df[[SERIES]]) else rep(NA_character_, nrow(df))
dropped <- sum(is.na(times_all)) - n_early
if (dropped > 0) warnings <- c(warnings, sprintf("%d rows without a time were left out.", dropped))
series_keys <- if (!is.null(SERIES)) sort(unique(keys_all[!is.na(keys_all)]), method = "radix") else list(NULL)
if (!is.null(SERIES) && anyNA(keys_all)) warnings <- c(warnings, "Rows without a series name were left out.")
# Degenerate inputs stop with catalog codes, in the same order as the Python driver.
if (all(is.na(values_all))) cs_error("CS_E_ALL_MISSING", column = VALUE)
if (!any(!is.na(times_all) & !is.na(values_all))) cs_error("CS_E_NO_ROWS")
out <- cs_ml_out_dir("target/academy-parity/run-8142/forecast.var/sim_var_aic/out-r")
extra_tables <- list() # model blocks may add result tables (assign with <<-)
extra_assumptions <- list() # … and assumption rows
current_series <- NULL
X_TRAIN <- NULL # regressors while fit_forecast runs: rows × regressors, aligned with its y
X_FUTURE <- NULL # … and h × regressors for the steps it forecasts
# Model blocks may set DIAG[[current_series, or "_"]] <<- list(resid = ..., fitdf = k, lags = L) from each fit (the final fit's
# entry is kept): the residuals their own check tests when that is not actual − fitted (GARCH: standardized; ARIMAX:
# the ARMA errors), the ARMA terms they were filtered with, and the Ljung–Box lags when the method's rule differs from
# min(2m, n/5). They go to forecast.parquet so the host's Residuals tab tests the same thing.
DIAG <- list()
# %% Model
# A vector autoregression forecasts every series from the lags of all of them (Luetkepohl 2005); a VECM adds the long-run
# relationships of cointegrated series (Johansen 1988). Least squares by equation in both engines; impulse responses use a
# Cholesky ordering with the target first, in the order the series are listed (the Python script runs the same code).
FINAL <- list()
DET <- PARAMS$deterministic
SEASONAL <- isTRUE(PARAMS$seasonal_dummies)
min_train <- function(m) 3L * (length(XREG) + 1L) + 6L
prepare_series <- function(y, t, m, freq) {
Y <- cbind(as.numeric(y), x_grid)
K <- ncol(Y)
if (PARAMS$lag_select == "manual") {
p <- as.integer(PARAMS$lags)
} else {
top <- cs_fcm_var_max_lag(length(y), K, as.integer(PARAMS$max_lags))
table <- cs_fcm_var_select(Y, top, if (PARAMS$model == "vecm") "const" else DET, m, SEASONAL)
p <- cs_fcm_var_pick(table, PARAMS$lag_select)
extra_tables[[length(extra_tables) + 1]] <<- list(
key = sprintf("lags%d", length(extra_tables) + 1),
title = paste0("Lag order (lower is better)", if (!is.null(current_series)) paste0(" — ", current_series) else ""),
columns = list(list(key = "lag", label = "Lags", type = "number"), list(key = "aic", label = "AIC", type = "number"), list(key = "hq", label = "HQ", type = "number"),
list(key = "sc", label = "SC", type = "number"), list(key = "fpe", label = "FPE", type = "number")),
rows = table
)
}
rank <- NULL
if (PARAMS$model == "vecm") {
rank <- if (!is.null(PARAMS$rank)) min(as.integer(PARAMS$rank), K) else as.integer(cs_ts_johansen(Y, 0, p - 1)$rank_trace)
}
list(p = p, rank = rank)
}
fit_system <- function(Y, m, spec) {
if (!is.null(spec$rank)) cs_fcm_vecm_fit(Y, spec$p, spec$rank, m, SEASONAL) else cs_fcm_var_fit(Y, spec$p, DET, m, SEASONAL)
}
fit_forecast <- function(y, t, h, m, levels, spec) {
Y <- cbind(as.numeric(y), X_TRAIN)
fit <- fit_system(Y, m, spec)
paths <- cs_fcm_var_forecast_paths(fit, h)
se <- cs_fcm_var_se(fit, h)
mean_ <- paths[, 1]
lower <- list(); upper <- list()
for (lv in levels) {
z <- cs_ml_fc_z(lv)
lower[[as.character(lv)]] <- mean_ - z * se[, 1]
upper[[as.character(lv)]] <- mean_ + z * se[, 1]
}
p <- fit$p
fitted <- c(rep(NaN, p), y[(p + 1):length(y)] - fit$U[, 1])
FINAL[[if (is.null(current_series)) "_" else current_series]] <<- list(fit = fit, paths = paths, se = se)
facts <- list(lag_order = as.numeric(p), max_root = cs_fcm_var_roots(fit))
for (i in seq_len(fit$K)) for (j in seq_len(fit$K)) {
facts[[sprintf("sigma_%d_%d", i, j)]] <- fit$Sigma[i, j]
for (lag in seq_len(p)) facts[[sprintf("a%d_%d_%d", lag, i, j)]] <- fit$A[[lag]][i, j]
}
if (!is.null(spec$rank)) {
facts$rank <- as.numeric(spec$rank)
label <- sprintf("VECM(%d lags, rank %d)", p, spec$rank)
} else {
label <- sprintf("VAR(%d)", p)
}
list(mean = mean_, lower = lower, upper = upper, fitted = fitted, label = label, facts = facts)
}
# %% Backtests and forecasts
lv <- function(level) if (level == floor(level)) as.character(as.integer(level)) else gsub(".", "_", as.character(level), fixed = TRUE)
bt_rows <- list()
fc_rows <- list()
facts <- list()
labels <- list()
freq_label <- ""
freq_alias <- ""
seasons <- integer(0)
n_obs <- 0
n_origins <- 0
filled <- 0
residuals_first <- NULL
for (key in series_keys) {
current_series <- key # model blocks may read it (e.g. table titles)
sel <- !is.na(times_all) & (if (!is.null(SERIES)) (!is.na(keys_all) & keys_all == key) else TRUE)
t_raw <- times_all[sel]; y_raw <- values_all[sel]
if (sum(!is.na(y_raw)) < 3) { # too few values to read the time step from
cs_error("CS_E_TOO_FEW_ROWS", what = if (is.null(key)) "Forecasting" else paste("Series", key), min = min_train(1) + 1, n = sum(!is.na(y_raw)))
}
x_later <- NULL
if (length(XREG)) { # rows after the last observed value carry known future regressors
x_raw <- x_all[sel, , drop = FALSE]
last_y <- max(t_raw[!is.na(y_raw)])
later <- t_raw > last_y
x_later <- x_raw[later, , drop = FALSE][order(t_raw[later]), , drop = FALSE]
t_raw <- t_raw[!later]; y_raw <- y_raw[!later]; x_raw <- x_raw[!later, , drop = FALSE]
}
freq <- cs_ml_fc_detect_frequency(sort(t_raw), TEMPORAL)
reg <- cs_ml_fc_regularize(t_raw, y_raw, freq)
t <- reg$t; y <- reg$y
x_grid <- if (length(XREG)) do.call(cbind, lapply(seq_len(ncol(x_raw)), function(j) cs_ml_fc_regularize(t_raw, x_raw[, j], freq)$y)) else NULL
filled <- filled + reg$filled
freq_label <- freq$label
freq_alias <- cs_ml_fc_alias(freq$unit)
m <- if (!is.null(SEASON)) as.integer(SEASON) else as.integer(freq$season)
seasons <- c(seasons, m)
n <- length(y)
n_obs <- n_obs + n
if (n < min_train(m) + 1) cs_error("CS_E_TOO_FEW_ROWS", what = if (is.null(key)) "Forecasting" else paste("Series", key), min = min_train(m) + 1, n = n)
spec <- prepare_series(y, t, m, freq)
step <- if (!is.null(STEP)) as.integer(STEP) else H
if (!is.null(OFFSETS)) {
origins <- cs_ml_fc_plan_origins(n, H, as.integer(OFFSETS), min_train(m))
if (length(origins) < length(OFFSETS)) {
warnings <- c(warnings, sprintf("%d of %d backtest origins were skipped for %s: too few values before them.", length(OFFSETS) - length(origins), length(OFFSETS), if (is.null(key)) VALUE else key))
}
} else {
origins <- cs_ml_fc_backtest_origins(n, H, WINDOWS, step, min_train(m))
}
for (o in origins) {
start <- if (!is.null(TRAIN_WINDOW)) max(1L, o - as.integer(TRAIN_WINDOW) + 1L) else 1L
if (length(XREG)) {
X_TRAIN <- x_grid[start:o, , drop = FALSE]
X_FUTURE <- x_grid[(o + 1):(o + H), , drop = FALSE]
}
res <- tryCatch(fit_forecast(y[start:o], t[start:o], H, m, LEVELS, spec), error = function(e) e)
if (inherits(res, "error")) {
warnings <- c(warnings, sprintf("Backtest from %s failed: %s", cs_ml_fc_format_time(t[o], TEMPORAL), conditionMessage(res)))
next
}
n_origins <- n_origins + 1
scale <- cs_ml_fc_mase_scale(y[1:o], m)
scale2 <- cs_ml_fc_rmsse_scale(y[1:o], m)
lag <- if (m > 1 && o > m) m else 1 # the seasonal naive forecast from this origin (MASE's lag rule)
for (k in seq_len(H)) {
row <- list(series = if (is.null(key)) NA_character_ else key, origin = cs_ml_fc_format_time(t[o], TEMPORAL),
time = cs_ml_fc_format_time(t[o + k], TEMPORAL), h = k, actual = y[o + k],
mean = res$mean[k], scale = scale, scale2 = scale2, last = y[o],
snaive = y[o - lag + (k - 1) %% lag + 1])
for (level in LEVELS) {
row[[paste0("lo_", lv(level))]] <- res$lower[[as.character(level)]][k]
row[[paste0("hi_", lv(level))]] <- res$upper[[as.character(level)]][k]
}
bt_rows[[length(bt_rows) + 1]] <- row
}
}
if (length(XREG)) {
X_TRAIN <- x_grid
X_FUTURE <- cs_ml_fc_future_regressors(x_grid, x_later, H)
if (nrow(x_later) < H) {
warnings <- c(warnings, sprintf("Future values of %s are known for %d of %d steps; the last known values are held for the rest.", paste(XREG, collapse = ", "), nrow(x_later), H))
}
}
final <- fit_forecast(y, t, H, m, LEVELS, spec)
labels[[length(labels) + 1]] <- final$label
for (name in names(final$facts)) facts[[if (is.null(SERIES)) name else sprintf("%s[%s]", name, key)]] <- final$facts[[name]]
fitted <- final$fitted
diag <- DIAG[[if (is.null(key)) "_" else key]]
resid <- diag$resid
if (is.null(residuals_first) && !is.null(resid)) {
residuals_first <- as.numeric(resid)
} else if (is.null(residuals_first) && !is.null(fitted)) {
ok <- !is.na(fitted)
residuals_first <- (y - fitted)[ok]
}
skey <- if (is.null(key)) NA_character_ else key
for (i in seq_len(n)) {
row <- list(series = skey, time = cs_ml_fc_format_time(t[i], TEMPORAL), t = t[i], kind = "actual", mean = y[i])
if (!is.null(resid) && i > n - length(resid)) row$resid <- resid[i - (n - length(resid))] # the last length(resid) times
if (!is.null(diag$fitdf)) row$lb_fitdf <- as.numeric(diag$fitdf)
if (!is.null(diag$lags)) row$lb_lags <- as.numeric(diag$lags)
fc_rows[[length(fc_rows) + 1]] <- row
if (!is.null(fitted) && !is.na(fitted[i])) {
fc_rows[[length(fc_rows) + 1]] <- list(series = skey, time = cs_ml_fc_format_time(t[i], TEMPORAL), t = t[i], kind = "fitted", mean = fitted[i])
}
}
future <- cs_ml_fc_future_times(t[n], freq, H)
for (k in seq_len(H)) {
row <- list(series = skey, time = cs_ml_fc_format_time(future[k], TEMPORAL), t = future[k], kind = "forecast", mean = final$mean[k])
for (level in LEVELS) {
row[[paste0("lo_", lv(level))]] <- final$lower[[as.character(level)]][k]
row[[paste0("hi_", lv(level))]] <- final$upper[[as.character(level)]][k]
}
fc_rows[[length(fc_rows) + 1]] <- row
}
}
if (filled > 0) warnings <- c(warnings, sprintf("%d missing time steps or values were filled by linear interpolation.", filled))
as_frame <- function(rows) {
cols <- unique(unlist(lapply(rows, names)))
as.data.frame(stats::setNames(lapply(cols, function(cn) {
v <- lapply(rows, function(r) if (is.null(r[[cn]])) NA else r[[cn]])
unlist(v)
}), cols), stringsAsFactors = FALSE, check.names = FALSE)
}
# %% Accuracy
bt <- if (length(bt_rows)) as_frame(bt_rows) else data.frame()
accuracy <- if (nrow(bt)) cs_ml_fc_accuracy(bt, LEVELS) else list()
fc_df <- as_frame(fc_rows)
forecasts <- fc_df[fc_df$kind == "forecast", , drop = FALSE]
weights <- seq_len(nrow(forecasts))
top <- if (length(LEVELS)) lv(max(LEVELS)) else NULL
wsum <- function(xs) sum(weights * xs) / sum(weights)
values <- list(
n_series = length(series_keys), n_obs = n_obs, horizon = H, season = seasons[1], n_origins = n_origins,
filled = filled, fc_check = wsum(forecasts$mean),
model_label = if (length(series_keys) == 1) labels[[1]] else sprintf("%d series, one model each", length(series_keys)),
freq_label = freq_label, frequency = freq_alias
)
if (!is.null(top)) {
values$fc_lo_check <- wsum(forecasts[[paste0("lo_", top)]])
values$fc_hi_check <- wsum(forecasts[[paste0("hi_", top)]])
}
for (k in names(accuracy)) values[[sprintf("bt[%s]", k)]] <- accuracy[[k]]
values <- c(values, facts)
nanoparquet::write_parquet(fc_df, file.path(out, "forecast.parquet"))
artifacts <- list(list(key = "forecast", path = file.path(out, "forecast.parquet"), format = "parquet"))
if (nrow(bt)) {
nanoparquet::write_parquet(bt, file.path(out, "backtest.parquet"))
artifacts[[2]] <- list(key = "backtest", path = file.path(out, "backtest.parquet"), format = "parquet")
}
# %% Charts
charts <- list()
shown <- if (!is.null(SERIES)) utils::head(series_keys, 8) else NULL
fan <- fc_df[fc_df$kind != "fitted" & (if (!is.null(SERIES)) fc_df$series %in% shown else TRUE), , drop = FALSE]
roles <- list(
time = cs_col(TIME, fan$time, kind = if (TEMPORAL) "temporal" else "numeric"),
value = cs_col(VALUE, fan$mean, kind = "numeric"),
kind = cs_col("kind", fan$kind, kind = "categorical", levels = c("actual", "forecast"))
)
for (level in c(80, 95)) {
if (level %in% LEVELS) {
roles[[paste0("lo_", lv(level))]] <- cs_col(paste0("lo_", lv(level)), fan[[paste0("lo_", lv(level))]], kind = "numeric")
roles[[paste0("hi_", lv(level))]] <- cs_col(paste0("hi_", lv(level)), fan[[paste0("hi_", lv(level))]], kind = "numeric")
}
}
if (!is.null(SERIES)) roles$series <- cs_col(SERIES, fan$series, kind = "categorical", levels = shown)
charts[[1]] <- cs_chart("forecast", "forecast-fan", sprintf("Forecast of %s", VALUE), roles)
if (nrow(bt)) {
charts[[length(charts) + 1]] <- cs_chart("backtest", "backtest-errors", "Backtest errors by horizon", list(
h = cs_col("horizon", bt$h, kind = "numeric"),
error = cs_col("error", bt$actual - bt$mean, kind = "numeric"),
origin = cs_col("origin", bt$origin, kind = "categorical")
))
}
if (length(residuals_first) > 4) {
lags <- min(max(2 * seasons[1], 10), length(residuals_first) - 1, 48)
r_acf <- cs_ml_fc_acf(residuals_first, lags)
bound <- 1.959963984540054 / sqrt(length(residuals_first))
charts[[length(charts) + 1]] <- cs_chart("acf", "acf-plot", "Residual autocorrelation", list(
lag = cs_col("lag", seq_len(lags), kind = "numeric"),
acf = cs_col("ACF", r_acf, kind = "numeric"),
bound = cs_col("bound", rep(bound, lags), kind = "numeric")
))
}
# %% Impulse responses and variance decomposition
warnings <- Filter(function(w) !startsWith(w, "Future values of"), warnings) # the other series are forecast, not supplied
NAMES <- c(VALUE, XREG)
first_key <- if (is.null(SERIES)) "_" else series_keys[1]
final0 <- FINAL[[first_key]]
fit0 <- final0$fit; paths0 <- final0$paths; se0 <- final0$se
K0 <- fit0$K
NH <- as.integer(PARAMS$irf_horizon)
theta0 <- cs_fcm_var_irf(fit0, NH)
bands0 <- cs_fcm_var_irf_bands(fit0, NH, as.integer(PARAMS$irf_boot), as.numeric(PARAMS$irf_level) / 100, SEED)
fevd0 <- cs_fcm_var_fevd(theta0)
suffix0 <- if (!is.null(SERIES)) paste0(" — ", first_key) else ""
grid0 <- expand.grid(j = seq_len(K0), i = seq_len(K0), h = seq_len(NH + 1))[, c("h", "i", "j")]
weights0 <- grid0$h * grid0$i * (grid0$j + 1)
wcheck <- function(cube) sum(weights0 * cube[cbind(grid0$h, grid0$i, grid0$j)]) / sum(weights0)
values$irf_check <- wcheck(theta0)
values$fevd_check <- wcheck(fevd0)
if (!is.null(bands0)) {
values$irf_lo_check <- wcheck(bands0$lower)
values$irf_hi_check <- wcheck(bands0$upper)
values$irf_reps <- as.numeric(bands0$reps)
}
values$others_fc_check <- sum(paths0[, -1, drop = FALSE]) / (H * (K0 - 1))
idx0 <- cbind(grid0$h, grid0$i, grid0$j)
irf_roles <- list(
h = cs_col("steps", grid0$h - 1, kind = "numeric"),
value = cs_col("response", theta0[idx0], kind = "numeric"),
response = cs_col("responding series", NAMES[grid0$i], kind = "categorical", levels = NAMES),
shock = cs_col("shock", NAMES[grid0$j], kind = "categorical", levels = NAMES)
)
if (!is.null(bands0)) {
irf_roles$lo <- cs_col("low", bands0$lower[idx0], kind = "numeric")
irf_roles$hi <- cs_col("high", bands0$upper[idx0], kind = "numeric")
}
charts[[length(charts) + 1]] <- cs_chart("irf", "impulse-response", paste0("Impulse responses", suffix0), irf_roles)
charts[[length(charts) + 1]] <- cs_chart("fevd", "fevd", paste0("Forecast error variance decomposition", suffix0), list(
h = cs_col("steps ahead", grid0$h, kind = "numeric"),
value = cs_col("share", fevd0[idx0], kind = "numeric"),
response = cs_col("responding series", NAMES[grid0$i], kind = "categorical", levels = NAMES),
shock = cs_col("shock", NAMES[grid0$j], kind = "categorical", levels = NAMES)
))
fevd_keep <- Filter(function(h) h %in% c(1, 2, 4, 6, 8, 12, NH + 1), seq_len(NH + 1))
extra_tables[[length(extra_tables) + 1]] <- list(
key = "fevd",
title = paste0(sprintf("What drives the forecast error of %s", VALUE), suffix0),
columns = c(list(list(key = "h", label = "Steps ahead", type = "number")), lapply(seq_len(K0), function(j) list(key = sprintf("s%d", j - 1), label = NAMES[j], type = "number"))),
rows = lapply(fevd_keep, function(h) c(list(h = h), stats::setNames(as.list(fevd0[h, 1, ]), sprintf("s%d", seq_len(K0) - 1))))
)
if (K0 > 1) {
other_rows <- list()
for (j in 2:K0) for (k in seq_len(H)) other_rows[[length(other_rows) + 1]] <- list(series = NAMES[j], h = k, mean = paths0[k, j], se = se0[k, j])
extra_tables[[length(extra_tables) + 1]] <- list(
key = "others",
title = paste0("Forecasts of the other series", suffix0),
columns = list(list(key = "series", label = "Series"), list(key = "h", label = "Steps ahead", type = "number"), list(key = "mean", label = "Forecast", type = "number"), list(key = "se", label = "SE", type = "number")),
rows = other_rows
)
}
if (fit0$kind == "var") {
granger0 <- cs_fcm_var_granger(fit0)
extra_tables[[length(extra_tables) + 1]] <- list(
key = "granger",
title = paste0("Do one series' lags help predict another? (predictive, not causal)", suffix0),
columns = list(list(key = "cause", label = "Lags of"), list(key = "effect", label = "Predicting"), list(key = "f", label = "F", type = "number"), list(key = "df2", label = "df", type = "number"), list(key = "p", label = "p", type = "number")),
rows = lapply(granger0, function(r) { r$cause <- NAMES[r$cause]; r$effect <- NAMES[r$effect]; r })
)
for (r in granger0) values[[sprintf("granger_p_%d_%d", r$cause, r$effect)]] <- r$p
} else if (fit0$rank > 0) {
rk <- fit0$rank
extra_tables[[length(extra_tables) + 1]] <- list(
key = "cointegration",
title = paste0("Long-run relationships: each row of β is a combination that stays stationary, α how fast each series returns to it", suffix0),
columns = c(list(list(key = "series", label = "Series")), unlist(lapply(seq_len(rk), function(r) list(list(key = sprintf("b%d", r - 1), label = sprintf("β%d", r), type = "number"), list(key = sprintf("a%d", r - 1), label = sprintf("α%d", r), type = "number"))), recursive = FALSE)),
rows = lapply(seq_len(K0), function(i) c(list(series = NAMES[i]), stats::setNames(as.list(fit0$beta[i, ]), sprintf("b%d", seq_len(rk) - 1)), stats::setNames(as.list(fit0$alpha[i, ]), sprintf("a%d", seq_len(rk) - 1))))
)
for (i in seq_len(K0)) for (r in seq_len(rk)) {
values[[sprintf("beta_%d_%d", i, r)]] <- fit0$beta[i, r]
values[[sprintf("alpha_%d_%d", i, r)]] <- fit0$alpha[i, r]
}
}
root0 <- cs_fcm_var_roots(fit0)
is_vecm <- fit0$kind == "vecm"
root_ok <- root0 < (if (is_vecm) 1 + 1e-6 else 1)
extra_assumptions[[length(extra_assumptions) + 1]] <- list(
key = "stability", label = if (is_vecm) "No roots beyond the expected unit roots" else "The system is stable", status = if (root_ok) "pass" else "warn", statistic = root0,
detail = paste0(sprintf("Largest root modulus %.3f.", root0), if (!root_ok) " Explosive: difference the series, or use a VECM if they are cointegrated." else "")
)
pt_lags <- max(10L, fit0$p + 5L)
if (pt_lags < fit0$T) {
pt0 <- cs_fcm_var_portmanteau(fit0, pt_lags)
values$portmanteau_q <- pt0$stat
values$portmanteau_p <- pt0$p
extra_assumptions[[length(extra_assumptions) + 1]] <- list(
key = "independence", label = "Residuals look uncorrelated", status = if (pt0$p > 0.05) "pass" else "warn", statistic = pt0$p,
detail = paste0(sprintf("Adjusted portmanteau at %d lags: p = %.3f.", pt_lags, pt0$p), if (pt0$p <= 0.05) " Dynamics remain in the residuals: try more lags." else "")
)
}
# %% Result
show <- intersect(c("mae", "rmse", "mape", "smape", "mase", "wape"), names(accuracy))
tables <- list()
if (length(accuracy)) {
rows <- lapply(show, function(k) list(metric = if (k == "smape") "sMAPE" else toupper(k), value = accuracy[[k]]))
for (level in LEVELS) {
ck <- paste0("coverage_", lv(level))
if (!is.null(accuracy[[ck]])) rows[[length(rows) + 1]] <- list(metric = sprintf("Coverage of the %s%% interval", lv(level)), value = accuracy[[ck]])
}
tables[[1]] <- list(key = "accuracy", title = sprintf("Backtest accuracy (%d origin%s, horizon %d)", n_origins, if (n_origins != 1) "s" else "", H),
columns = list(list(key = "metric", label = "Metric"), list(key = "value", label = "Value", type = "number")), rows = rows)
}
fc_cols <- c(if (!is.null(SERIES)) list(list(key = "series", label = "Series")),
list(list(key = "time", label = TIME), list(key = "mean", label = "Forecast", type = "number")))
for (level in LEVELS) {
fc_cols <- c(fc_cols, list(list(key = paste0("lo_", lv(level)), label = sprintf("%s%% low", lv(level)), type = "number"),
list(key = paste0("hi_", lv(level)), label = sprintf("%s%% high", lv(level)), type = "number")))
}
tables <- c(tables, extra_tables)
keep <- setdiff(names(forecasts), c("t", "kind", if (is.null(SERIES)) "series"))
tables[[length(tables) + 1]] <- list(key = "forecast", title = "Forecast", columns = fc_cols,
rows = lapply(seq_len(min(200, nrow(forecasts))), function(i) as.list(forecasts[i, keep, drop = FALSE])))
summary <- sprintf("%s: %d-step forecasts of %s (%s data, %d observations).", values$model_label, H, VALUE, freq_label, n_obs)
if (!is.null(accuracy$mae)) summary <- paste0(summary, sprintf(" Backtest MAE %s over %d origin%s.", format(signif(accuracy$mae, 3)), n_origins, if (n_origins != 1) "s" else ""))
cs_publish(list(
title = "VAR / VECM",
engine = cs_engine_info("stats", "nanoparquet"),
n = n_obs,
summary = summary,
statistics = lapply(utils::head(show, 3), function(k) list(key = k, label = toupper(k), value = accuracy[[k]])),
tables = tables,
values = values,
assumptions = extra_assumptions,
warnings = warnings,
notes = list(),
charts = charts,
artifacts = artifacts
))
VAR(2): 6-step forecasts of y1 (monthly data, 240 observations). Backtest MAE 1.33 over 2 origins.
- MAE
- 1.329
- RMSE
- 1.580
- MAPE
- 0.4174
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- The system is stable — Largest root modulus 0.652.
- Residuals look uncorrelated — Adjusted portmanteau at 10 lags: p = 0.458.
Backtest accuracy (2 origins, horizon 6)
| Metric | Value |
|---|---|
| MAE | 1.329 |
| RMSE | 1.580 |
| MAPE | 0.4174 |
| sMAPE | 0.5513 |
| MASE | 0.9367 |
| WAPE | 0.4614 |
| Coverage of the 80% interval | 0.6667 |
| Coverage of the 95% interval | 0.9167 |
Lag order (lower is better)
| Lags | AIC | HQ | SC | FPE |
|---|---|---|---|---|
| 1 | −0.3640 | −0.2921 | −0.1857 | 0.6949 |
| 2 | −0.3960 | −0.2702 | −0.0840 | 0.6730 |
| 3 | −0.3694 | −0.1897 | 0.0763 | 0.6913 |
| 4 | −0.3188 | −0.0852 | 0.2606 | 0.7272 |
| 5 | −0.3003 | −0.0127 | 0.4128 | 0.7411 |
| 6 | −0.2463 | 0.0952 | 0.6006 | 0.7826 |
| 7 | −0.2068 | 0.1886 | 0.7737 | 0.8146 |
| 8 | −0.2043 | 0.2450 | 0.9099 | 0.8172 |
What drives the forecast error of y1
| Steps ahead | y1 | y2 | y3 |
|---|---|---|---|
| 1 | 1 | 0 | 0 |
| 2 | 0.9902 | 0.0038 | 0.0061 |
| 4 | 0.9689 | 0.0247 | 0.0064 |
| 6 | 0.9676 | 0.0259 | 0.0064 |
| 8 | 0.9676 | 0.0259 | 0.0065 |
| 12 | 0.9676 | 0.0259 | 0.0065 |
| 13 | 0.9676 | 0.0259 | 0.0065 |
Forecasts of the other series
| Series | Steps ahead | Forecast | SE |
|---|---|---|---|
| y2 | 1 | 3.438 | 0.9721 |
| y2 | 2 | 2.662 | 1.164 |
| y2 | 3 | 2.051 | 1.228 |
| y2 | 4 | 1.746 | 1.244 |
| y2 | 5 | 1.620 | 1.248 |
| y2 | 6 | 1.561 | 1.250 |
| y3 | 1 | 0.8958 | 0.8474 |
| y3 | 2 | 0.8147 | 0.8968 |
| y3 | 3 | 0.5316 | 0.9514 |
| y3 | 4 | 0.3142 | 0.9721 |
| y3 | 5 | 0.1498 | 0.9830 |
| y3 | 6 | 0.0446 | 0.9875 |
Do one series' lags help predict another? (predictive, not causal)
| Lags of | Predicting | F | df | p |
|---|---|---|---|---|
| y2 | y1 | 2.272 | 231 | 0.1054 |
| y3 | y1 | 1.025 | 231 | 0.3605 |
| y1 | y2 | 11.928 | 231 | 1.175e-5 |
| y3 | y2 | 0.3823 | 231 | 0.6827 |
| y1 | y3 | 1.174 | 231 | 0.3108 |
| y2 | y3 | 0.5356 | 231 | 0.5860 |
Forecast
| month | Forecast | 80% low | 80% high | 95% low | 95% high |
|---|---|---|---|---|---|
| 2020-01-01 | 3.338 | 1.873 | 4.803 | 1.097 | 5.578 |
| 2020-02-01 | 2.219 | 0.5252 | 3.913 | −0.3715 | 4.810 |
| 2020-03-01 | 1.815 | 0.0870 | 3.543 | −0.8277 | 4.458 |
| 2020-04-01 | 1.722 | −0.0133 | 3.457 | −0.9318 | 4.375 |
| 2020-05-01 | 1.677 | −0.0599 | 3.413 | −0.9792 | 4.332 |
| 2020-06-01 | 1.638 | −0.0992 | 3.375 | −1.019 | 4.294 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# VAR / VECM
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method forecast.var 1.0.0 · spec 1f4b7a8e32837d9f
# Dataset: f7_var_sim (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import forecast as fc
from codesplash.ml import forecast_models as fcm
from codesplash.stats import ts as cs_ts
# %% Data
TIME = "month"
VALUE = "y1"
SERIES = None
H = 6
LEVELS = [float(v) for v in [80, 95]]
SEASON = None # None = from the time steps (12 monthly, 4 quarterly, 7 daily …)
WINDOWS = 2
STEP = None # None = the horizon
OFFSETS = None # the host's BacktestPlan: distance of each origin from the end of the series; None = windows and step
TRAIN_WINDOW = None # None = train on all values before each origin
TRAIN_START = None # rows before this time are left out (for example, before a structural break)
SEED = 42
XREG = ["y2", "y3"]
PARAMS = {
"model": "var",
"lag_select": "aic",
"lags": 2,
"max_lags": 8,
"deterministic": "const",
"seasonal_dummies": False,
"rank": None,
"irf_horizon": 12,
"irf_boot": 50,
"irf_level": 90,
}
df = pd.read_parquet("tests/parity/fixtures/f7_var_sim.parquet", columns=list(dict.fromkeys([c for c in (TIME, VALUE, SERIES) if c] + list(XREG))))
cs.check_finite_columns(df, [TIME, VALUE] + list(XREG)) # infinite values stop with CS_E_NOT_FINITE, naming the column
if len(df) == 0:
cs.cs_error("CS_E_NO_ROWS")
warnings = []
times_all, TEMPORAL = fc.to_days(df[TIME])
values_all = pd.to_numeric(df[VALUE], errors="coerce").to_numpy(dtype=np.float64)
x_all = np.column_stack([pd.to_numeric(df[c], errors="coerce").to_numpy(dtype=np.float64) for c in XREG]) if XREG else None
if TRAIN_START is not None:
cut = fc.parse_time(TRAIN_START, TEMPORAL)
early = np.nan_to_num(times_all, nan=np.inf) < cut
if early.any():
warnings.append(f"{int(early.sum())} rows before {TRAIN_START} were left out of training.")
times_all = np.where(early, np.nan, times_all)
keys_all = df[SERIES].astype("object").to_numpy() if SERIES else np.array([None] * len(df), dtype=object)
dropped = int(np.isnan(times_all).sum()) - (int(early.sum()) if TRAIN_START is not None else 0)
if dropped:
warnings.append(f"{dropped} rows without a time were left out.")
series_keys = sorted({str(k) for k in keys_all if not pd.isna(k)}) if SERIES else [None] # None, NaN, pd.NA: no name
if SERIES and any(pd.isna(k) for k in keys_all):
warnings.append("Rows without a series name were left out.")
# Degenerate inputs stop with catalog codes, in the same order as the R driver.
if bool(np.isnan(values_all).all()):
cs.cs_error("CS_E_ALL_MISSING", column=VALUE)
if not bool((~np.isnan(times_all) & ~np.isnan(values_all)).any()):
cs.cs_error("CS_E_NO_ROWS")
out = csml.out_dir("target/academy-parity/run-8142/forecast.var/sim_var_aic/out-python")
extra_tables = [] # model blocks may add result tables (e.g. automatic selection)
extra_assumptions = [] # … and assumption rows
current_series = None
X_TRAIN = None # regressors while fit_forecast runs: rows × regressors, aligned with its y
X_FUTURE = None # … and h × regressors for the steps it forecasts
# Model blocks may set DIAG[current_series] = {"resid": [...], "fitdf": k, "lags": L} from each fit (the final fit's
# entry is kept): the residuals their own check tests when that is not actual − fitted (GARCH: standardized; ARIMAX:
# the ARMA errors), the ARMA terms they were filtered with, and the Ljung–Box lags when the method's rule differs from
# min(2m, n/5). They go to forecast.parquet so the host's Residuals tab tests the same thing.
DIAG = {}
# %% Model
# A vector autoregression forecasts every series from the lags of all of them (Lütkepohl 2005); a VECM adds the long-run
# relationships of cointegrated series (Johansen 1988). Least squares by equation in both engines; impulse responses use a
# Cholesky ordering with the target first, in the order the series are listed (the R script runs the same code).
FINAL = {}
DET = PARAMS["deterministic"]
SEASONAL = bool(PARAMS["seasonal_dummies"])
def min_train(m):
return 3 * (len(XREG) + 1) + 6
def prepare_series(y, t, m, freq):
Y = np.column_stack([np.asarray(y, dtype=float), x_grid])
K = Y.shape[1]
if PARAMS["lag_select"] == "manual":
p = int(PARAMS["lags"])
else:
top = fcm.var_max_lag(len(y), K, int(PARAMS["max_lags"]))
table = fcm.var_select(Y, top, "const" if PARAMS["model"] == "vecm" else DET, m, SEASONAL)
p = fcm.var_pick(table, PARAMS["lag_select"])
extra_tables.append(
{
"key": f"lags{len(extra_tables) + 1}",
"title": "Lag order (lower is better)" + (f" — {current_series}" if current_series else ""),
"columns": [{"key": "lag", "label": "Lags", "type": "number"}, {"key": "aic", "label": "AIC", "type": "number"}, {"key": "hq", "label": "HQ", "type": "number"},
{"key": "sc", "label": "SC", "type": "number"}, {"key": "fpe", "label": "FPE", "type": "number"}],
"rows": table,
}
)
rank = None
if PARAMS["model"] == "vecm":
if PARAMS["rank"] is not None:
rank = min(int(PARAMS["rank"]), K)
else:
rank = int(cs_ts.johansen(Y, 0, p - 1)["rank_trace"])
return {"p": p, "rank": rank}
def fit_system(Y, m, spec):
if spec["rank"] is not None:
return fcm.vecm_fit(Y, spec["p"], spec["rank"], m, SEASONAL)
return fcm.var_fit(Y, spec["p"], DET, m, SEASONAL)
def fit_forecast(y, t, h, m, levels, spec):
Y = np.column_stack([np.asarray(y, dtype=float), X_TRAIN])
fit = fit_system(Y, m, spec)
paths = fcm.var_forecast_paths(fit, h)
se = fcm.var_se(fit, h)
mean = [float(v) for v in paths[:, 0]]
lower = {lv: [mean[k] - fc.z_value(lv) * float(se[k, 0]) for k in range(h)] for lv in levels}
upper = {lv: [mean[k] + fc.z_value(lv) * float(se[k, 0]) for k in range(h)] for lv in levels}
p = fit["p"]
fitted = [float("nan")] * p + [float(y[p + i] - fit["U"][i, 0]) for i in range(len(y) - p)]
FINAL[current_series] = (fit, paths, se)
facts = {"lag_order": float(p), "max_root": fcm.var_roots(fit)}
for i in range(fit["K"]):
for j in range(fit["K"]):
facts[f"sigma_{i + 1}_{j + 1}"] = float(fit["Sigma"][i, j])
for lag in range(p):
facts[f"a{lag + 1}_{i + 1}_{j + 1}"] = float(fit["A"][lag][i, j])
if spec["rank"] is not None:
facts["rank"] = float(spec["rank"])
label = f"VECM({p} lags, rank {spec['rank']})"
else:
label = f"VAR({p})"
return {"mean": mean, "lower": lower, "upper": upper, "fitted": fitted, "label": label, "facts": facts}
# %% Backtests and forecasts
def lv(level):
return str(int(level)) if float(level).is_integer() else str(level).replace(".", "_")
bt_rows = []
fc_rows = []
facts = {}
labels = {}
freq_label = ""
freq_alias = ""
seasons = []
n_obs = 0
n_origins = 0
filled = 0
residuals_first = None
for key in series_keys:
current_series = key # model blocks may read it (e.g. table titles)
sel = ~np.isnan(times_all) & ((keys_all.astype(str) == key) if SERIES else True)
t_raw, y_raw = times_all[sel], values_all[sel]
if int(np.sum(~np.isnan(y_raw))) < 3: # too few values to read the time step from
cs.cs_error("CS_E_TOO_FEW_ROWS", what=("Forecasting" if key is None else f"Series {key}"), min=min_train(1) + 1, n=int(np.sum(~np.isnan(y_raw))))
x_later = None
if XREG: # rows after the last observed value carry known future regressors
x_raw = x_all[sel]
last_y = np.nanmax(np.where(np.isnan(y_raw), np.nan, t_raw))
later = t_raw > last_y
order_later = np.argsort(t_raw[later], kind="stable")
x_later = x_raw[later][order_later]
t_raw, y_raw, x_raw = t_raw[~later], y_raw[~later], x_raw[~later]
freq = fc.detect_frequency(np.sort(t_raw), TEMPORAL)
t, y, nfill = fc.regularize(t_raw, y_raw, freq)
x_grid = np.column_stack([fc.regularize(t_raw, x_raw[:, j], freq)[1] for j in range(x_raw.shape[1])]) if XREG else None
filled += nfill
freq_label = freq["label"]
freq_alias = fc.ALIASES.get(freq["unit"], "")
m = int(SEASON) if SEASON else int(freq["season"])
seasons.append(m)
y = [float(v) for v in y]
n = len(y)
n_obs += n
if n < min_train(m) + 1:
cs.cs_error("CS_E_TOO_FEW_ROWS", what=("Forecasting" if key is None else f"Series {key}"), min=min_train(m) + 1, n=n)
spec = prepare_series(y, t, m, freq)
step = int(STEP) if STEP else H
if OFFSETS is not None:
origins = fc.plan_origins(n, H, [int(v) for v in OFFSETS], min_train(m))
if len(origins) < len(OFFSETS):
warnings.append(f"{len(OFFSETS) - len(origins)} of {len(OFFSETS)} backtest origins were skipped for {key or VALUE}: too few values before them.")
else:
origins = fc.backtest_origins(n, H, WINDOWS, step, min_train(m))
for o in origins:
start = max(0, o - int(TRAIN_WINDOW)) if TRAIN_WINDOW else 0
if XREG:
X_TRAIN, X_FUTURE = x_grid[start:o], x_grid[o:o + H]
try:
res = fit_forecast(y[start:o], t[start:o], H, m, LEVELS, spec)
except Exception as e: # a failed origin is skipped, not fatal
warnings.append(f"Backtest from {fc.format_time(t[o - 1], TEMPORAL)} failed: {e}")
continue
n_origins += 1
scale = fc.mase_scale(y[:o], m)
scale2 = fc.rmsse_scale(y[:o], m)
lag = m if (m > 1 and o > m) else 1 # the seasonal naive forecast from this origin (MASE's lag rule)
for k in range(H):
row = {
"series": key,
"origin": fc.format_time(t[o - 1], TEMPORAL),
"time": fc.format_time(t[o + k], TEMPORAL),
"h": k + 1,
"actual": y[o + k],
"mean": float(res["mean"][k]),
"scale": scale,
"scale2": scale2,
"last": y[o - 1],
"snaive": y[o - lag + k % lag],
}
for level in LEVELS:
row[f"lo_{lv(level)}"] = float(res["lower"][level][k])
row[f"hi_{lv(level)}"] = float(res["upper"][level][k])
bt_rows.append(row)
if XREG:
X_TRAIN = x_grid
X_FUTURE = fc.future_regressors(x_grid, x_later, H)
if len(x_later) < H:
warnings.append(f"Future values of {', '.join(XREG)} are known for {len(x_later)} of {H} steps; the last known values are held for the rest.")
final = fit_forecast(y, t, H, m, LEVELS, spec)
labels[key] = final["label"]
for name, value in final["facts"].items():
facts[name if not SERIES else f"{name}[{key}]"] = value
fitted = final.get("fitted")
diag = DIAG.get(key) or {}
resid = diag.get("resid")
if residuals_first is None and resid is not None:
residuals_first = [float(v) for v in resid]
elif residuals_first is None and fitted is not None:
residuals_first = [y[i] - fitted[i] for i in range(n) if fitted[i] is not None and not math.isnan(fitted[i])]
for i in range(n):
row = {"series": key, "time": fc.format_time(t[i], TEMPORAL), "t": float(t[i]), "kind": "actual", "mean": y[i]}
if resid is not None and i >= n - len(resid): # the last len(resid) times (differencing drops early ones)
row["resid"] = float(resid[i - (n - len(resid))])
if "fitdf" in diag:
row["lb_fitdf"] = float(diag["fitdf"])
if "lags" in diag:
row["lb_lags"] = float(diag["lags"])
fc_rows.append(row)
if fitted is not None and not math.isnan(fitted[i]):
fc_rows.append({"series": key, "time": fc.format_time(t[i], TEMPORAL), "t": float(t[i]), "kind": "fitted", "mean": float(fitted[i])})
future = fc.future_times(t[-1], freq, H)
for k in range(H):
row = {"series": key, "time": fc.format_time(future[k], TEMPORAL), "t": float(future[k]), "kind": "forecast", "mean": float(final["mean"][k])}
for level in LEVELS:
row[f"lo_{lv(level)}"] = float(final["lower"][level][k])
row[f"hi_{lv(level)}"] = float(final["upper"][level][k])
fc_rows.append(row)
if filled:
warnings.append(f"{filled} missing time steps or values were filled by linear interpolation.")
# %% Accuracy
accuracy = fc.accuracy(bt_rows, LEVELS)
forecasts = [r for r in fc_rows if r["kind"] == "forecast"]
weights = [i + 1.0 for i in range(len(forecasts))]
top = lv(max(LEVELS)) if LEVELS else None
def wsum(xs):
return fc._sum([weights[i] * xs[i] for i in range(len(xs))]) / fc._sum(weights)
values = {
"n_series": len(series_keys),
"n_obs": n_obs,
"horizon": H,
"season": seasons[0],
"n_origins": n_origins,
"filled": filled,
"fc_check": wsum([r["mean"] for r in forecasts]),
"model_label": labels[series_keys[0]] if len(series_keys) == 1 else f"{len(series_keys)} series, one model each",
"freq_label": freq_label,
"frequency": freq_alias,
}
if top:
values["fc_lo_check"] = wsum([r[f"lo_{top}"] for r in forecasts])
values["fc_hi_check"] = wsum([r[f"hi_{top}"] for r in forecasts])
for k, v in accuracy.items():
values[f"bt[{k}]"] = v
values.update(facts)
pd.DataFrame(fc_rows).to_parquet(os.path.join(out, "forecast.parquet"), index=False)
artifacts = [{"key": "forecast", "path": os.path.join(out, "forecast.parquet"), "format": "parquet"}]
if bt_rows:
pd.DataFrame(bt_rows).to_parquet(os.path.join(out, "backtest.parquet"), index=False)
artifacts.append({"key": "backtest", "path": os.path.join(out, "backtest.parquet"), "format": "parquet"})
# %% Charts
charts = []
shown = series_keys[:8]
fan = [r for r in fc_rows if r["series"] in shown and r["kind"] != "fitted"]
kind = "temporal" if TEMPORAL else "numeric"
roles = {
"time": cs.col(TIME, [r["time"] for r in fan], kind=kind),
"value": cs.col(VALUE, [r["mean"] for r in fan], kind="numeric"),
"kind": cs.col("kind", [r["kind"] for r in fan], kind="categorical", levels=["actual", "forecast"]),
}
for level in (80.0, 95.0):
if level in LEVELS:
roles[f"lo_{lv(level)}"] = cs.col(f"lo_{lv(level)}", [r.get(f"lo_{lv(level)}") for r in fan], kind="numeric")
roles[f"hi_{lv(level)}"] = cs.col(f"hi_{lv(level)}", [r.get(f"hi_{lv(level)}") for r in fan], kind="numeric")
if SERIES:
roles["series"] = cs.col(SERIES, [r["series"] for r in fan], kind="categorical", levels=shown)
charts.append(cs.chart("forecast", "forecast-fan", f"Forecast of {VALUE}", roles))
if bt_rows:
charts.append(
cs.chart(
"backtest",
"backtest-errors",
"Backtest errors by horizon",
{
"h": cs.col("horizon", [r["h"] for r in bt_rows], kind="numeric"),
"error": cs.col("error", [r["actual"] - r["mean"] for r in bt_rows], kind="numeric"),
"origin": cs.col("origin", [r["origin"] for r in bt_rows], kind="categorical"),
},
)
)
if residuals_first and len(residuals_first) > 4:
lags = min(max(2 * seasons[0], 10), len(residuals_first) - 1, 48)
r_acf = fc.acf(residuals_first, lags)
bound = 1.959963984540054 / math.sqrt(len(residuals_first))
charts.append(
cs.chart(
"acf",
"acf-plot",
"Residual autocorrelation",
{
"lag": cs.col("lag", list(range(1, lags + 1)), kind="numeric"),
"acf": cs.col("ACF", r_acf, kind="numeric"),
"bound": cs.col("bound", [bound] * lags, kind="numeric"),
},
)
)
# %% Impulse responses and variance decomposition
warnings = [w for w in warnings if not w.startswith("Future values of")] # the other series are forecast, not supplied
NAMES = [VALUE] + list(XREG)
fit0, paths0, se0 = FINAL[series_keys[0]]
K0 = fit0["K"]
NH = int(PARAMS["irf_horizon"])
theta0 = fcm.var_irf(fit0, NH)
bands0 = fcm.var_irf_bands(fit0, NH, int(PARAMS["irf_boot"]), float(PARAMS["irf_level"]) / 100.0, SEED)
fevd0 = fcm.var_fevd(theta0)
suffix0 = f" — {series_keys[0]}" if SERIES else ""
weights0 = [(h + 1.0) * (i + 1.0) * (j + 2.0) for h in range(NH + 1) for i in range(K0) for j in range(K0)]
def wcheck(cube):
flat = [float(cube[h, i, j]) for h in range(NH + 1) for i in range(K0) for j in range(K0)]
return fc._sum([weights0[k] * flat[k] for k in range(len(flat))]) / fc._sum(weights0)
values["irf_check"] = wcheck(theta0)
values["fevd_check"] = wcheck(fevd0)
if bands0 is not None:
values["irf_lo_check"] = wcheck(bands0["lower"])
values["irf_hi_check"] = wcheck(bands0["upper"])
values["irf_reps"] = float(bands0["reps"])
others0 = [float(paths0[k, j]) for k in range(H) for j in range(1, K0)]
values["others_fc_check"] = fc._mean(others0)
irf_rows = [
{"h": h, "response": NAMES[i], "shock": NAMES[j], "irf": float(theta0[h, i, j]),
"lo": float(bands0["lower"][h, i, j]) if bands0 is not None else None, "hi": float(bands0["upper"][h, i, j]) if bands0 is not None else None}
for h in range(NH + 1) for i in range(K0) for j in range(K0)
]
fevd_rows = [{"h": h + 1, "response": NAMES[i], "shock": NAMES[j], "share": float(fevd0[h, i, j])} for h in range(NH + 1) for i in range(K0) for j in range(K0)]
charts.append(
cs.chart(
"irf", "impulse-response", "Impulse responses" + suffix0,
{
"h": cs.col("steps", [r["h"] for r in irf_rows], kind="numeric"),
"value": cs.col("response", [r["irf"] for r in irf_rows], kind="numeric"),
"response": cs.col("responding series", [r["response"] for r in irf_rows], kind="categorical", levels=NAMES),
"shock": cs.col("shock", [r["shock"] for r in irf_rows], kind="categorical", levels=NAMES),
**({"lo": cs.col("low", [r["lo"] for r in irf_rows], kind="numeric"), "hi": cs.col("high", [r["hi"] for r in irf_rows], kind="numeric")} if bands0 is not None else {}),
},
)
)
charts.append(
cs.chart(
"fevd", "fevd", "Forecast error variance decomposition" + suffix0,
{
"h": cs.col("steps ahead", [r["h"] for r in fevd_rows], kind="numeric"),
"value": cs.col("share", [r["share"] for r in fevd_rows], kind="numeric"),
"response": cs.col("responding series", [r["response"] for r in fevd_rows], kind="categorical", levels=NAMES),
"shock": cs.col("shock", [r["shock"] for r in fevd_rows], kind="categorical", levels=NAMES),
},
)
)
extra_tables.append(
{
"key": "fevd",
"title": f"What drives the forecast error of {VALUE}" + suffix0,
"columns": [{"key": "h", "label": "Steps ahead", "type": "number"}] + [{"key": f"s{j}", "label": NAMES[j], "type": "number"} for j in range(K0)],
"rows": [{"h": h + 1, **{f"s{j}": float(fevd0[h, 0, j]) for j in range(K0)}} for h in range(NH + 1) if h + 1 in (1, 2, 4, 6, 8, 12, NH + 1)],
}
)
if K0 > 1:
extra_tables.append(
{
"key": "others",
"title": "Forecasts of the other series" + suffix0,
"columns": [{"key": "series", "label": "Series"}, {"key": "h", "label": "Steps ahead", "type": "number"}, {"key": "mean", "label": "Forecast", "type": "number"}, {"key": "se", "label": "SE", "type": "number"}],
"rows": [{"series": NAMES[j], "h": k + 1, "mean": float(paths0[k, j]), "se": float(se0[k, j])} for j in range(1, K0) for k in range(H)],
}
)
if fit0["kind"] == "var":
granger0 = fcm.var_granger(fit0)
extra_tables.append(
{
"key": "granger",
"title": "Do one series' lags help predict another? (predictive, not causal)" + suffix0,
"columns": [{"key": "cause", "label": "Lags of"}, {"key": "effect", "label": "Predicting"}, {"key": "f", "label": "F", "type": "number"}, {"key": "df2", "label": "df", "type": "number"}, {"key": "p", "label": "p", "type": "number"}],
"rows": [{**r, "cause": NAMES[r["cause"]], "effect": NAMES[r["effect"]]} for r in granger0],
}
)
for r in granger0:
values[f"granger_p_{r['cause'] + 1}_{r['effect'] + 1}"] = r["p"]
elif fit0["rank"] > 0:
extra_tables.append(
{
"key": "cointegration",
"title": "Long-run relationships: each row of β is a combination that stays stationary, α how fast each series returns to it" + suffix0,
"columns": [{"key": "series", "label": "Series"}]
+ [c for r in range(fit0["rank"]) for c in ({"key": f"b{r}", "label": f"β{r + 1}", "type": "number"}, {"key": f"a{r}", "label": f"α{r + 1}", "type": "number"})],
"rows": [{"series": NAMES[i], **{f"b{r}": float(fit0["beta"][i, r]) for r in range(fit0["rank"])}, **{f"a{r}": float(fit0["alpha"][i, r]) for r in range(fit0["rank"])}} for i in range(K0)],
}
)
for i in range(K0):
for r in range(fit0["rank"]):
values[f"beta_{i + 1}_{r + 1}"] = float(fit0["beta"][i, r])
values[f"alpha_{i + 1}_{r + 1}"] = float(fit0["alpha"][i, r])
root0 = fcm.var_roots(fit0)
is_vecm = fit0["kind"] == "vecm"
extra_assumptions.append(
{
"key": "stability",
"label": "The system is stable" if not is_vecm else "No roots beyond the expected unit roots",
"status": "pass" if root0 < (1.0 + 1e-6 if is_vecm else 1.0) else "warn",
"statistic": root0,
"detail": f"Largest root modulus {root0:.3f}." + ("" if root0 < (1.0 + 1e-6 if is_vecm else 1.0) else " Explosive: difference the series, or use a VECM if they are cointegrated."),
}
)
pt_lags = max(10, fit0["p"] + 5)
if pt_lags < fit0["T"]:
pt0 = fcm.var_portmanteau(fit0, pt_lags)
values["portmanteau_q"] = pt0["stat"]
values["portmanteau_p"] = pt0["p"]
extra_assumptions.append(
{
"key": "independence",
"label": "Residuals look uncorrelated",
"status": "pass" if pt0["p"] > 0.05 else "warn",
"statistic": pt0["p"],
"detail": f"Adjusted portmanteau at {pt_lags} lags: p = {pt0['p']:.3f}." + ("" if pt0["p"] > 0.05 else " Dynamics remain in the residuals: try more lags."),
}
)
# %% Result
show = [m for m in ("mae", "rmse", "mape", "smape", "mase", "wape") if m in accuracy]
tables = []
if accuracy:
tables.append(
{
"key": "accuracy",
"title": f"Backtest accuracy ({n_origins} origin{'s' if n_origins != 1 else ''}, horizon {H})",
"columns": [{"key": "metric", "label": "Metric"}, {"key": "value", "label": "Value", "type": "number"}],
"rows": [{"metric": k.upper() if k != "smape" else "sMAPE", "value": accuracy[k]} for k in show]
+ [{"metric": f"Coverage of the {lv(level)}% interval", "value": accuracy.get(f"coverage_{lv(level)}")} for level in LEVELS if f"coverage_{lv(level)}" in accuracy],
}
)
tables.extend(extra_tables)
tables.append(
{
"key": "forecast",
"title": "Forecast",
"columns": ([{"key": "series", "label": "Series"}] if SERIES else [])
+ [{"key": "time", "label": TIME}, {"key": "mean", "label": "Forecast", "type": "number"}]
+ [c for level in LEVELS for c in ({"key": f"lo_{lv(level)}", "label": f"{lv(level)}% low", "type": "number"}, {"key": f"hi_{lv(level)}", "label": f"{lv(level)}% high", "type": "number"})],
"rows": [{k: v for k, v in r.items() if k not in ("t", "kind") and (SERIES or k != "series")} for r in forecasts[:200]],
}
)
summary = f"{values['model_label']}: {H}-step forecasts of {VALUE} ({freq_label} data, {n_obs} observations)."
if "mae" in accuracy:
summary += f" Backtest MAE {accuracy['mae']:.3g} over {n_origins} origin{'s' if n_origins != 1 else ''}."
cs.publish(
{
"title": "VAR / VECM",
"engine": cs.engine_info("numpy", "scipy", "numpy", "pandas"),
"n": n_obs,
"summary": summary,
"statistics": [{"key": k, "label": k.upper(), "value": accuracy[k]} for k in show[:3]],
"tables": tables,
"values": values,
"assumptions": extra_assumptions,
"warnings": warnings,
"notes": [],
"charts": charts,
"artifacts": artifacts,
}
)
The Granger table comes from the same model. The first series helps predict the second here: p < .001. It doesn't help predict the third: p = .311.
Look at Do one series' lags help predict another? Note that it says "predictive, not causal". Then find the impulse-response chart.
Trace a shock
ReadAn impulse response shows what the VAR expects to happen to each series after a one-off shock to one of them.
To shock "one series", you must separate correlated errors. CodeSplash's orthogonalized responses use a Cholesky decomposition, so the order of the series matters: the first one, Value, can affect all the others in the same period, and the last none.
The band comes from bootstrap draws, and it shows estimation uncertainty only, given the model and the order.
Change the order
ReflectA price and a demand series have correlated errors. You put price first, so a shock to price affects demand in that same month, but not the other way round.
Is that realistic for your data? If you reversed the order, and the answer changed a lot, what would you conclude?
An impulse response is a statement about this VAR and this order. It's only causal if your ordering assumption is true.
What drives forecast error?
ReadThe forecast error variance decomposition splits each series' forecast uncertainty into the shares from each shock. In What drives the forecast error, a large own share means the series mostly follows its own shocks.
On the road-casualty data, with petrol prices and seasonal dummies, the assumption row flags leftover dependence: p < .001. Don't lean on these shares until that's dealt with.
Levels, differences, or VECM?
PredictPredict first
Three series have unit roots, and Johansen's trace test gives a cointegrating rank of 1. Which model keeps the long-run relationship?
Reveal
A VECMVector error correction modelA VAR for cointegrated series. It adds terms that pull the series back when they drift from their long-run relationship. with rank 1. It models changes, and adds an error-correction term that pulls the series back toward their long-run relationship. Differencing alone throws that relationship away. With Cointegrating rank left at From the Johansen trace test, this model finds VECM(1 lags, rank 1).
Check your understanding
CheckpointCheck yourself
A VAR has series and lags. How many lag coefficients does it have in total?
Show the answer
Answer: 18
. Parameters add up fast, so VARs suit a few series with a decent number of rows.
Check yourself
Why does the order of the series matter for orthogonalized impulse responses?
Show the answer
Answer: b
The coefficients don't depend on order. The split of correlated errors does.
Check yourself
A VAR in levels has its largest root at a modulus of 0.999. What should you do?
Show the answer
Answer: a
So close to 1, shocks barely fade, so long-horizon responses and forecasts are very uncertain. This is a warning sign.
Do it in CodeSplash
In the appIn Forecast, choose VAR / VECM. Fill Value and Other series. The Series lab's Relationships step tells you which series may be worth including.
import pandas as pd
from statsmodels.tsa.api import VAR
from statsmodels.tsa.vector_ar.vecm import VECM
Y = pd.read_csv("three_series.csv")[["y1", "y2", "y3"]]
fit = VAR(Y).fit(maxlags=8, ic="aic")
print(fit.is_stable(), fit.test_causality("y1", ["y2"]).pvalue)
fit.irf(12).plot(orth=True)
vecm = VECM(Y, k_ar_diff=1, coint_rank=1, deterministic="co").fit()
print(vecm.alpha, vecm.beta)# install.packages(c("vars", "urca"))
library(vars)
Y <- read.csv("three_series.csv")[c("y1", "y2", "y3")]
fit <- VAR(Y, lag.max = 8, ic = "AIC", type = "const")
plot(irf(fit, n.ahead = 12))
fevd(fit, n.ahead = 12)
vec2var(urca::ca.jo(Y, K = 2, spec = "transitory"), r = 1)Recap
Recap- A VAR predicts each series from the lags of all, and its coefficients grow as .
- Impulse responses and variance shares depend on the ordering of the series, so state it.
- Check stability and leftover dependence first.
- For cointegrated series, a VECM keeps the long-run relationship.
Concepts in this lesson