Nowcast Bayesian 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 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 |
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 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 |
|---|---|---|
| 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 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.
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 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.
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.
is the conditional standard deviation of idiosyncratic error .
The unobserved factors have this VAR representation
,
where is the diagonal covariance matrix of the errors .
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
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
Lamba1representing 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
Lamba1associated 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
,
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.
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 describes the sensitivity of economic indicator to factor . Elements of iota containing a 1 are parameters in the model, such that each growth loading 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.
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 bssm
The Bayesian linear state-space model framework (bssm) of Econometrics Toolbox requires a state-space model in this form
,
where is the vector of states at time , are the measurements, and are coefficient matrices, and and are covariance matrices associated with independent standard error processes and . contains measurement deflators, it is absorbed into and 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 () 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 and , and the AR(1) trend , 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.
0 is an appropriately-sized matrix or vector of zeros.
1 is an appropriately-sized vector of ones.
is the identity matrix.
is a vector of zeros in this example.
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
.
It has the form required by bssm.
State Equation
This example assumes 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 and state-disturbance errors as follows:
where:
is the lag VAR model coefficient matrix.
is the identity matrix.
0 is an appropriately-sized block matrix of zeros.
As a result, the state equation has the form required by bssm
,
where
,
where
is the scalar standard deviation of the random walk process .
.
.
is a vector of zeros.
Prior Distribution
A Bayesian state-space model requires prior distribution assumptions on all model parameters. This example uses the following prior distributions:
, where is a vector of zeros and , an -by- diagonal matrix.
, where is a vector of zeros and , an -by- diagonal matrix.
, where is a length vector composed of 0.75 and , an -by- diagonal matrix.
, where and each element is an independent, standard Gaussian variable.
, which is the inverse gamma distribution with shape 1.5 and scale 0.125.
.
.
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
, 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.
Number of lags in the VAR model of .
Number of lags in the AR model of .
, 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:
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.
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
tunefunction. 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.Obtain the posterior distribution of the DFM by drawing a large sample from the posterior distribution of the Bayesian state-space model using the
simulatefunction. 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.For each parameter (row), compute the posterior parameter estimate by taking the mean of the Metropolis-Hastings sample.
For each vintage date:
Create the vintage data.
Standardize the vintage data.
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 theRealTimeUpdateoption totrue. Unstandardize the filter estimates.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, seebssm.priorDistribution: Log of the prior distribution of the state-space model parameters. Fore details, seebssm.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.
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