Nowcast Dynamic Factor Model of US Gross Domestic Product
R2026bThis example shows how to nowcast economic variables, or predict them at the current or near future period, and to evaluate a nowcasting model for mixed frequency and jagged-edge economic data. The example nowcasts US gross domestic product (GDP) using a multivariate dynamic factor model (DFM) of it and other variables in standard state-space form. The example evaluates the quality of the nowcasting model by applying vintage analysis.
Economic policy decisions require timely assessments of current conditions, yet key macroeconomic indicators such as GDP are published with substantial delays—typically four to six weeks after the end of the reference quarter. This publication lag creates an information void during which policymakers, businesses, and investors must form views about the present state of the economy without direct observation of the target variable. Nowcasting addresses this gap by exploiting the relationships between the target series and higher-frequency indicators that are more readily available. Monthly series such as industrial production, retail sales, and consumer sentiment—and increasingly, daily or weekly financial and survey data—provide valuable signals about ongoing economic activity well before official statistics appear.
To integrate these mixed-frequency data sources into coherent real-time estimates, a range of econometric frameworks has been developed, including dynamic factor models (DFMs), mixed-data sampling (MIDAS) regressions, and state-space approaches[1][2]. These methods optimally combine timely but partial indicators to infer the current state of GDP and other target variables, and have become central tools for central banks and policy institutions where real-time insight is crucial for effective oversight. More recently, advances in machine learning—particularly recurrent architectures such as long short-term memory (LSTM) networks—have opened new avenues for capturing complex temporal patterns within high-frequency economic data[20].
Import and Organize Economic Data
Import and preprocess historical observations of the indicators in this table from the Federal Reserve Bank of St. Louis.
Variable | Description | Frequency |
All employees, total non-farm[16] | Monthly | |
Unemployment rate[19] | Monthly | |
Average weekly hours of production and non-supervisory employees, total private[4] | Monthly | |
Industrial production, total index[15] | Monthly | |
Consumer price index (CPI) for all urban consumers, all items in US city average[7] | Monthly | |
Commercial and industrial loans, all commercial banks[5] | Monthly | |
New privately-owned housing units started, total units[13] | Monthly | |
Real GDP[11] | Quarterly | |
Fixed private investment[10] | Quarterly | |
GDP, implicit price deflator[12] | Quarterly | |
Non-farm business sector, hourly compensation for all workers[6] | Quarterly | |
Personal consumption expenditures (PCE)[17] | Monthly | |
PCE: chain-type price index[18] | Monthly | |
Real disposable personal income[8] | Monthly | |
Federal funds effective rate[9] | Monthly | |
10-year high quality market (HQM) corporate bond spot rate[14] | Monthly |
Connect to the Federal Reserve Economic Data (FRED®) server by using the fredrs (Datafeed Toolbox) function. The function requires an active FRED API key to authenticate requests and retrieve data. Replace its placeholder value of the apikey variable in this code block with your FRED API key.
apikey = "placeholder";
f = fredrs(apikey);Fetch each indicator from the server and store the data in a timetable by using the local function localFetch (this function requires the Datafeed Toolbox™). Obtain observations from January 1, 2000 through December 31, 2024. Identify the frequency of each variable.
SeriesNames= ["PAYEMS" "UNRATE" "AWHNONAG" "INDPRO" "CPIAUCSL" ... "BUSLOANS" "HOUST" "GDPC1" "FPI" "GDPDEF" "COMPNFB" "PCE" "PCEPI" "DSPIC96" ... "FEDFUNDS" "HQMCB10YR"]; startdate = datetime(2000,1,1); enddate = datetime(2024,12,31); % Preallocate variables isMonthly = true(numel(SeriesNames),1); RawFredData = timetable; % Fetch data from FRED for i = 1:numel(SeriesNames) TT = localFetch(f,SeriesNames(i)); if days(diff(TT.Time(1:2))) < 40 TT.Time = dateshift(TT.Time,"end","month"); else TT.Time = dateshift(TT.Time,"end","quarter"); isMonthly(i) = false; end RawFredData = synchronize(RawFredData,TT,"union"); end
Reorganize the data by performing the following actions:
Shift the dates to occur at the start of the month.
Position the quarterly variables at the end of the table, with the response variable
GDPC1being at the last position.
Ensure all observations are within the desired sampling range.
DataTbl = RawFredData; DataTbl.Properties.DimensionNames(1) = "Date"; DataTbl.Date = dateshift(DataTbl.Date,"start","month"); varlist = SeriesNames(isMonthly); varlist = upper([varlist SeriesNames(~isMonthly)]); varlist(varlist == "GDPC1") = []; varlist(end+1) = "GDPC1"; DataTbl = DataTbl(:,varlist); range = [datetime(1999,1,1) datetime(2024,12,1)]; % 1999 first quarter to 2024 last quarter ind = DataTbl.Date >= range(1) & DataTbl.Date <= range(2); DataTbl = DataTbl(ind,:);
Stabilize Each Series
A DFM assumption is all series represented by it must fluctuate around a stable mean. Therefore, ensure all series in the state-space model are stationary, specifically, they have a constant mean and variance, and they do not have a deterministic trend.
The local function transformData accepts the input data as a numeric array, whether the series is monthly, and a string vector of transform IDs for transforms to apply to each input variable. This table contains the transform IDs, associated transformation, and the raw series behavior to which the transformation applies.
ID | Transformation | Series behavior |
|---|---|---|
| First different operator | Difference stationary |
| Percent change | Trend stationary |
"pca" | Percent change, annualized | Trend stationary, contextualized against monthly series |
Apply the transformations to the variables.
seriesID = varlist; nM = sum(isMonthly); nQ = sum(~isMonthly); isMonthly = true(nM+nQ,1); isMonthly(nM+1:end) = false; transform = ["chg" "chg" "pch" "pch" "pch" "pch" "pch" ... "pch" "pch" "pch" "chg" "chg" "pch" "pch" "pch" "pca"]; X = table2array(DataTbl); Xdata = transformData(X,isMonthly,transform); sampletimes = DataTbl.Date;
Specify Dynamic Factor Model as Standard State-Space Model
This example uses a linear Gaussian state-space model to describe the dynamics of the DFM system. One motivation behind using the state-space framework is the Kalman filter readily accommodates missing observations; rather than remove entire observations (periods of time) when at least one measurement is missing (list-wise deletion), the Kalman filter process updates state forecasts using the currently available information. In other words, missing measurements do not inform state estimation, but observed measurements can impact state estimation.
Define Dynamic Factor Model
Dynamic factor models (DFM) are the dominant approach for macroeconomic nowcasting within the state-space framework, particularly at central banks and international institutions[3]. A simple form of the DFM posits that observed economic indicators decompose into the following equation, which abstracts away mixed sampling frequencies of the measurements.
,
where:
is a vector of observed indicators at time , , where and (for example, GDP, employment, prices).
The sampling times are relative to the variable with the maximum sampling frequency (for example, the sampling frequency is monthly for a mix of monthly and quarterly data).
is the vector of unconditional means of the series.
is a vector of unobserved common factors at time , , where .
is a matrix of factor loadings.
is an vector of idiosyncratic errors at time , . The errors are mutually independent AR(1) processes.
The unobserved factors have this VAR representation
.
This example assumes has a VAR(4) representation, with lags 1 through 3 equal to 0, and that the factors are independent ( and are diagonal matrices).
Together, the equations form a state-space model, with as the measurements and as the states (the notation in this example mostly matches the notation in [3], but is different from the state-space model notation Econometrics Toolbox uses).
The DFM for this system has an factor loading structure, where each factor captures a different dimension of the economy.
Global factor — This factor represents the overall economic conditions and captures co-movement across all indicators. Because the factor applies to all variables, set each element of the column associated with the global factor to one in a matrix call
Lambda1.Real factor — This factor represents the contribution from physical economic activity: production, sales, construction. Measurements on industrial production, housing starts, and the GDP load the real factor, in other words, set each element associated with such measurements to one in the column of
Lambda1representing the real factor, and set all other elements to zero.Labor factor — This factor represents the contribution from employment conditions. Measurements on payroll, the unemployment rate, and average hours worked load the labor factor. Similar to the real factor, set elements of the column in
Lambda1associated with labor measurements to one, and set all other elements to zero.
Specify the structure of the factor loading matrix with the monthly series stacked over the quarterly series
,
where:
is the number of monthly series. The subscript identifies quantities associated with the monthly series.
is the number of quarterly series. The subscript identifies quantities associated with the quarterly series.
is the loading matrix for monthly indicators.
is the loading matrix for quarterly indicators.
The rows correspond to the series in seriesID (monthly series stacked on quarterly series) and the columns correspond to the global, real, and labor factors.
LambdaM = [
1 0 1
1 0 1
1 0 1
1 1 0
1 0 0
1 1 0
1 1 0
1 1 0
1 0 0
1 1 0
1 0 0
1 0 0];
LambdaQ = [
1 0 0
1 0 0
1 0 1
1 1 0];
Lambda1 =[LambdaM; LambdaQ];Elements of Lambda1 containing a 1 are parameters in the model, such that each loading describes the sensitivity of economic indicator to factor .
Represent Quarterly Measurements as Monthly
The DFM, as written, does not account for the missing observations of lower-frequency variables induced by mixed-frequency data. However, [3] proposes the following procedure to account for such missing data, specifically missing quarterly measurements when mixed with monthly series.
Choose the third month in a given quarter as the reference month to associate the observed quarterly values.
Express each quarterly measurement, in unit root levels, as the sum of the unobserved months that compose it at the reference month. For a quarterly series and reference month , , where are the associated unobserved monthly measurements.
Apply the first difference to the unobserved unit root monthly series . Because is monthly and stationary, it is represented in in the measurement equation of the DFM.
Apply the Mariano and Murasawa approximation [21] to the first difference of the quarterly series. Specifically, for quarterly series and at each reference month
Hence, the stationary quarterly series is represented as a linear combination of observed monthly values; you can think of the transformation as a weighted moving average. Make this result concrete by substituting from the measurement equation system.
.
This result changes the structure of the loading matrix and loading factor vector, which expands to a vector, to
,
where the elements 0 are appropriately sized matrices of zeros. Observe that the weights associated with the quarterly factor loading matrices match the weighting scheme resulting from the Mariano and Murasawa approximation.
Represent State-Space Model for ssm
The standard state-space model framework (ssm) of Econometrics Toolbox requires a state-space model in this form
,
where is the vector of states at time , are the measurements, contains measurement deflators, and are coefficient matrices, and and are covariance matrices associated with independent standard Gaussian error processes and .
Because the dynamic component required by ssm is in the state equation and the DFM contains a dynamic component () in the measurement equation, the DFM must be expressed differently to fit the requirements of the ssm framework. To accomplish this, treat the monthly and quarterly AR(1) idiosyncratic errors and as additional state vectors. Because the quarterly series use the Mariano and Murasawa approximation, you must include the lagged idiosyncratic errors for the quarterly series through lag 4. Thus, the state vector is
.
Measurement Equation
Following the Mariano and Murasawa approximation applied to the measurement equation, the observation loading matrix that accounts for the idiosyncratic error is
where:
is the collection of state-space model parameters.
is the identity matrix.
Hence, the measurement equation is
.
It has the form required by ssm.
State Equation
The state equation must represent the factor vector as a VAR(4) model and the idiosyncratic errors as independent AR(1) processes. To accomplish this goal, form the state-transition matrix and state-disturbance errors as follows:
where:
is the VAR model coefficient matrix.
is the identity matrix.
0 is an appropriately-sized block matrix of zeros.
1 is an appropriately-sized block matrix of ones.
As a result, the state equation has the form required by ssm
,
where
.
The local function paramMap specifies the structure of the standard state-space model. The inputs are:
, the is a vector of estimable model parameters
The maximum lag of and in the measurement equation
, the number of factors.
, the number of monthly series
, the number of quarterly series
, the pre-transformed factor loading matrix with monthly series loadings stacked on the quarterly series loadings.
Represent the DFM as a standard state-space model in MATLAB®. The function does not deflate the data by . Instead, you specify the data deflator when you estimate the model.
State-space model estimation requires initial parameter values. Select each initial value at random from the interval (0,1).
nLags = 4; nBlks = size(Lambda1,2); rng(1,"twister") % For reproducibility theta0 = randn(1,(nBlks+nM+nQ)*2+sum(Lambda1,"all")); % Initial values for theta mu0 = randn(1,nM+nQ); % Initial values for mu Mdl = ssm(@(x)paramMap(x,nLags,nBlks,nM,nQ,Lambda1));
Mdl is an ssm object representing the DFM.
Apply Vintage Analysis to Nowcasting Model
A key nowcasting challenge is that economic data is published on different schedules. This staggered data availability is characterized by periods where some indicators are available while others are not, which can impact estimation routines, forecasting, and model performance evaluation. In addition to the missing information, some high frequency observations are not published at the same time as others, which causes a "jagged-edge" at the end of the sample, where fewer observations are available. To realistically assess the performance of a nowcasting model, simulate staggered data and a jagged-edge by applying the data vintages process. Such simulations reflect the practical constraints faced by forecasters who must forecast using incomplete data; you can robustly evaluate models that include data vintage information because the process does not introduce future data revisions or hindsight bias.
A vintage analysis for nowcasting model evaluation follows these general steps:
Choose a historical date to nowcast. Call this date the target date.
Choose several monthly series to have the same missing-observations pattern as the quarterly series.
Choose a number of months around the target date to simulate times when information is yet to be published for the chosen monthly series and quarterly series. Call these dates the vintage dates. In this example, the vintages dates are:
Two months before the target date. This vintage date represents the information landscape two months before the target, when many indicators for the period are not yet available.
One month before the target date.
The month of the target date.
One month after the target date.
Two months after the target date. At this point, the most relevant economic indicators for the target period have been published.
Fit the DFM to the full data through to three months before the target date. This set is called the estimation data and the estimated model is the base model used to update the missing information.
Construct a data set containing all observations to the target date. For the chosen monthly series and quarterly series and for each vintage date, fill the missing months from the end of the series with
NaNvalues according to the vintage. Call these data sets the vintage data sets.Obtain baseline predictions by forecasting the model to the target date.
Obtain filtered state estimates of the indicators for each vintage data set at only the end of the data.
Compare the vintage estimates with the actual observations.
Consider nowcasting GDPC1 monthly from the 2022Q3 through 2024Q4. Create a vector of those target quarters and a vector of the number of months ahead and behind each quarter to nowcast for the vintage analysis.
series = "GDPC1";
idx_GDP = find(strcmpi(series,seriesID));
testDateRange = [datetime(2022,9,1) datetime(2024,12,1)];
testDates = testDateRange(1):calmonths(3):testDateRange(2);
vintagesettings = -2:2; Choose several series, arbitrarily, to have a month-lag in their publication dates. This example chooses PCE, PCEPI, DSPIC96, FPI, GDPDEF, and COMPNFB. Create a vector containing a nonnegative integer for each series in seriesID except for GDPC1, the value represents the number of months the publication date lags after its reference date (in this example, each have a one month lag).
lagsVar = ["PCE" "PCEPI" "DSPIC96" "FPI" "GDPDEF" "COMPNFB"]; dataPublishLag = double(ismember(seriesID(1:end-1),lagsVar)); % One-month lag for each series
Perform the remaining steps of the vintage analysis by looping over the target dates in testDates and performing the following steps:
Standardize the estimation data.
Fit the DFM to the standardized data. Supply the initial parameter values, a vector of ones to estimate the mean deflator , the OPG covariance estimation method, that the estimation display is off, the forecast uncertainty threshold is
1e-5, and use the univariate treatment of the multivariate model for computational efficiency.For each vintage date:
Create the vintage data.
Standardize the vintage data.
At the first vintage (2 months behind), forecast the current model for GDP to the target date and obtain the forecast error MSEs by using
forecast. Unstandardize the forecasts.At vintages greater than the first, obtain filter estimates at the final vintage by using
update. Unstandardize the filter estimates.Compute the absolute error of the GDP prediction.
% Preallocation Results = timetable; foreMSE = nan(1,length(testDates)); nPeriod = 3; for idx_date = 1:length(testDates) testTargetDate = testDates(idx_date); idx_est = (sampletimes >= range(1)) & (sampletimes < testTargetDate + calmonths(vintagesettings(1))); X = Xdata(idx_est,:); nT = size(X,1); Mx = mean(X,"omitnan"); Wx = std(X,"omitnan"); X = (X - Mx)./Wx; ZReg = ones(nT,1); [Mdl2,estParams] = estimate(Mdl,X,theta0,Beta0=mu0,Predictors=ZReg,CovMethod="opg", ... Display="off",Tolerance=1e-5,Univariate=true); mu = estParams((end - nM - nQ + 1):end); idx_dv = (sampletimes >= range(1)) & (sampletimes <= testTargetDate); Mx_new = Mx; Wx_new = Wx; for idx_vintage = 1:length(vintagesettings) vintage = vintagesettings(idx_vintage); X_new = Xdata(idx_dv,:); actual = X_new(end,idx_GDP); for ii = 1:(nM + nQ - 1) X_new((end - dataPublishLag(ii) + vintage):end,ii) = NaN; end X_new(end,idx_GDP) = NaN; nT_new = size(X_new,1); Zreg_new = ones(nT_new,1); X_new = (X_new - Mx_new)./Wx_new; if idx_vintage == 1 [pred,ymse] = forecast(Mdl2,nPeriod,X,Predictors0=ZReg,PredictorsF=ones(nPeriod,1),Beta=mu); pred = pred.*Wx + Mx; pred = pred(end,idx_GDP); ymse = ymse .* (Wx.^2); foreMSE(idx_date) = ymse(end,idx_GDP); else state = update(Mdl2,X_new,Predictors=Zreg_new,Beta=mu,Tolerance=1e-12); pred = (mu(idx_GDP) + Mdl2.C(idx_GDP,:)*state).*Wx_new(idx_GDP) + Mx_new(idx_GDP); end ResultI = timetable(testTargetDate,vintage,pred,actual,abs(pred-actual),VariableNames=["Vintage" "Pred" "Actual" "Error"]); pos = (idx_date - 1)*length(vintagesettings) + idx_vintage; Results(pos,:) = ResultI; Results.Time(pos) = ResultI.testTargetDate; end end
Warning: Numerical optimization does not return a convergence flag. Maximum likelihood estimation is less likely to succeed if starting parameter values are far from true values. Try different starting values, other optimization algorithms and settings. Also try to reparameterize the model and rescale the data.
Warning: Covariance matrix of estimators cannot be computed precisely due to inversion difficulty. Check parameter identifiability. Also try different starting values and other options to compute the covariance matrix.
Warning: Matrix is close to singular or badly scaled. Results may be inaccurate. RCOND = 1.767291e-19.
Warning: Numerical optimization does not return a convergence flag. Maximum likelihood estimation is less likely to succeed if starting parameter values are far from true values. Try different starting values, other optimization algorithms and settings. Also try to reparameterize the model and rescale the data.
Warning: Covariance matrix of estimators cannot be computed precisely due to inversion difficulty. Check parameter identifiability. Also try different starting values and other options to compute the covariance matrix.
Warning: Matrix is close to singular or badly scaled. Results may be inaccurate. RCOND = 1.190399e-18.
Warning: Numerical optimization does not return a convergence flag. Maximum likelihood estimation is less likely to succeed if starting parameter values are far from true values. Try different starting values, other optimization algorithms and settings. Also try to reparameterize the model and rescale the data.
Warning: Covariance matrix of estimators cannot be computed precisely due to inversion difficulty. Check parameter identifiability. Also try different starting values and other options to compute the covariance matrix.
Warning: Matrix is close to singular or badly scaled. Results may be inaccurate. RCOND = 1.760072e-20.
Warning: Numerical optimization does not return a convergence flag. Maximum likelihood estimation is less likely to succeed if starting parameter values are far from true values. Try different starting values, other optimization algorithms and settings. Also try to reparameterize the model and rescale the data.
Warning: Covariance matrix of estimators cannot be computed precisely due to inversion difficulty. Check parameter identifiability. Also try different starting values and other options to compute the covariance matrix.
Warning: Matrix is close to singular or badly scaled. Results may be inaccurate. RCOND = 6.847961e-19.
Warning: Numerical optimization does not return a convergence flag. Maximum likelihood estimation is less likely to succeed if starting parameter values are far from true values. Try different starting values, other optimization algorithms and settings. Also try to reparameterize the model and rescale the data.
Warning: Covariance matrix of estimators cannot be computed precisely due to inversion difficulty. Check parameter identifiability. Also try different starting values and other options to compute the covariance matrix.
Warning: Matrix is close to singular or badly scaled. Results may be inaccurate. RCOND = 2.948698e-19.
Warning: Numerical optimization does not return a convergence flag. Maximum likelihood estimation is less likely to succeed if starting parameter values are far from true values. Try different starting values, other optimization algorithms and settings. Also try to reparameterize the model and rescale the data.
Warning: Covariance matrix of estimators cannot be computed precisely due to inversion difficulty. Check parameter identifiability. Also try different starting values and other options to compute the covariance matrix.
Warning: Matrix is close to singular or badly scaled. Results may be inaccurate. RCOND = 1.524545e-19.
Warning: Numerical optimization does not return a convergence flag. Maximum likelihood estimation is less likely to succeed if starting parameter values are far from true values. Try different starting values, other optimization algorithms and settings. Also try to reparameterize the model and rescale the data.
Warning: Covariance matrix of estimators cannot be computed precisely due to inversion difficulty. Check parameter identifiability. Also try different starting values and other options to compute the covariance matrix.
Warning: Matrix is close to singular or badly scaled. Results may be inaccurate. RCOND = 1.030953e-18.
Warning: Numerical optimization does not return a convergence flag. Maximum likelihood estimation is less likely to succeed if starting parameter values are far from true values. Try different starting values, other optimization algorithms and settings. Also try to reparameterize the model and rescale the data.
Warning: Covariance matrix of estimators cannot be computed precisely due to inversion difficulty. Check parameter identifiability. Also try different starting values and other options to compute the covariance matrix.
Warning: Matrix is close to singular or badly scaled. Results may be inaccurate. RCOND = 4.458231e-19.
Warning: Numerical optimization does not return a convergence flag. Maximum likelihood estimation is less likely to succeed if starting parameter values are far from true values. Try different starting values, other optimization algorithms and settings. Also try to reparameterize the model and rescale the data.
Warning: Covariance matrix of estimators cannot be computed precisely due to inversion difficulty. Check parameter identifiability. Also try different starting values and other options to compute the covariance matrix.
Warning: Matrix is close to singular or badly scaled. Results may be inaccurate. RCOND = 1.113212e-18.
Warning: Numerical optimization does not return a convergence flag. Maximum likelihood estimation is less likely to succeed if starting parameter values are far from true values. Try different starting values, other optimization algorithms and settings. Also try to reparameterize the model and rescale the data.
Warning: Covariance matrix of estimators cannot be computed precisely due to inversion difficulty. Check parameter identifiability. Also try different starting values and other options to compute the covariance matrix.
Warning: Matrix is close to singular or badly scaled. Results may be inaccurate. RCOND = 4.983285e-19.
Optimization warnings can appear due to the high dimensionality of the parameter space and flatness of the likelihood near optima. However, the optimization issues do not necessarily affect the reliability of the nowcast estimates.
VintageResults = Results;
Assess Performance
For each target period, the model generates predictions under each of the five data vintages ranging from two months before to two months after the target period. Display the absolute error of each GDP prediction among the vintages.
disp(VintageResults)
Time Vintage Pred Actual Error
___________ _______ _______ _______ ________
01-Sep-2022 -2 2.7188 2.919 0.20017
01-Sep-2022 -1 3.3355 2.919 0.41645
01-Sep-2022 0 2.2905 2.919 0.62849
01-Sep-2022 1 2.4012 2.919 0.51786
01-Sep-2022 2 2.119 2.919 0.80004
01-Dec-2022 -2 3.1858 2.7897 0.39615
01-Dec-2022 -1 3.3948 2.7897 0.60509
01-Dec-2022 0 2.281 2.7897 0.50873
01-Dec-2022 1 1.3908 2.7897 1.3989
01-Dec-2022 2 1.4085 2.7897 1.3812
01-Mar-2023 -2 2.078 2.927 0.84898
01-Mar-2023 -1 4.1615 2.927 1.2345
01-Mar-2023 0 3.7256 2.927 0.79861
01-Mar-2023 1 3.1472 2.927 0.22019
01-Mar-2023 2 3.0364 2.927 0.10938
01-Jun-2023 -2 3.2684 2.5352 0.73316
01-Jun-2023 -1 3.5624 2.5352 1.0271
01-Jun-2023 0 3.1034 2.5352 0.56813
01-Jun-2023 1 2.3438 2.5352 0.19142
01-Jun-2023 2 2.5152 2.5352 0.020043
01-Sep-2023 -2 2.7628 4.6949 1.9321
01-Sep-2023 -1 3.1611 4.6949 1.5338
01-Sep-2023 0 2.6255 4.6949 2.0694
01-Sep-2023 1 2.5507 4.6949 2.1442
01-Sep-2023 2 2.6653 4.6949 2.0295
01-Dec-2023 -2 3.7504 3.4192 0.33122
01-Dec-2023 -1 2.6204 3.4192 0.79882
01-Dec-2023 0 2.7847 3.4192 0.6345
01-Dec-2023 1 2.0972 3.4192 1.322
01-Dec-2023 2 2.0894 3.4192 1.3298
01-Mar-2024 -2 2.9647 0.84209 2.1226
01-Mar-2024 -1 0.60017 0.84209 0.24193
01-Mar-2024 0 2.2846 0.84209 1.4425
01-Mar-2024 1 2.1768 0.84209 1.3347
01-Mar-2024 2 2.2947 0.84209 1.4526
01-Jun-2024 -2 4.034 3.5893 0.44473
01-Jun-2024 -1 2.7046 3.5893 0.88464
01-Jun-2024 0 2.9604 3.5893 0.62891
01-Jun-2024 1 2.9571 3.5893 0.63218
01-Jun-2024 2 2.8688 3.5893 0.72051
01-Sep-2024 -2 3.3224 3.3402 0.017708
01-Sep-2024 -1 1.6515 3.3402 1.6887
01-Sep-2024 0 1.8008 3.3402 1.5393
01-Sep-2024 1 1.5344 3.3402 1.8058
01-Sep-2024 2 1.6235 3.3402 1.7166
01-Dec-2024 -2 2.9882 1.8522 1.1359
01-Dec-2024 -1 2.2981 1.8522 0.44589
01-Dec-2024 0 1.9644 1.8522 0.11217
01-Dec-2024 1 2.4425 1.8522 0.59025
01-Dec-2024 2 2.3541 1.8522 0.50189
The results from the state-space model estimation and prediction are annualized rates. To ensure a fair comparison across different models, convert the results to quarterly rates. For each vintage, compute and display the MAE and RMSE, and plot the predicted quarterly GDP rates with the observed rates.
Results = VintageResults; Results.Pred = (Results.Pred/100 + 1).^0.25 - 1; Results.Actual = (Results.Actual/100 + 1).^0.25 - 1; disp(table(["2 months before";"1 month before"; "Month of";"1 month after"; "2 months after"], ... [mae(Results.Pred(1:5:end),Results.Actual(1:5:end)); ... mae(Results.Pred(2:5:end),Results.Actual(2:5:end)); ... mae(Results.Pred(3:5:end),Results.Actual(3:5:end)); ... mae(Results.Pred(4:5:end),Results.Actual(4:5:end)); ... mae(Results.Pred(5:5:end),Results.Actual(5:5:end))], ... VariableNames = ["Vintage" "DFM_MAE"]))
Vintage DFM_MAE
_________________ _________
"2 months before" 0.0019988
"1 month before" 0.0021696
"Month of" 0.0021866
"1 month after" 0.0024907
"2 months after" 0.0024672
disp(table(["2 months before"; "1 month before"; "Month of";"1 month after";"2 months after"], ... [rmse(Results.Pred(1:5:end),Results.Actual(1:5:end)); ... rmse(Results.Pred(2:5:end),Results.Actual(2:5:end)); ... rmse(Results.Pred(3:5:end),Results.Actual(3:5:end)); ... rmse(Results.Pred(4:5:end),Results.Actual(4:5:end)); ... rmse(Results.Pred(5:5:end),Results.Actual(5:5:end))], ... VariableNames=["Vintage" "DFM_RMSE"]))
Vintage DFM_RMSE
_________________ _________
"2 months before" 0.0026038
"1 month before" 0.0024427
"Month of" 0.002585
"1 month after" 0.0029452
"2 months after" 0.0029281
figure plot(Results.Time(1:5:end), ... [Results.Pred(1:5:end)*100,Results.Pred(2:5:end)*100,Results.Pred(3:5:end)*100, ... Results.Pred(4:5:end)*100,Results.Pred(5:5:end)*100,Results.Actual(1:5:end)*100]) xlabel("Time") ylabel("GDP Quarterly Growth Rate (%)") legend(["2 months before" "1 month before" "Month of" "1 month after" "2 months after" "Actual"], ... Location="best")

