Skip to content

DForecasting · forecast.var

VAR / VECM

How will several series that move together continue, and how does a shock to one spread to the others?

A vector autoregression forecasts each series from the lags of all of them; a VECM adds long-run relationships for cointegrated series (rank from the Johansen trace test, or set by you). The forecast shown is for the Value series; the others appear in a table. Impulse responses (Cholesky, residual bootstrap on the shared stream), forecast error variance decompositions, Granger-type F tests, stability and an adjusted portmanteau test are included. Least squares in both engines, so Python and R agree to rounding.

Verified in Python and R Python and R agree to 10 decimals Seeded Also called VAR, VECM, vector autoregression…

A real result

Example “Sim var aic”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

VAR / VECMRecorded · Python and R agreeRecorded 2026-11-25 · 65 values compared
R

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

Plots

Forecast of y1Where is the series heading, and how uncertain is the forecast?
View data
hi_80hi_95kindlo_80lo_95monthy1
——actual——946,684,800,0001.490
——actual——949,363,200,0000.4667
——actual——951,868,800,000−0.7308
——actual——954,547,200,0000.5103
——actual——957,139,200,0001.109
——actual——959,817,600,0000.5950
——actual——962,409,600,0001.229
——actual——965,088,000,0003.016
——actual——967,766,400,0002.634
——actual——970,358,400,000−0.2967
——actual——973,036,800,000−0.1389
——actual——975,628,800,0000.3949
——actual——978,307,200,0001.686
——actual——980,985,600,0003.459
——actual——983,404,800,0002.717
——actual——986,083,200,0001.220
——actual——988,675,200,0001.473
——actual——991,353,600,0000.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,0001.117
——actual——1,004,572,800,000−0.3429
——actual——1,007,164,800,0001.032
——actual——1,009,843,200,0003.144
——actual——1,012,521,600,0001.903
——actual——1,014,940,800,0002.239
——actual——1,017,619,200,0002.363
——actual——1,020,211,200,0002.291
——actual——1,022,889,600,0002.483
——actual——1,025,481,600,0001.154
——actual——1,028,160,000,0001.490
——actual——1,030,838,400,0002.713
——actual——1,033,430,400,0004.160
——actual——1,036,108,800,0003.233
——actual——1,038,700,800,0002.103
——actual——1,041,379,200,0002.278
——actual——1,044,057,600,0000.4014
——actual——1,046,476,800,000−1.533
——actual——1,049,155,200,0000.6342
——actual——1,051,747,200,0002.731
——actual——1,054,425,600,0001.632
——actual——1,057,017,600,000−0.8263
——actual——1,059,696,000,0000.7748
——actual——1,062,374,400,0000.4315
——actual——1,064,966,400,0002.176
——actual——1,067,644,800,0002.361
——actual——1,070,236,800,0004.135
——actual——1,072,915,200,0002.901
——actual——1,075,593,600,0000.4129
——actual——1,078,099,200,0003.961
——actual——1,080,777,600,0001.131
——actual——1,083,369,600,0000.7565
——actual——1,086,048,000,0000.3064
——actual——1,088,640,000,0003.654
——actual——1,091,318,400,0003.362
——actual——1,093,996,800,0001.992
——actual——1,096,588,800,0004.333
——actual——1,099,267,200,0002.406
——actual——1,101,859,200,000−0.4051

First 60 of 246 rows.

