メインコンテンツ

Nowcast Bayesian Dynamic Factor Model of US Gross Domestic Product

R2026b

This 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 Bayesian linear 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

PAYEMS

All employees, total non-farm[16]

Monthly

UNRATE

Unemployment rate[19]

Monthly

AWHNONAG

Average weekly hours of production and non-supervisory employees, total private[4]

Monthly

INDPRO

Industrial production, total index[15]

Monthly

CPIAUCSL

Consumer price index (CPI) for all urban consumers, all items in US city average[7]

Monthly

BUSLOANS

Commercial and industrial loans, all commercial banks[5]

Monthly

HOUST

New privately-owned housing units started, total units[13]

Monthly

GDPC1

Real GDP[11]

Quarterly

FPI

Fixed private investment[10]

Quarterly

GDPDEF

GDP, implicit price deflator[12]

Quarterly

COMPNFB

Non-farm business sector, hourly compensation for all workers[6]

Quarterly

PCE

Personal consumption expenditures (PCE)[17]

Monthly

PCEPI

PCE: chain-type price index[18]

Monthly

DSPIC96

Real disposable personal income[8]

Monthly

FEDFUNDS

Federal funds effective rate[9]

Monthly

HQMCB10YR

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 GDPC1 being 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

idx_est = DataTbl.Date >= range(1) & DataTbl.Date <= range(2);
DataTbl = DataTbl(idx_est,:);

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

"chg"

First different operator

Difference stationary

"pch"

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 Bayesian State-Space Model

This example uses a Bayesian linear state-space model to describe the dynamics of the DFM system, as described in [1]. 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]. This form of the DFM posits that observed economic indicators decompose into the following equation, which abstracts away mixed sampling frequencies of the measurements.

Xt=μ+ιgt+Λ1Ft+εtgt=gt-1+γgνgt,νgt∼N(0,1)εj,t=ρjεj,t-1+σεj,tej,t,ej,t∼N(0,1)

where:

  • Xt is a vector of n observed indicators at time t, xj,t , where j=1,...,n and t=1,...,T (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.

  • gt is the long-run growth trend for GDP and hourly consumption only (the final two response variables).

  • ι is a vector indicating which series have a long-term growth trend term.

  • Ft is a vector of r unobserved common factors at time t, fj,t, where j=1,...,r≪n.

  • Λ1 is a matrix of factor loadings.

  • εt is an vector of n idiosyncratic errors at time t, εj,t. The errors are mutually independent AR(1) processes.

  • σεj,t is the conditional standard deviation of idiosyncratic error εj,t.

The unobserved factors Ft have this VAR representation

Ft=A1Ft-1+⋯+ApFt-p+ut,ut∼N(0,Σu,t),

where Σu,t is the diagonal covariance matrix of the errors ut.

Together, the equations form a state-space model, with Xt as the measurements and Ft 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 r=3 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 Lamba1.

  • 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 Lamba1 representing 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 Lamba1 associated with labor measurements to one, and set all other elements to zero.

Specify the structure of the factor matrix with the monthly series stacked over the quarterly series

Λ1=[ΛMΛQ],

where:

  • nM is the number of monthly series. The subscript M identifies quantities associated with the monthly series.

  • nQ is the number of quarterly series. The subscript Q identifies quantities associated with the quarterly series.

  • ΛM is the nM×r loading matrix for monthly indicators.

  • ΛQ is the nQ×r loading matrix for quarterly indicators.

Also specify the long-term growth trend loading.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];
iota = zeros(1,nM + nQ);
iota(end-1:end) = 1;

Elements of Lambda1 containing a 1 are parameters in the model, such that each factor loading λjk describes the sensitivity of economic indicator j to factor k. Elements of iota containing a 1 are parameters in the model, such that each growth loading ιj is the time-varying trend of the corresponding series.

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.

  1. Choose the third month in a given quarter as the reference month to associate the observed quarterly values.

  2. 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 yQ,t and reference month t, yQ,t=yM,t+yM,t-1+yM,t-2, where yM,s,s={t,t-1,t-2} are the associated unobserved monthly measurements.

  3. Apply the first difference to the unobserved unit root monthly series ΔyM,t=yM,t-yM,t-1. Because ΔyM,t is monthly and stationary, it is represented in Xt in the measurement equation of the DFM.

  4. Apply the Mariano and Murasawa approximation [21] to the first difference of the quarterly series. Specifically, for quarterly series yQ,t and at each reference month t=3,6,9,...