As the vintage moves from "2 months before" to "2 months after" the target quarter, more monthly indicators become available to inform nowcasts of GDP. Therefore, in theory, the forecast accuracy is expected to improve monotonically. However, a short evaluation sample and GDP data revisions introduce noise into vintage-level metrics.
Plot the forecast interval for the forecasts at 2-month before target quarter.
idx = sampletimes >= testDateRange(1) - calmonths(15) & sampletimes <= testDateRange(2);
plotData = Xdata(idx,idx_GDP);
times = sampletimes(idx);
idx = ~ismissing(plotData);
plotData = rmmissing(plotData);
times = times(idx);
plotData = (plotData/100 + 1).^0.25 - 1;
custom_fanplot(times,plotData*100,Results.Time(1:5:end), ...
Results.Pred(1:5:end)*100,((sqrt(foreMSE)/100+1).^0.25-1)*100)
Local Functions
You can call the functions in this section only in this script.
paraMap:Map state-space model parameters to coefficient matrices. For details, seessm.localFetch: Fetch data on variablesinFieldfrom the FRED server using connectionf, and return the data in a timetable.transformData: Transform variables in data setdataaccording to transformationstcode.custom_fanplot: Graph ad hoc, custom fan plot.
function [A,B,C,D,Mean0,Cov0,StateType] = paramMap(theta,nLags,nBlks,nM,nQ,blocks) % paramMap Parameter-to-matrix mapping function for ssm % For details, call "doc ssm". % % A, state-transition matrix A1 = diag(theta(1:nBlks)); iStart = nBlks; Ir = eye(nBlks); Alpha = diag(theta(iStart+1:iStart+nM)); iStart = iStart + nM; AlphaQ = diag(theta(iStart+1:iStart+nQ)); iStart = iStart + nQ; Iq = eye(nQ); A = zeros(nBlks*(nLags+1)+nM+nQ*(nLags+1)); A(1:nBlks,1:nBlks) = A1; for ii = 1:nLags A(ii*nBlks+1:(ii+1)*nBlks,(ii-1)*nBlks+1:ii*nBlks) = Ir; end ind = nBlks*(nLags+1)+(1:nM); A(ind,ind) = Alpha; ind = nBlks*(nLags+1)+nM+(1:nQ); A(ind,ind) = AlphaQ; aStart = nBlks*(nLags+1)+nM; for ii = 1:nLags A(ii*nQ+aStart+1:(ii+1)*nQ+aStart,(ii-1)*nQ+aStart+1:ii*nQ+aStart) = Iq; end % B, state-disturbance-loading coefficient matrix Bxt = diag(exp(theta(iStart+1:iStart+nBlks))); % Use exponential to allow unrestricted iStart = iStart + nBlks; BepM = diag(exp(theta(iStart+1:iStart+nM))); iStart = iStart + nM; BepQ = diag(exp(theta(iStart+1:iStart+nQ))); iStart = iStart + nQ; B = zeros(nBlks*(nLags+1)+nM+nQ*(nLags+1)); B(1:nBlks,1:nBlks) = Bxt; ind = nBlks*(nLags+1)+(1:nM); B(ind,ind) = BepM; ind = nBlks*(nLags+1)+nM+(1:nQ); B(ind,ind) = BepQ; % C, Measurement-sensitivity coefficient matrix weightMQ = zeros(nM+nQ,nBlks); for ii = 1:nM+nQ nW = sum(blocks(ii,:)); weightMQ(ii,logical(blocks(ii,:))) = theta(iStart+1:iStart+nW); iStart = iStart + nW; end C = zeros(nM+nQ,nBlks*(nLags+1)+nM+nQ*(nLags+1)); C(:,1:nBlks) = weightMQ; ind = nBlks*(nLags+1)+(1:nM); C(1:nM,ind) = eye(nM); coef = [1 2 3 2 1]; for ii = 2:nLags+1 C(nM+1:end,(ii-1)*nBlks+1:ii*nBlks) = weightMQ(nM+1:end,:)*coef(ii); end ind = nBlks*(nLags+1)+nM; for ii = 1:nLags+1 C(nM+1:end,ind+(ii-1)*nQ+1:ind+ii*nQ) = eye(nQ)*coef(ii); end % D, observation-innovation coefficient matrix D = 0; Mean0 = []; % Default initial state mean Cov0 = []; % Default initial state covariances StateType = zeros(nBlks*(nLags+1)+nM+nQ*(nLags+1),1); % All stationary states end function outData = localFetch(f,inField) % localFetch Fetch data from FRED server % Inputs: % f : FRED connection object % inField : String vector of series names % % Outputs: % outData : Timetable of fetched data % outData = series(f,inField,"observations"); outData = timetable(outData.observations{1}.date,outData.observations{1}.value,VariableNames=inField); end function Y = transformData(data,monthly,tcode) % transformData Apply transformation to each data series % % Inputs: % data : T x N matrix of raw time series data with N variables and T % observations % monthly : Length N logical vector identifying monthly series % tcode : Length N string vector. Supported transformations include: % * "chg" -- First difference % * "pch" -- Percent difference % * "pca" -- Annualized percent change % % Outputs: % Y : T x N matrix of transformed data % [nObs,nVar] = size(data); Y = NaN(nObs,nVar); for j = 1:nVar code = tcode(j); isMon = monthly(j); % Determine lag from frequency if isMon lag = 1; else lag = 3; end idx0 = lag; yrPct = lag/12; % Fraction of year for annualized rates switch code case "chg" Y(idx0:lag:nObs,j) = [NaN; data(idx0+lag:lag:nObs,j) - data(idx0:lag:nObs-idx0,j)]; case "pch" Y(idx0:lag:nObs,j) = 100*[NaN; data(idx0+lag:lag:nObs,j) ./ data(idx0:lag:nObs-idx0,j) - 1]; case "pca" Y(idx0:lag:nObs,j) = 100*[NaN; (data(idx0+lag:lag:nObs,j) ./ data(idx0:lag:nObs-lag,j)).^(1/yrPct) - 1]; end end end function custom_fanplot(histDates,histData,predDates,predData,rmse_val) % Z-scores for 95% intervals z_scores = [0.674, 1.96]; colors = [0.9 0.9 0.9; 0.8 0.8 0.8; 0.7 0.7 0.7]; interval_labels = ["50% Forecast Interval" "95% Forecast Interval"]; figure hold on % Ensure column vectors predDates = predDates(:); predData = predData(:); histDates = histDates(:); histData = histData(:); % Connect last historical point before predictions ind = find(histDates < predDates(1)); connectedDates = [histDates(ind(end)); predDates]; connectedData = [histData(ind(end)); predData]; % Plot the fan bands (largest to smallest) for i = numel(z_scores):-1:1 margin = z_scores(i)*rmse_val(:); % Create upper and lower bounds upper = [connectedData(1); connectedData(2:end) + margin]; lower = [connectedData(1); connectedData(2:end) - margin]; % Create filled polygon with proper label fill([connectedDates; flipud(connectedDates)], ... [upper; flipud(lower)], ... colors(i,:),EdgeColor="none",FaceAlpha=0.9, ... DisplayName=interval_labels(i)); end % Plot historical data plot(histDates,histData,"k-",LineWidth=1.5,DisplayName="Historical"); % Plot forecast line (connected to last historical point) plot(connectedDates,connectedData,"r--",LineWidth=1.5,DisplayName="Forecast"); hold off grid on xlabel("Date") ylabel("GDP Quarterly Growth Rate (%)") title("GDP Nowcast") legend(Location="best") end