Backtest errors by horizonHow does forecast error grow with the horizon, and how stable is it across origins?
View data
errorhorizonorigin
1.31012018-12-01
0.440122018-12-01
1.48932018-12-01
2.09942018-12-01
1.05452018-12-01
1.20262018-12-01
−0.309412019-06-01
1.81922019-06-01
0.792132019-06-01
0.273942019-06-01
1.72652019-06-01
3.43162019-06-01
Residual autocorrelationIs a series (or a model's residuals) autocorrelated, and at which lags?
View data
ACFboundlag
0.00360.12701
0.02380.12702
−0.02900.12703
0.05840.12704
0.00640.12705
−0.06270.12706
0.12120.12707
−0.00870.12708
−0.05390.12709
−0.03660.127010
0.10840.127011
0.00660.127012
0.06630.127013
−0.00010.127014
0.01860.127015
−0.05470.127016
0.00310.127017
0.12560.127018
−0.07050.127019
0.06770.127020
0.07600.127021
0.02980.127022
−0.00770.127023
0.03000.127024
Impulse responsesWhen one series gets a one-off shock, how do the others respond over the following periods?
View data
stepshighlowresponding seriesshockresponse
01.2031.051y1y11.143
000y1y20
000y1y30
00.53090.3343y2y10.4454
00.92040.7947y2y20.8640
000y2y30
00.25360.0930y3y10.1765
00.33520.1784y3y20.2670
00.82830.7170y3y30.7847
10.73910.5360y1y10.6506
10.2070−0.0032y1y20.0810
1−0.0131−0.1937y1y3−0.1031
10.62500.3969y2y10.5260
10.44990.2484y2y20.3642
10.0799−0.0876y2y30.0072
10.20750.0465y3y10.1273
10.19490.0471y3y20.1350
10.28600.1508y3y30.2273
20.30540.0993y1y10.2094
20.28620.0488y1y20.1620
20.0809−0.1427y1y3−0.0321
20.46270.2271y2y10.3674
20.23550.0186y2y20.1390
20.0888−0.0933y2y30.0221
20.26870.1032y3y10.1988
20.19550.0341y3y20.1156
20.31230.1397y3y30.2190
30.1407−0.0803y1y10.0489
30.22370.0037y1y20.1117
30.0821−0.1001y1y3−0.0056
30.25450.0265y2y10.1755
30.17770.0127y2y20.0902
30.0841−0.0657y2y30.0177
30.21570.0718y3y10.1517
30.12980.0316y3y20.0792
30.17800.0435y3y30.1029
40.0973−0.0710y1y10.0285
40.1006−0.0226y1y20.0463
40.0731−0.0571y1y30.0090
40.1454−0.0387y2y10.0728
40.12650.0024y2y20.0656
40.0726−0.0487y2y30.0194
40.16780.0437y3y10.1079
40.10350.0282y3y20.0655
40.15210.0125y3y30.0726
50.0847−0.0452y1y10.0248
50.0521−0.0197y1y20.0140
50.0432−0.0330y1y30.0073
50.0906−0.0258y2y10.0367
50.0813−0.0017y2y20.0380
50.0570−0.0306y2y30.0167
50.11030.0218y3y10.0696
50.07440.0170y3y20.0472
50.1010−5.391e-5y3y30.0428
60.0579−0.0167y1y10.0161
60.0374−0.0107y1y20.0063
60.0299−0.0231y1y30.0050
60.0650−0.0135y2y10.0245
60.0460−0.0031y2y20.0191
60.0429−0.0199y2y30.0125

First 60 of 117 rows.

Forecast error variance decompositionHow much of each series' forecast uncertainty comes from shocks to each series, at each horizon?
View data
steps aheadresponding seriesshockshare
1y1y11
1y1y20
1y1y30
1y2y10.2099
1y2y20.7901
1y2y30
1y3y10.0434
1y3y20.0993
1y3y30.8574
2y1y10.9902
2y1y20.0038
2y1y30.0061
2y2y10.3508
2y2y20.6492
2y2y33.800e-5
2y3y10.0589
2y3y20.1113
2y3y30.8298
3y1y10.9755
3y1y20.0180
3y1y30.0064
3y2y10.4043
3y2y20.5954
3y2y30.0004
3y3y10.0960
3y3y20.1137
3y3y30.7903
4y1y10.9689
4y1y20.0247
4y1y30.0064
4y2y10.4139
4y2y20.5855
4y2y30.0006
4y3y10.1163
4y3y20.1155
4y3y30.7682
5y1y10.9678
5y1y20.0258
5y1y30.0064
5y2y10.4147
5y2y20.5845
5y2y30.0008
5y3y10.1258
5y3y20.1174
5y3y30.7568
6y1y10.9676
6y1y20.0259
6y1y30.0064
6y2y10.4147
6y2y20.5843
6y2y30.0010
6y3y10.1296
6y3y20.1186
6y3y30.7518
7y1y10.9676
7y1y20.0259
7y1y30.0065
7y2y10.4148
7y2y20.5841
7y2y30.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)