ΔyQ,t=yQ,t-yQ,t-3≈(yM,t+yM,t-1+yM,t-2)-(yM,t-3+yM,t-4+yM,t-5)=ΔyM,t+2ΔyM,t-1+3ΔyM,t-2+2ΔyM,t-3+ΔyM,t-4.

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 ΔyQ,t=ΛQft+εQ,t from the measurement equation system.

ΔXM,t=μM+ιgt+ΛMft+εM,tΔXQ,t≈μQ+ιgt+ΛQft+2ΛQft-1+3ΛQft-2+2ΛQft-3+ΛQft-4+εQ,t-4+2εQ,t-1+3εQ,t-2+2εQ,t-3+εQ,t-4.

This result changes the structure of the loading matrix and loading factor vector, which expands to a 5r×1 vector, to

Λ2Ft=[ΛM0000ΛQ2ΛQ3ΛQ2ΛQΛQ][ftft-1ft-2ft-3ft-4],

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 bssm

The Bayesian linear state-space model framework (bssm) of Econometrics Toolbox requires a state-space model in this form

St=ASt-1+BηtMt=CSt+Dwt,

where St is the vector of states at time t, Mt are the measurements,A and C are coefficient matrices, and B′B and D′D are covariance matrices associated with independent standard error processes ηt and wt. μ contains measurement deflators, it is absorbed into C and A as a constant state. All model parameters have prior distributions and, when combined with the data likelihood, they have a posterior distribution.

Because the dynamic component required by bssm is in the state equation and the DFM contains a dynamic component (εt) in the measurement equation, the DFM must be expressed differently to fit the requirements of the bssm framework. To accomplish this, treat the monthly and quarterly AR(1) idiosyncratic errors εM,t and εQ,t, and the AR(1) trend gt, 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

αt=[gtgt-1gt-2gt-3gt-4ftft-1ft-2ft-3ft-4εM,tεQ,tεQ,t-1εQ,t-2εQ,t-3εQ,t-4μ].

Measurement Equation

Following the Mariano and Murasawa approximation applied to the measurement equation, the observation loading matrix that accounts for the idiosyncratic error is

Z(θ)=[ιM0000ΛM0000InM0000001ιQ2ιQ3ιQ2ιQιQΛQ2ΛQ3ΛQ2ΛQΛQ0InQ2InQ3InQ2InQInQ01],

where:

  • θ is the collection of state-space model parameters.

  • 0 is an appropriately-sized matrix or vector of zeros.

  • 1 is an appropriately-sized vector of ones.

  • Ik is the k×k identity matrix.

  • ιM is a vector of zeros in this example.

  • ιQ is zero for all series except for GDP and hourly consumption in this example.

Because the idiosyncratic and trend errors are modeled in the state equation, the measurement model is observed without error. Hence, the measurement equation is

Xt=Z(θ)αt+0wt.

It has the form required by bssm.

State Equation

This example assumes Ft has a VAR(4) representation. Therefore, 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 T(θ) and state-disturbance errors ηt as follows:

T(θ)=[1000000000000000000100000000000000000001000000000000000000010000000000000000000100000000000000000000A1A2A3A4000000000000000Ir0000000000000000000Ir0000000000000000000Ir0000000000000000000Ir00000000000000000000r0000000000000000000PM0000000000000000000PQ000000000000000000InQ0000000000000000000InQ0000000000000000000InQ0000000000000000000InQ00000000000000000000001],ηt=[νg0000uteM,teQ,t],

where:

  • Aj is the r×r lag j VAR model coefficient matrix.

  • Ik is the k×k identity matrix.

  • 0 is an appropriately-sized block matrix of zeros.

  • Pk=diag(ρ1,...,ρnk)

As a result, the state equation has the form required by bssm

αt=T(θ)αt-1+Bηt,

where

B=[γg00000000000000000000000000000000000000000000Σu1/20004r0000000000000Σε,M1/200000000Σε,Q1/20n+10000000],

where

  • γg is the scalar standard deviation of the random walk process gt.

  • Σu1/2=diag(σu,1,...,σu,r).

  • Σε,k1/2=diag(σε,1,...,σε,k).

  • 0k is a vector of k zeros.

