Main Content

Nowcast 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 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

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

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

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

Xt=μ+Λ1Ft+εtεj,t=ρjεj,t-1+ej,t,ej,t∼N(0,σj2),

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.

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

The unobserved factors Ft have this VAR representation

Ft=A1Ft-1+⋯+ApFt-p+ut,ut∼N(0,Q).

This example assumes Ft has a VAR(4) representation, with lags 1 through 3 equal to 0, and that the factors are independent (A1 and Q are diagonal matrices).

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 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 Lambda1 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 Lambda1 associated 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

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

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 λjk describes the sensitivity of economic indicator j to factor k.

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+ΛMft+εM,tΔXQ,t≈μQ+Λ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 ssm

The standard state-space model framework (ssm) of Econometrics Toolbox requires a state-space model in this form

St=ASt-1+BηtMt-μ=CSt+Dvt,

where St is the vector of states at time t, Mt are the measurements, μ contains measurement deflators,A and C are coefficient matrices, and B′B and D′D are covariance matrices associated with independent standard Gaussian error processes ηt and vt.

Because the dynamic component required by ssm 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 ssm framework. To accomplish this, treat the monthly and quarterly AR(1) idiosyncratic errors εM,t and εQ,t 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=[ftft-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(θ)=[ΛM0000InM00000ΛQ2ΛQ3ΛQ2ΛQΛQ0InQ2InQ3InQ2InQInQ],

where:

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

  • Ik is the k×k identity matrix.

Hence, the measurement equation is

Xt-μ=Z(θ)αt+0vt.

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 T(θ) and state-disturbance errors ηt as follows:

T(θ)=[A10000000000Ir00000000000Ir00000000000Ir00000000000Ir000000000000diag(ρM,1,…,ρM,nM)00000000000diag(ρQ,1,…,ρQ,nQ)000000000010000000000010000000000010000000000010],ηt=[ut0000etetQ0000],

where:

  • A1 is the r×r VAR model coefficient matrix.

  • Ir is the r×r 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

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

where

B=[Q00000000000000000000000000000000000000000000000000000000000diag(σM,1,…,σM,nM)00000000000diag(σQ,1,…,σQ,nQ)000000000000000000000000000000000000000000000000].

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 ft and εQ,t in the measurement equation

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

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:

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

  3. For each vintage date:

    1. Create the vintage data.

    2. Standardize the vintage data.

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

    4. At vintages greater than the first, obtain filter estimates at the final vintage by using update. Unstandardize the filter estimates.

    5. 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, see ssm.

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

  • 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

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