MetricValue
MAE1.329
RMSE1.580
MAPE0.4174
sMAPE0.5513
MASE0.9367
WAPE0.4614
Coverage of the 80% interval0.6667
Coverage of the 95% interval0.9167

Lag order (lower is better)

LagsAICHQSCFPE
1−0.3640−0.2921−0.18570.6949
2−0.3960−0.2702−0.08400.6730
3−0.3694−0.18970.07630.6913
4−0.3188−0.08520.26060.7272
5−0.3003−0.01270.41280.7411
6−0.24630.09520.60060.7826
7−0.20680.18860.77370.8146
8−0.20430.24500.90990.8172

What drives the forecast error of y1

Steps aheady1y2y3
1100
20.99020.00380.0061
40.96890.02470.0064
60.96760.02590.0064
80.96760.02590.0065
120.96760.02590.0065
130.96760.02590.0065

Forecasts of the other series

SeriesSteps aheadForecastSE
y213.4380.9721
y222.6621.164
y232.0511.228
y241.7461.244
y251.6201.248
y261.5611.250
y310.89580.8474
y320.81470.8968
y330.53160.9514
y340.31420.9721
y350.14980.9830
y360.04460.9875

Do one series' lags help predict another? (predictive, not causal)

Lags ofPredictingFdfp
y2y12.2722310.1054
y3y11.0252310.3605
y1y211.9282311.175e-5
y3y20.38232310.6827
y1y31.1742310.3108
y2y30.53562310.5860

Forecast

monthForecast80% low80% high95% low95% high
2020-01-013.3381.8734.8031.0975.578
2020-02-012.2190.52523.913−0.37154.810
2020-03-011.8150.08703.543−0.82774.458
2020-04-011.722−0.01333.457−0.93184.375
2020-05-011.677−0.05993.413−0.97924.332
2020-06-011.638−0.09923.375−1.0194.294
Python

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)

MetricValue
MAE1.329
RMSE1.580
MAPE0.4174
sMAPE0.5513
MASE0.9367
WAPE0.4614
Coverage of the 80% interval0.6667
Coverage of the 95% interval0.9167

Lag order (lower is better)

LagsAICHQSCFPE
1−0.3640−0.2921−0.18570.6949
2−0.3960−0.2702−0.08400.6730
3−0.3694−0.18970.07630.6913
4−0.3188−0.08520.26060.7272
5−0.3003−0.01270.41280.7411
6−0.24630.09520.60060.7826
7−0.20680.18860.77370.8146
8−0.20430.24500.90990.8172

What drives the forecast error of y1

Steps aheady1y2y3
1100
20.99020.00380.0061
40.96890.02470.0064
60.96760.02590.0064
80.96760.02590.0065
120.96760.02590.0065
130.96760.02590.0065

Forecasts of the other series

SeriesSteps aheadForecastSE
y213.4380.9721
y222.6621.164
y232.0511.228
y241.7461.244
y251.6201.248
y261.5611.250
y310.89580.8474
y320.81470.8968
y330.53160.9514
y340.31420.9721
y350.14980.9830
y360.04460.9875

Do one series' lags help predict another? (predictive, not causal)

Lags ofPredictingFdfp
y2y12.2722310.1054
y3y11.0252310.3605
y1y211.9282311.175e-5
y3y20.38232310.6827
y1y31.1742310.3108
y2y30.53562310.5860