Prior Distribution

A Bayesian state-space model requires prior distribution assumptions on all model parameters. This example uses the following prior distributions:

  • μ∼N(mμ,Σμ), where mμ is a vector of n zeros and Σμ=diag(100,...,100), an n-by-n diagonal matrix.

  • vec(Λ)∼N(mΛ,ΣΛ), where mΛ is a vector of rn zeros and Σμ=diag(4,...,4), an rn-by-rn diagonal matrix.

  • vec(Aj)∼N(mA,j,ΣA,j),j=1,...,4, where mAj is a length r2 vector composed of 0.75 and ΣA,j=diag(0.25,...,0.25), an r2-by-r2 diagonal matrix.

  • ρ∼N(mρ,Σρ), where ρ={ρ1,...,ρn} and each element is an independent, standard Gaussian variable.

  • γg∼IG(1.5,0.125), which is the inverse gamma distribution with shape 1.5 and scale 0.125.

  • σu,j2∼IG(1.5,2),j=1,...,r.

  • σε,j2∼IG(1.5,2),j=1,...,n.

Create Bayesian State-Space Model

The local function paramMap specifies the structure of the state-space model. The inputs are:

  • θ, the is a vector of estimable model parameters

  • r, the number of factors.

  • nm, the number of monthly series

  • nQ, the number of quarterly series

  • Λ1, the pre-transformed factor loading matrix with monthly series loadings stacked on the quarterly series loadings.

  • Number of lags in the VAR model of Ft.

  • Number of lags in the AR model of εt.

  • ι, the vector indicating which series have a long-term growth trend.

The local function priorDistribution specifies the prior distribution of the model parameters θ. The inputs are the same as paramMap, but without ι.

Represent the DFM as a standard and Bayesian state-space model in MATLAB®. The standard state-space model is required for nowcasting.

nLags = 4;
nLagsE = 1;
nBlks = size(Lambda1,2); 
Mdl = ssm(@(x)paramMap(x,nBlks,nM,nQ,Lambda1,nLags,nLagsE,iota));
BayesMdl = ssm2bssm(Mdl,@(x)priorDistribution(x,nBlks,nM,nQ,Lambda1,nLags,nLagsE));

BayesMdl is an bssm object representing the DFM, and Mdl is a standard state-space model.

State-space model estimation requires initial parameter values, and the Metropolis-Hastings Markov chain Monte Carlo algorithm, which simulate implements, requires a proposal scale matrix. High-quality initial parameter values and proposal scale matrices are critical for high-dimensional problems; experimentation is required to obtain them. For simplicity, this example provides predetermined initial values and a proposal scale matrix in NowcastBSSMTheta0Propoosal.mat. However, you can use tune and simulate to help you determine high-quality values.

load("NowcastBSSMTheta0Propoosal.mat")

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:

  1. Choose a historical date to nowcast. Call this date the target date.

  2. Choose several monthly series to have the same missing-observations pattern as the quarterly series.

  3. 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.

  4. 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.

  5. 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 NaN values according to the vintage. Call these data sets the vintage data sets.

  6. Obtain baseline predictions by forecasting the model to the target date.

  7. Obtain filtered state estimates of the indicators for each vintage data set at only the end of the data.

  8. 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:

  1. Standardize the estimation data.

  2. The estimation method is a Metropolis-Hastings sampler, which is a Markov chain Monte Carlo (MCMC) method. For only the first iteration of the loop, obtain a data-driven proposal distribution scale matrix by using the tune function. Turn off the estimation display, and specify the univariate treatment of the multivariate model for computational efficiency, the square-root filter, and the outer product of gradients method to approximate the Hessian of the proposal distribution scale matrix. Use the same proposal distribution scale matrix for the remaining iterations.

  3. Obtain the posterior distribution of the DFM by drawing a large sample from the posterior distribution of the Bayesian state-space model using the simulate function. Supply the standardized data, parameter estimates of the previous iteration as the initial parameter values, and the tuned proposal distribution scale matrix. Specify the univariate treatment of the multivariate model for computational efficiency and the square-root filter.

  4. For each parameter (row), compute the posterior parameter estimate by taking the mean of the Metropolis-Hastings sample.

  5. For each vintage date:

    1. Create the vintage data.

    2. Standardize the vintage data.

    3. Filtering data through a Bayesian linear state-space model is the same as filtering the same data through a standard linear state-space model at the given parameter values. Therefore, nowcast the Bayesian state-space model by filtering the vintage data through a standard state-space model at the Bayesian estimates using the standard state-space model function filter. Supply the posterior parameter estimates and set the RealTimeUpdate option to true. Unstandardize the filter estimates.

    4. Compute the absolute error of the GDP prediction.