Forecast

monthForecast80% low80% high95% low95% high
2020-01-013.3381.8734.8031.0975.578
2020-02-012.2190.52523.913−0.37154.810
2020-03-011.8150.08703.543−0.82774.458
2020-04-011.722−0.01333.457−0.93184.375
2020-05-011.677−0.05993.413−0.97924.332
2020-06-011.638−0.09923.375−1.0194.294

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Sim var aicf7_var_sim · others: y2, y3 · time: month · value: y1
  • Granger manual trendts_granger · others: x, z · time: day · value: y
  • Coint vecm trace rankts_coint · others: x2, x3 · time: quarter · value: x1
  • Coint vecm rank2ts_coint · others: x1, x3 · time: quarter · value: x2
  • Seatbelts seasonal dummiesf7_seatbelts · others: petrol · time: month · value: drivers
  • Panel regionsf7_var_panel · others: y2 · series: region · time: month · value: y1
  • Sim experiment planf7_var_sim · others: y2, y3 · time: month · value: y1

In the guides

Where it sits in the decision guides

  • Time series (ARIMA, ETS) · DS & ML Decision Guide · Predict — forecast or classify outcomes
  • Probabilistic forecasting (Bayesian, deep ensembles) · DS & ML Decision Guide · Predict — forecast or classify outcomes

What you need

Timetemporal / numeric · 1 column
Dates or evenly spaced numbers; gaps are filled by linear interpolation.
Valuenumeric · 1 column
The series the forecast and backtest are reported for. It comes first in the Cholesky ordering.
Other seriesnumeric · 1–7 columns
The series modeled jointly with it, measured at the same times. Order matters for impulse responses: most exogenous first.
Seriescategorical · 0–1 column
Optional: one forecast per series (panel data in long format).

Choices you make

model

Modeldefault var

VAR for stationary series; VECM when wandering series share long-run relationships (check with the cointegration tests).

  • VAR (levels)(default) — Each series on the lags of all series.
  • VECM (cointegrated series) — Adds error-correction terms that pull the series back to their long-run relationships.
Lag orderdefault aic

How many lags to use: chosen by an information criterion on a common sample, or set by you.

  • AIC(default) — Tends to keep more lags; often best for forecasting.
  • Hannan–Quinn — Between AIC and SC.
  • Schwarz (SC, BIC) — Prefers fewer lags.
  • Final prediction error — Minimizes the estimated one-step forecast error variance.
  • Set the lags — Use the number of lags below.
Lagsdefault 2

Lags of every series in every equation.

Most lags to trydefault 8

The largest lag order the criterion considers (reduced when the sample is short).

Deterministic termsdefault const

What each equation includes besides lags. A VECM always has an unrestricted constant.

  • Constant(default) — A mean for each equation.
  • Trend — A linear trend, no constant.
  • Constant and trend — For series with deterministic growth.
  • None — Only lags: series centered on zero.
Seasonal dummiesdefault off

Add centered dummies for each season (uses the season length), so seasonality is not forced through the lags.

Cointegrating rankdefault —

How many long-run relationships to impose. Leave empty to use the trace test at 5%.

Impulse response stepsdefault 12

Steps after a shock to trace in the impulse responses and variance decomposition.

Bootstrap draws for the bandsdefault 200

Residual bootstrap draws for the impulse response bands (0 = no bands). More draws take longer.

Band level (%)default 90

Coverage of the impulse response bands.

options

Horizondefault 12

Steps ahead to forecast.

Interval levels (%)default 80,95

Coverage of the prediction intervals drawn around the forecast, in percent (80% and 95% by default).

Season lengthdefault —

Observations per seasonal cycle (12 monthly, 4 quarterly, 7 daily …); automatic reads the time steps.

validation

Backtest originsdefault 3

Refit on the data up to each origin and forecast the next horizon (0 = no backtest). The lag order and rank are chosen once on the whole series.

Origin spacingdefault —

Periods between backtest origins. Leave empty to step by the horizon, so the test windows don't overlap.

Advanced

Train fromdefault —

Leave out rows before this date or number, for example before a structural break. Empty uses every row.

Training windowdefault —

Train each backtest on only this many values before its origin (a sliding window). Empty uses all of them.

Backtest plandefault —

Set by forecast experiments: each origin's distance from the end of the series, shared by all their models.

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • The system is stable

    All companion-matrix roots inside the unit circle for a VAR; a VECM also has the unit roots it implies.

    • If violated → Fit a VECM — Roots beyond the unit circle usually mean the series wander. A VECM keeps them in levels and models their long-run relationships; check cointegration first.
  • Residuals look uncorrelated

    Adjusted portmanteau test across all series: a small p means dynamics remain, so try more lags.

    • If violated → Allow more lags — AIC tends to keep more lags than the other criteria, and a higher ceiling lets it reach longer dynamics.

What it reports

n_obs
How many independent units the analysis used; it sets precision and power.
horizon
How many periods ahead a forecast predicts; uncertainty grows with the horizon.
season
A pattern that repeats at a fixed period — daily, weekly, yearly.
n_series
How many series a run forecast. With a series column in long format, each one gets its own model and its own backtest.
fc_check
A single weighted average of the whole forecast, later steps counting more, so two runs or engines can be compared with one number.
irf_check
The path each series follows after a one-standard-deviation shock to one series, holding everything else at its fitted behavior.
fevd_check
The share of each series' forecast uncertainty that comes from shocks to each series, at each horizon.
others_fc_check
Each series is regressed on the lags of all the series, so they forecast each other. The lag order is chosen by an information criterion.
n_origins
How many points in the series a forecaster was refit from and scored against the values that followed.
filled
How many missing steps in the regular time grid were filled before fitting, so the series has no holes.
model_label
The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
freq_label
The spacing of the time grid the forecaster used (daily, weekly, monthly …), as a code and in words.
frequency
The spacing of the time grid the forecaster used (daily, weekly, monthly …), as a code and in words.

Per group, level or term: bt[<metric>], lag_order, max_root, a<l>_<i>_<j>, sigma_<i>_<j>, rank, beta_<i>_<r>, alpha_<i>_<r>, granger_p_<i>_<j>, irf_lo_check, irf_hi_check, irf_reps, portmanteau_q, portmanteau_p, <fact>[<series>], fc_lo_check, fc_hi_check

Python and R

Python and R agree to 10 decimals (relative tolerance 1e-8). Python uses numpy, scipy; R uses stats.

Default traps between the two languages

  • Both engines run the same twin (least squares by equation; reduced-rank regression with β normalized so its top block is the identity), and the bootstrap draws come from the shared Wichmann–Hill stream.
  • Forecast intervals use Σ with the degrees-of-freedom correction (Lütkepohl 3.2.19), as vars and statsmodels do. Coefficients, forecasts and their standard errors, lag criteria, impulse responses, variance decompositions, the adjusted portmanteau test and companion roots match vars and statsmodels (tests/crosscheck/s7_forecasters.R and .py).
  • The VECM rank from the trace test uses the jplv7 deterministic form of ts.cointegration; estimation uses Johansen's case with an unrestricted constant, and its level coefficients and forecasts match urca::ca.jo(spec = 'transitory') with vec2var.
Python

The exact script CodeSplash ran for example “Sim var aic” · 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,
    }
)
R

The exact script CodeSplash ran for example “Sim var aic” · 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
))

Sources

  • Lütkepohl H (2005). New Introduction to Multiple Time Series Analysis. Springer.
  • Johansen S (1988). Statistical analysis of cointegration vectors. Journal of Economic Dynamics and Control 12(2–3), 231–254.
  • Sims CA (1980). Macroeconomics and reality. Econometrica 48(1), 1–48.

From the CodeSplash method registry · forecast.var v1.0.0.