The posterior estimation procedure involves taking a large MCMC sample from a large parameter space, and the data vintage analysis loops over 10 target dates. Therefore, the execution time of the procedure is high.

rng(1,"twister") % For reproducibility

% Preallocation
Results = timetable; 
foreMSE = nan(1,length(testDates));
options = optimoptions("fminunc",Display="off",MaxIterations=1000,MaxFunctionEvaluations=1e5);

for idx_date = 1:length(testDates)

    testTargetDate = testDates(idx_date);
    idx_est = (sampletimes >= range(1)) & (sampletimes < testTargetDate + calmonths(vintagesettings(1)));
    X = Xdata(idx_est,:);    

    Mx = mean(X,"omitnan");
    Wx = std(X,'omitnan');
    X = (X-Mx)./Wx;

    PostParams = simulate(BayesMdl,X,theta0,Proposal,SquareRoot=true,Univariate=true);
    estParams = mean(PostParams,2)';
    [A,B,C,D,Mean0,Cov0,StateType] = BayesMdl.ParamMap(estParams);

    theta0 = estParams;

    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; 

        Mx_new = Mx;
        Wx_new = Wx;
        X_new = (X_new-Mx_new)./Wx_new;

        state = filter(Mdl,X_new,params=estParams,SquareRoot=true,Univariate=true,RealTimeUpdate=true);
        pred = (C(idx_GDP,:)*state(end,:)').*Wx_new(idx_GDP) + Mx_new(idx_GDP);
        
        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.Properties.RowTimes(pos) = resultI.testTargetDate;
    end
end
VintageResults = Results;

Optimization warnings associated with the proposal distribution can appear due to the high dimensionality of the parameter space and flatness of the likelihood near optima. However, such optimization issues do not necessarily affect the reliability of the posterior or nowcast estimates.

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       -0.38945      2.919      3.3085
    01-Sep-2022      -1       -0.69085      2.919      3.6099
    01-Sep-2022       0        0.17431      2.919      2.7447
    01-Sep-2022       1         0.5633      2.919      2.3557
    01-Sep-2022       2         1.0008      2.919      1.9182
    01-Dec-2022      -2         2.0088     2.7897     0.78083
    01-Dec-2022      -1         1.3113     2.7897      1.4784
    01-Dec-2022       0         1.2674     2.7897      1.5223
    01-Dec-2022       1          1.154     2.7897      1.6357
    01-Dec-2022       2         1.0104     2.7897      1.7793
    01-Mar-2023      -2        0.11285      2.927      2.8141
    01-Mar-2023      -1         2.8956      2.927    0.031388
    01-Mar-2023       0         3.3808      2.927     0.45381
    01-Mar-2023       1         2.7757      2.927     0.15127
    01-Mar-2023       2         2.4692      2.927     0.45777
    01-Jun-2023      -2          2.453     2.5352    0.082225
    01-Jun-2023      -1         3.0738     2.5352     0.53854
    01-Jun-2023       0         2.1104     2.5352     0.42481
    01-Jun-2023       1         1.9524     2.5352     0.58281
    01-Jun-2023       2         2.4095     2.5352     0.12576
    01-Sep-2023      -2         1.1183     4.6949      3.5766
    01-Sep-2023      -1         2.9846     4.6949      1.7103
    01-Sep-2023       0         2.4071     4.6949      2.2878
    01-Sep-2023       1          2.598     4.6949      2.0969
    01-Sep-2023       2         2.7715     4.6949      1.9234
    01-Dec-2023      -2         3.7436     3.4192     0.32438
    01-Dec-2023      -1         2.0031     3.4192      1.4161
    01-Dec-2023       0         4.1079     3.4192     0.68873
    01-Dec-2023       1         3.2071     3.4192     0.21216
    01-Dec-2023       2         3.3675     3.4192    0.051765
    01-Mar-2024      -2         3.4918    0.84209      2.6497
    01-Mar-2024      -1         1.4117    0.84209     0.56958
    01-Mar-2024       0         4.6438    0.84209      3.8017
    01-Mar-2024       1           3.87    0.84209      3.0279
    01-Mar-2024       2          3.999    0.84209      3.1569
    01-Jun-2024      -2         2.6139     3.5893     0.97542
    01-Jun-2024      -1         2.1014     3.5893      1.4878
    01-Jun-2024       0         2.5536     3.5893      1.0357
    01-Jun-2024       1         2.2171     3.5893      1.3722
    01-Jun-2024       2         2.4848     3.5893      1.1044
    01-Sep-2024      -2          2.962     3.3402     0.37819
    01-Sep-2024      -1         1.6144     3.3402      1.7258
    01-Sep-2024       0         2.9008     3.3402     0.43933
    01-Sep-2024       1         2.4712     3.3402     0.86898
    01-Sep-2024       2         2.7273     3.3402      0.6129
    01-Dec-2024      -2         2.7012     1.8522     0.84899
    01-Dec-2024      -1          3.247     1.8522      1.3947
    01-Dec-2024       0         3.3359     1.8522      1.4836
    01-Dec-2024       1         4.2759     1.8522      2.4237
    01-Dec-2024       2           4.26     1.8522      2.4077

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.0038725
    "1 month before"     0.0034325
    "Month of"           0.0036488
    "1 month after"      0.0036115
    "2 months after"     0.0033183
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.0049986
    "1 month before"     0.0041151
    "Month of"           0.0045143
    "1 month after"      0.0042985
    "2 months after"     0.0041122
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.

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, see bssm.

  • priorDistribution: Log of the prior distribution of the state-space model parameters. Fore details, see bssm.

  • localFetch: Fetch data on variables inField from the FRED server using connection f, and return the data in a timetable.

  • transformData: Transform variables in data set data according to transformations tcode.

function [A,B,C,D,Mean0,Cov0,StateType] = paramMap(theta,nBlks,nM,nQ,Lambda,nLags,nLagsE,iota)
    % paramMap Parameter-to-matrix mapping function for bssm
    % For details, call "doc bssm".
    %
    
    nObs = nM + nQ;
    
    iota = iota(:);
    
    if nQ == 0
        nMQLags = 0; 
    else
        nMQLags = 4;
    end
    
    factorTnum = nMQLags + 1; 
    
    if nQ == 0        
        vec_q = 1;
    else       
        vec_q = [1  2  3  2  1];
    end
    
    % A, state-transition matrix
    %% Trend g
    Ag = [1 zeros(1,nMQLags) 
        eye(nMQLags) zeros(nMQLags,1)];
    
    %% Latent f
    Af = [reshape(theta(1:nLags*nBlks*nBlks),nLags*nBlks,nBlks)' zeros(nBlks,(factorTnum-nLags)*nBlks)
        eye(nMQLags*nBlks) zeros(nMQLags*nBlks,nBlks)];
    iStart = nLags*nBlks*nBlks;
    
    %% Error, monthly
    param = zeros(nM,nLagsE*nM);
    param(logical(repmat(eye(nM),1,nLagsE))) = reshape(theta((iStart + 1):(iStart + nLagsE*nM)),nLagsE,nM)';
    
    Aem = [param
        eye((nLagsE - 1)*nM) zeros((nLagsE - 1)*nM,nM)];
    iStart = iStart + nLagsE*nM;
    
    %% Error, quarterly
    param = zeros(nQ,factorTnum*nQ);
    param(logical(repmat(eye(nQ),1,nLagsE))) = reshape(theta((iStart + 1):(iStart + nLagsE*nQ)),nLagsE,nQ)';
    
    Aeq = [param
        eye(nMQLags*nQ) zeros(nMQLags*nQ,nQ)];
    iStart = iStart + nLagsE*nQ;
    
    A = blkdiag(Ag,Af,Aem,Aeq);
    
    % B, state-disturbance-loading coefficient matrix 
    paramB = theta((iStart + 1):(iStart + 1 + nBlks + nM + nQ));
    iStart = iStart + 1 + nBlks + nM + nQ;
    iem = nBlks + 2;
    ieq = nBlks + 2 + nM;
    
    B = blkdiag([paramB(1); zeros(nMQLags,1)], [diag(paramB(2:(nBlks + 1))); ...
        zeros(nMQLags*nBlks,nBlks)], ...
        [diag(paramB(iem:(ieq - 1)));zeros((nLagsE - 1)*nM,nM)], [diag(paramB(ieq:end)); ...
        zeros(nMQLags*nQ,nQ)]);
    
    % C, Measurement-sensitivity coefficient matrix
    weightMQ = zeros(nM + nQ,nBlks);
    for ii = 1:(nM + nQ)
        nW = sum(Lambda(ii,:));
        weightMQ(ii,logical(Lambda(ii,:))) = theta((iStart + 1):(iStart + nW));
        iStart = iStart + nW;
    end
    
    trendM = iota(1:nM);
    trendQ = iota((nM + 1):end);
    
    C = [trendM(:) zeros(nM,nMQLags) weightMQ(1:nM,:) zeros(nM,nMQLags*nBlks) ...
        eye(nM) zeros(nM,(nLagsE - 1)*nM) zeros(nM,factorTnum*nQ)];
    C = [C
        kron(vec_q,trendQ(:)) kron(vec_q,weightMQ((nM + 1):end,:)) zeros(nQ,nLagsE*nM) kron(vec_q,eye(nQ))];
    
    % D, observation-innovation coefficient matrix 
    D = 1e-4*eye(nObs);
    
    % Mu
    Mu = theta((iStart + 1):(iStart + nM + nQ));
    
    Mean0 = zeros(nBlks*factorTnum + factorTnum + nM*nLagsE + nQ*factorTnum,1); % Initial state mean
    StateType = zeros(nBlks*factorTnum + factorTnum + nM*nLagsE + nQ*factorTnum,1); % All stationary states
    
    A = blkdiag(A,1); % Include mu as a constant state
    B = [B; zeros(1,size(B,2))];
    C = [C Mu(:)];
    
    Mean0 = [Mean0; 1];
    Cov0 = eye(nBlks*factorTnum + factorTnum + nM*nLagsE + nQ*factorTnum + 1); % Initial state covariances
    Cov0(end,end) = 0;
    StateType = [StateType; 1]; % Include mu as a constant state
end

function logPrior = priorDistribution(theta,nBlks,nM,nQ,Lambda,nLags,nLagsE)
    % logPrior Prior distribution of the state-space model parameters
    % For details, call "doc bssm".
    %
    
    nObs = nM + nQ;
    invgampdf = @(x,a,b)exp(a.*log(b) - gammaln(a) - (a+1).*log(x) - (b./x));
    
    % A_j, VAR coefficients
    vecA = normpdf(theta(1:nLags*nBlks*nBlks)',0.75,0.5)';
    iStart = nLags*nBlks*nBlks;
    
    % rho, AR coefficients
    vecrho = normpdf(theta(iStart+1:iStart+nLagsE*nObs),0,1);
    iStart = iStart + nLagsE*nObs;
    
    % gamma_g, long-term trend variance
    gamma_g = invgampdf(theta(iStart+1),1.5,0.125);
    iStart = iStart + 1;
    
    % Sigma_u, factor variances
    sigma_u = invgampdf(theta(iStart++1:iStart+nBlks),1.5,2);
    iStart = iStart + nBlks;
    
    % Sigma_epsilon, AR error variances
    sigma_eps = invgampdf(theta(iStart+1:iStart+nObs),1.5,2);
    iStart = iStart + nObs;
    
    % Lambda, factor coefficients
    nW = sum(Lambda,"all");
    vecLambda = normpdf(theta(iStart+1:iStart+nW),0,2);
    iStart = iStart + nW;
    
    % Mu
    m_mu = 0;
    mu = normpdf(theta(iStart+1:end),m_mu,10);
    
    logPrior = sum(log([vecA vecrho gamma_g sigma_u sigma_eps vecLambda mu]));
    
    if isnan(logPrior) || ~isreal(logPrior)
        logPrior = -Inf;
    end
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

References

[1] Almuzara, Martin, Katie Baker, Hannah O'Keeffe, and Argia Sbordone. "The New York Fed Staff Nowcast 2.0." Report, Federal Reserve Bank of New York, Economic Research, June 2023. https://www.newyorkfed.org/medialibrary/media/research/blog/2023/NYFed-Staff-Nowcast_technical-paper.

[2] Bańbura, Marta, and Gerhard Rünstler. "A Look into the Factor Model Black Box." ECB Working Paper No. 1275, European Central Bank, Frankfurt, 2010.

[3] Bok, Brandyn, Daniele Caratelli, Domenico Giannone, Argia M. Sbordone, and Andrea Tambalotti. "Macroeconomic Nowcasting and Forecasting with Big Data." Annual Review of Economics 10, no. 1 (2018): 615–43. https://doi.org/10.1146/annurev-economics-080217-053214.

[4] Federal Reserve Bank of St. Louis. "Average Weekly Hours of Production and Nonsupervisory Employees, Total Private." FRED Economic Data. Last modified July 5, 2026. https://fred.stlouisfed.org/series/AWHNONAG.

[5] Federal Reserve Bank of St. Louis. "Commercial and Industrial Loans, All Commercial Banks." FRED Economic Data. Last modified July 5, 2026. https://fred.stlouisfed.org/series/BUSLOANS.

[6] Federal Reserve Bank of St. Louis. "Nonfarm Business Sector: Compensation Per Hour for All Workers." FRED Economic Data. Last modified July 5, 2026. https://fred.stlouisfed.org/series/COMPNFB.

[7] Federal Reserve Bank of St. Louis. "Consumer Price Index for All Urban Consumers: All Items in U.S. City Average." FRED Economic Data. Last modified July 5, 2026. https://fred.stlouisfed.org/series/CPIAUCSL.

[8] Federal Reserve Bank of St. Louis. "Real Disposable Personal Income." FRED Economic Data. Last modified July 5, 2026. https://fred.stlouisfed.org/series/DSPIC96.

[9] Federal Reserve Bank of St. Louis. "Federal Funds Effective Rate." FRED Economic Data. Last modified July 5, 2026. https://fred.stlouisfed.org/series/FEDFUNDS.

[10] Federal Reserve Bank of St. Louis. "Fixed Private Investment." FRED Economic Data. Last modified July 5, 2026. https://fred.stlouisfed.org/series/FPI.

[11] Federal Reserve Bank of St. Louis. "Real Gross Domestic Product." FRED Economic Data. Last modified July 5, 2026. https://fred.stlouisfed.org/series/GDPC1.

[12] Federal Reserve Bank of St. Louis. "Gross Domestic Product: Implicit Price Deflator." FRED Economic Data. Last modified July 5, 2026. https://fred.stlouisfed.org/series/GDPDEF.

[13] Federal Reserve Bank of St. Louis. "New Privately-Owned Housing Units Started: Total Units." FRED Economic Data. Last modified July 5, 2026. https://fred.stlouisfed.org/series/HOUST.

[14] Federal Reserve Bank of St. Louis. "10-Year High Quality Market (HQM) Corporate Bond Spot Rate." FRED Economic Data. Last modified July 5, 2026. https://fred.stlouisfed.org/series/HQMCB10YR.

[15] Federal Reserve Bank of St. Louis. "Industrial Production: Total Index." FRED Economic Data. Last modified July 5, 2026. https://fred.stlouisfed.org/series/INDPRO.

[16] Federal Reserve Bank of St. Louis. "All Employees, Total Nonfarm." FRED Economic Data. Last modified July 5, 2026. https://fred.stlouisfed.org/series/PAYEMS.

[17] Federal Reserve Bank of St. Louis. "Personal Consumption Expenditures." FRED Economic Data. Last modified July 5, 2026. https://fred.stlouisfed.org/series/PCE.

[18] Federal Reserve Bank of St. Louis. "Personal Consumption Expenditures: Chain-Type Price Index." FRED Economic Data. Last modified July 5, 2026. https://fred.stlouisfed.org/series/PCEPI.

[19] Federal Reserve Bank of St. Louis. "Unemployment Rate." FRED Economic Data. Last modified July 5, 2026. https://fred.stlouisfed.org/series/UNRATE.

[20] Hopp, D. "Economic Nowcasting with Long Short-Term Memory Artificial Neural Networks (LSTM)." UNCTAD Research Paper No. 62. Geneva: UNCTAD, 2021.

[21] Mariano, Roberto S., and Yasutomo Murasawa. "A New Coincident Index of Business Cycles Based on Monthly and Quarterly Series." Journal of Applied Econometrics 18, no. 4 (2003): 427–43. https://doi.org/10.1002/jae.695.

See Also

Objects

Functions

Topics