import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import statsmodels.api as sm
from statsmodels.tsa.api import VARUnemployment rate, Inflation, and Federal Funds Rate Example¶
Consider the three time series downloaded from FRED: UNRATE (Unemployment Rate; monthly), PCEPI (PCE Price Index;monthly), FEDFUNDS (monthly). We shall fit a VAR model to these time series (after differencing the PCEPI dataset).
unrate = pd.read_csv("UNRATE_19Nov2026.csv", index_col=0, parse_dates=True)["UNRATE"]
pcepi = pd.read_csv("PCEPI_19Nov2026.csv", index_col=0, parse_dates=True)["PCEPI"]
fedfunds = pd.read_csv("FEDFUNDS_19Nov2026.csv", index_col=0, parse_dates=True)["FEDFUNDS"]All these are monthly datasets; but the months for which data is available differs among the three datasets.
print("Unemployment rate")
print(unrate.head())
print(unrate.tail())
print("\nPCE price index")
print(pcepi.head())
print(pcepi.tail())
print("\nFederal funds rate")
print(fedfunds.head())
print(fedfunds.tail())Unemployment rate
observation_date
1948-01-01 3.4
1948-02-01 3.8
1948-03-01 4.0
1948-04-01 3.9
1948-05-01 3.5
Name: UNRATE, dtype: float64
observation_date
2026-06-01 4.2
2026-07-01 4.1
2026-08-01 4.1
2026-09-01 4.2
2026-10-01 4.1
Name: UNRATE, dtype: float64
PCE price index
observation_date
1959-01-01 15.164
1959-02-01 15.179
1959-03-01 15.189
1959-04-01 15.219
1959-05-01 15.227
Name: PCEPI, dtype: float64
observation_date
2026-05-01 131.241
2026-06-01 131.106
2026-07-01 131.187
2026-08-01 131.611
2026-09-01 132.257
Name: PCEPI, dtype: float64
Federal funds rate
observation_date
1954-07-01 0.80
1954-08-01 1.22
1954-09-01 1.07
1954-10-01 0.85
1954-11-01 0.83
Name: FEDFUNDS, dtype: float64
observation_date
2026-06-01 3.63
2026-07-01 3.63
2026-08-01 3.63
2026-09-01 3.75
2026-10-01 3.88
Name: FEDFUNDS, dtype: float64
Below we plot the three series.
fig, ax = plt.subplots(3, 1, figsize=(11, 7), sharex=True)
ax[0].plot(unrate)
ax[0].set_title("Unemployment rate (%)")
ax[1].plot(pcepi)
ax[1].set_title("PCE price index")
ax[2].plot(fedfunds)
ax[2].set_title("Federal funds rate (%)")
ax[2].set_xlabel("Year")
fig.tight_layout()
plt.show()
For the VAR, we shall work with , and . We will keep the data from February 1959 to September 2025 (Unemployment rate seems to be missing for October 2025; so we will limit our data to September 2025). represents inflation rate; so it is a natural variable to study along with unemployment rate and the federal funds interest rate.
var_data = pd.DataFrame({
"y1": unrate,
"y2": 1200 * np.log(pcepi).diff(),
"y3": fedfunds
}).asfreq("MS")
# Keep the 800 consecutive months with complete observations
var_data = var_data.loc["1959-02":"2025-09"]
y1 = var_data["y1"]
y2 = var_data["y2"]
y3 = var_data["y3"]
print(var_data.head())
print(len(var_data), "months") y1 y2 y3
observation_date
1959-02-01 5.9 1.186435 2.43
1959-03-01 5.6 0.790306 2.80
1959-04-01 5.2 2.367799 2.96
1959-05-01 5.1 0.630625 2.90
1959-06-01 5.0 3.462525 3.39
800 months
Below is the plot of y1, y2, y3.
fig, ax = plt.subplots(3, 1, figsize=(12, 7), sharex=True)
ax[0].plot(y1)
ax[0].set_title("Unemployment rate (%)")
ax[1].plot(y2)
ax[1].axhline(0, color="gray", linewidth=0.8)
ax[1].set_title("Monthly PCE inflation (annualized %)")
ax[2].plot(y3)
ax[2].set_title("Federal funds rate (%)")
ax[2].set_xlabel("Year")
fig.tight_layout()
plt.show()
We now fit the VAR(1) model to the data, using the VAR function from statsmodels.
var1 = VAR(var_data).fit(1)
print("Estimate of the intercept:", var1.intercept)
print("Estimate of A1:")
print(var1.coefs[0])Estimate of the intercept: [0.16227219 0.21917971 0.15176785]
Estimate of A1:
[[ 0.96798842 -0.01261336 0.01337334]
[ 0.0523748 0.59286271 0.16276692]
[-0.02385082 0.02900276 0.97857246]]
The fitted VAR(1) equations are
The third equation can be rewritten as follows (note ) $$ \begin{aligned} y_{3,t} - y_{3,t-1} &= 0.15176785 - 0.02385082,y_{1,t-1} + 0.02900276,y_{2,t-1}
0.02142754,y_{3,t-1} \ &= 0.02142754 \left( \frac{0.15176785 - 0.02385082,y_{1,t-1} + 0.02900276,y_{2,t-1}} {0.02142754}
y_{3,t-1} \right) \ &\approx 0.02142754 \left( 7.08284 - 1.11309,y_{1,t-1} + 1.35353,y_{2,t-1} - y_{3,t-1} \right). \end{aligned} $$
The model predicts that each month the federal funds rate closes about of the gap between last month’s rate and the target or reference rate .
Here is more intuition behind the target rate equation:
The two coefficients capture the main intuition behind the Fed’s interest rate decisions.
Higher inflation raises the target rate. Holding unemployment fixed, a one-percentage-point higher inflation reading raises the target by about 1.35 percentage points. Higher interest rates make borrowing more expensive, which can slow spending and ease upward pressure on prices.
Higher unemployment lowers the target rate. Holding inflation fixed, a one-percentage-point higher unemployment rate lowers the target by about 1.11 percentage points. Lower interest rates can encourage households to spend and businesses to invest, supporting demand and hiring.
The target tells us which way the model predicts the funds rate will move. If last month’s funds rate was below the target, the model predicts an increase. If it was above the target, the model predicts a decrease. The adjustment is gradual: the predicted change closes about 2.14% of the gap in one month.
We call this target model-implied because it is inferred from historical data. The Fed sets its official target range using a broader assessment of the economy.
As a simple example, suppose last month’s unemployment rate was 5% and annualized monthly PCE inflation was 2%. Then the model-implied target for the federal funds rate is 4.22%, using the more precise coefficient estimates calculated as . If last month’s federal funds rate was below this reference rate, the VAR predicts an increase this month. If it was above this reference rate, the VAR predicts a decline.
The Inflation Equation¶
Let us now consider the second equation (for inflation)
The coefficient of is positive, which seems to suggest that an increase in the federal interest rate leads to an increase in inflation as opposed to a decrease.
Below, let us fit a regression for on for a fixed , without the other terms . Even here, we see positive coefficients (for all ).
p = 1
print(sm.OLS(y2, sm.add_constant(y3.shift(p)), missing="drop").fit().params)const 1.206813
y3 0.416884
dtype: float64
Below we plot the estimated coefficients for the regression of on for each fixed value of .
lags = range(1, 21)
slopes = []
# Fit a separate regression for each lag, using all available pairs
for p in lags:
lag_y3 = y3.shift(p).rename("lag_y3")
fit = sm.OLS(y2, sm.add_constant(lag_y3), missing="drop").fit()
slopes.append(fit.params["lag_y3"])
plt.figure(figsize=(10, 4))
plt.plot(lags, slopes, "o-")
plt.axhline(0, color="gray", linestyle="--")
plt.xticks(lags)
plt.xlabel("Lag $p$ (months)")
plt.ylabel("Fitted slope")
plt.title(r"Regression of inflation $y_2(t)$ on the federal funds rate $y_3(t-p)$")
plt.tight_layout()
plt.show()
It is clear that the coefficient is positive for all values of .
Inflation after a federal funds rate shock (Impulse Response)¶
For the fitted VAR(1) model, we can check how a one-time, one-percentage-point shock to FEDFUNDS changes predicted inflation months later, compared with the forecast from the same starting values with no shock. This is called impulse response analysis.
The idea here is that it is technically possible for inflation to come down a few months after the interest rate increase, instead of immediately after. Impulse response analysis shows that this is not the case in this problem.
The impulse response analysis can be computed in two ways. One is to use the statsmodels function irf. The other is to take the fitted VAR(1) coefficient matrix , and then compute recursively . After months, the responses of unemployment, inflation, and the federal funds rate (to the federal funds rate shock) are the three components of . Since inflation is the second variable, its response is the second component, , measured in percentage points of annualized monthly PCE inflation.
The plot below shows this inflation response for . The line is computed from the matrix powers, and the circles are computed by statsmodels. They agree up to numerical precision.
H = 24
A = var1.coefs[0]
months = range(H + 1)
inflation_response_1 = np.array([np.linalg.matrix_power(A, h)[1, 2] for h in months])
inflation_response_2 = var1.irf(H).irfs[:, 1, 2]
print("Largest absolute difference =", np.max(np.abs(inflation_response_1 - inflation_response_2)))
print("Match within tolerance =", np.allclose(inflation_response_1, inflation_response_2,
atol=1e-12, rtol=0))
plt.figure(figsize=(9, 4))
plt.plot(months, inflation_response_1, label=r"Matrix powers $(A^h)_{2,3}$")
plt.plot(months, inflation_response_2, "o", fillstyle="none", label="statsmodels IRF")
plt.xlabel("Months after the funds rate shock")
plt.ylabel("Inflation response (percentage points)")
plt.xticks(months)
plt.legend()
plt.tight_layout()
plt.show()Largest absolute difference = 5.551115123125783e-17
Match within tolerance = True

The impulse responses are all positive, which shows that, for the fitted VAR(1) model, the inflation is predicted to go up even after multiple months following an interest rate spike.
This pattern is sometimes called the price puzzle. The Fed raises interest rates to cool demand and bring inflation down over time. Yet in our fitted VAR(1), a one-percentage-point upward shock to the federal funds rate predicts higher subsequent inflation. Twelve months after the shock, the forecast for annualized monthly PCE inflation is about 0.36 percentage points above the no-shock forecast.
One possible explanation is that the Fed sees inflationary pressures building before they show up in the data used by the VAR. A rate hike can then signal that higher inflation is coming, even if the hike itself keeps inflation lower than it otherwise would have been.
This can be easily illustrated with a simple toy example.
Bike Example (Speed and Braking while Biking downhill)¶
We simulate a cyclist riding downhill for seconds, indexed by . For each second , we record three quantities.
is the cyclist’s speed at the beginning of second .
is the amount of speed removed by braking during second .
is the amount of speed the cyclist would gain from gravity during second if they coasted. A steeper downhill slope gives a larger .
Since the first second is labeled , we write the starting speed as . We simulate the ride according to
where the are independent draws from , independent of the sequence . We use .
The braking rule describes how the cyclist responds to the slope of the hill. The cyclist brakes harder on steeper stretches, aiming to cancel about half the speed they would gain by coasting. On a gentle stretch where gravity would add 0.06 units of speed, braking removes about 0.03. On a steeper stretch where gravity would add 0.10, braking removes about 0.05. The term allows for small variations in how firmly the cyclist applies the brakes. In the second example, the amount removed can range from 0.049 to 0.051.
The speed equation says that the cyclist starts the second at speed , loses from braking, and gains from gravity.
The simulation gives observations for . In the last observation, is the speed at the beginning of the final second. The last update gives the finishing speed .
seed = 248
n = 120
brake_variation = 0.001
rng = np.random.default_rng(seed)
G = rng.uniform(0.04, 0.12, size = n)
eta = rng.uniform(-brake_variation, brake_variation, size = n)
B = np.empty(n)
V = np.empty(n + 1)
V[0] = 10
for i in range(n):
# During second i + 1, the cyclist starts at speed V[i].
B[i] = 0.5 * G[i] + eta[i]
V[i + 1] = V[i] + G[i] - B[i]Below we plot the three time series .
plt.figure(figsize = (12, 7))
top = plt.subplot(3, 1, 1)
plt.plot(G, color = 'blue', label = 'Hill gain G (mph)')
plt.legend(loc = 'upper right')
plt.subplot(3, 1, 2, sharex = top)
plt.plot(V, color = 'green', label = 'Speed V (mph)')
plt.legend(loc = 'upper right')
plt.subplot(3, 1, 3, sharex = top)
plt.plot(B, color = 'orange', label = 'Braking B (mph)')
plt.legend(loc = 'upper right')
plt.xlabel('Time (seconds)')
plt.tight_layout()
plt.show()
Suppose we observe only speed and braking. Below we perform a regression of on and .
bikedata = np.column_stack([V[:-1], B])
y = bikedata[1:, 0] # V_t
X = sm.add_constant(bikedata[:-1, :]) # Intercept, V_{t-1}, B_{t-1}
fit = sm.OLS(y, X).fit()
print("V_t regression")
for term, coef, se in zip(["Intercept", "V[t-1]", "B[t-1]"], fit.params, fit.bse):
print(f" {term:9s} {coef: .5f} (SE {se:.5f})")V_t regression
Intercept -0.00053 (SE 0.00099)
V[t-1] 1.00012 (SE 0.00008)
B[t-1] 0.97961 (SE 0.00878)
The fitted regression equation is:
A naive interpretation of the coefficient 0.98 on is that, for a given starting speed , braking harder causes the cyclist to go faster one second later. This is the opposite of what we expect braking to do. The surprising positive sign parallels the price puzzle in monetary policy, with braking playing the role of the interest rate and speed playing the role of the inflation rate.
The regression holds the starting speed fixed, but it leaves out the slope of the hill. Since the cyclist brakes harder on steeper stretches, observing more braking also tells us that gravity probably contributed a larger gain in speed during that second.
To see this algebraically, the braking rule gives
The change from to occurs during second , so we use the braking and gravity terms from that second. Substituting into the speed equation gives
This explains why the fitted coefficient on is close to +1. Across stretches of the hill, an additional 0.01 units of speed removed by braking typically goes along with about 0.02 units of additional speed gained from gravity. The cyclist therefore gains about 0.01 more speed on the steeper stretch, even after braking harder.
On a fixed slope, the comparison is different. With and held fixed, any additional braking reduces by exactly the amount of speed removed. Including in the regression recovers this coefficient of -1 on braking.
Below we regress on . In this case, the effect of braking on speed is correctly recovered.
# Each row contains speed, braking, and gravity for the same second.
bikedata3 = np.column_stack([V[:-1], B, G])
y = bikedata3[1:, 0] # V_t
X = sm.add_constant(bikedata3[:-1, :]) # Intercept, V_{t-1}, B_{t-1}, G_{t-1}
fit_all = sm.OLS(y, X).fit()
terms = ["Intercept", "V[t-1]", "B[t-1]", "G[t-1]"]
print("V_t regression")
for term, coef, se in zip(terms, fit_all.params, fit_all.bse):
print(f" {term:9s} {coef: .5f} (SE {se:.5f})")V_t regression
Intercept -0.00000 (SE 0.00000)
V[t-1] 1.00000 (SE 0.00000)
B[t-1] -1.00000 (SE 0.00000)
G[t-1] 1.00000 (SE 0.00000)
Another scenario in which the braking effect would be correctly recovered is if braking does not follow the very specific rule and instead if it were random.
seed = 248
n = 120
rng = np.random.default_rng(seed)
G = rng.uniform(0.04, 0.12, size=n)
B = rng.uniform(0.02, 0.06, size=n) # Random braking, independent of the slope
V = np.empty(n + 1)
V[0] = 0
for t in range(n):
V[t + 1] = V[t] + G[t] - B[t]
# Use the same 1,199 transitions as the original VAR(1).
bikedata = np.column_stack([V[:-1], B])
y = bikedata[1:, 0] # V_t
X = sm.add_constant(bikedata[:-1, :]) # Intercept, V_{t-1}, B_{t-1}
fit_random = sm.OLS(y, X).fit()
terms = ["Intercept", "V[t-1]", "B[t-1]"]
print("V_t regression")
for term, coef, se in zip(terms, fit_random.params, fit_random.bse):
print(f" {term:9s} {coef: .5f} (SE {se:.5f})")V_t regression
Intercept 0.06334 (SE 0.00880)
V[t-1] 1.00178 (SE 0.00158)
B[t-1] -0.66423 (SE 0.18756)
This gives so the sign corresponding to is correct. If the sample size is larger, we will get a more accurate estimate of the coefficient (closer to -1). Go back and increase to say and re-run the code.
To summarize this example, heavier braking predicts a larger speed gain because the cyclist brakes harder on steeper slopes, and we recover the negative braking coefficient when we account for the slope or randomize braking. Motivated by this example, one possible explanation for the price puzzle is that the Fed raises rates in anticipation of inflationary pressures the model misses, so inflation can rise after a rate hike even if it would have risen more without one.
Below we discuss another toy example which is also conceptually similar to the inflation-interest rate problem.
Thermostat Example¶
We simulate a thermostat that heats a room in a cold climate. Time is measured in hours, and all temperatures are in degrees Celsius. We record three quantities.
is the indoor temperature at the beginning of hour .
is the average outdoor temperature during hour .
is the heating power during hour , measured in units such that one unit of heat adds one degree to the indoor temperature over the hour.
We model the outdoor temperatures as independent draws,
The mean of represents a typical cold-weather hour. The standard deviation of gives us a mix of colder and milder hours, with about two-thirds of the outdoor temperatures falling between and . Under the independence assumption, our best prediction from past temperatures alone is .
The indoor temperature evolves according to
where the disturbances are independent of the outdoor temperatures. Without heating or disturbances, the indoor temperature moves of the way toward the outdoor temperature each hour.
How the thermostat sets the heat¶
Suppose the room begins hour at the target temperature . If the heater is off, the indoor temperature one hour later will be , apart from the random disturbance. The heat needed to maintain the target is therefore
Thus, for an hour with outdoor temperature , the required heat is . On the other hand, for a typical hour, the thermostat can use the mean outdoor temperature of and supply .
We assume the thermostat schedules the heat one hour in advance. When it sets at the beginning of hour , it knows the indoor reading and has a weather forecast for hour . For simplicity, we assume the forecast equals the actual temperature . The thermostat gives weight to the heating requirement based on the forecast and weight to the requirement for a typical hour, where .
The thermostat also corrects for the indoor temperature. For each degree that is below target, it adds 0.3 units of heat. For each degree above target, it reduces the heat by the same amount. Combining this correction with the expected heat loss gives
Taking the target temperature to be , we can write the rule as
The coefficient -0.3 describes the thermostat’s negative feedback. Holding the outdoor forecast fixed, each C increase in the indoor reading at the beginning of hour causes the thermostat to schedule 0.3 fewer units of heat for hour .
For example, if the indoor reading is at the target of , a typical hour calls for 3 units of heat. If the forecast is , the room is expected to lose one additional degree, and the thermostat sets . With it supplies the usual 3 units, with it supplies 3.5, and with it supplies the full 4 units needed for the colder hour.
To summarize, we generate the data according to:
The code below simulates this data.
seed = 248
rng = np.random.default_rng(seed)
n = 2000
W = rng.normal(5, 5, n) #outside temperature during hour t (5 degrees on average)
eps = rng.normal(0, 0.3, n) #error term in the temperature equation
T = np.zeros(n)
H = np.zeros(n)
theta = 0.5
T[0], H[0] = 20, 3 #initial temperature and heater power
target_temp = 20
for t in range(1, n):
T[t] = 0.8 * T[t-1] + 0.2 * W[t-1] + 1.0 * H[t-1] + eps[t]
H[t] = 0.3 * (target_temp - T[t-1]) + theta * 0.2 * (target_temp - W[t]) + (1 - theta) * 0.2 * (target_temp - 5) # heater power depends on the previous temperature and the outside temperatureHere is a plot of the three time series.
n_plot = n
#n_plot = 120 #if you want to plot only the first 120 hours
fig, ax = plt.subplots(2, 1, figsize = (12, 5.5), sharex = True)
ax[0].plot(T[:n_plot], color = 'black')
ax[0].axhline(20, color = 'gray', linewidth = 0.5)
ax[0].set_ylabel('Room temperature (degrees C)')
ax[0].set_title('Data')
ax[1].plot(H[:n_plot], color = 'black')
ax[1].axhline(3, color = 'gray', linewidth = 0.5)
ax[1].set_ylabel('Heater power (kW)')
ax[1].set_xlabel('Hour')
plt.tight_layout()
plt.show()
Below we fit VAR(1) and VAR(2) models to the bivariate time series . Note we are ignoring the data on weather forecasts .
y_room = np.column_stack([T, H])
var1_room = VAR(y_room).fit(1)
print("Estimate of the intercept:", var1_room.intercept)
print("Estimate of A1 (first row: equation for the temperature, second row: equation for the heater):")
print(var1_room.coefs[0])
print("Standard errors of these estimates:")
print(var1_room.stderr[1:].T)
print("The matrix A1 in the equations which generated the data:")
print(np.array([[0.8, 1.0], [-0.3, 0.0]]))Estimate of the intercept: [12.82603334 8.92062885]
Estimate of A1 (first row: equation for the temperature, second row: equation for the heater):
[[ 0.47050629 -0.74630679]
[-0.29945316 0.01518088]]
Standard errors of these estimates:
[[0.01400663 0.0194972 ]
[0.01506719 0.0209735 ]]
The matrix A1 in the equations which generated the data:
[[ 0.8 1. ]
[-0.3 0. ]]
var2 = VAR(y_room).fit(2)
print("Estimate of the intercept:", var2.intercept)
print("Standard errors of the intercept:", var2.stderr[0])
print("Estimate of A1:")
print(var2.coefs[0])
print("Standard errors of A1:")
print(var2.stderr[1:3].T)
print("Estimate of A2:")
print(var2.coefs[1])
print("Standard errors of A2:")
print(var2.stderr[3:5].T)Estimate of the intercept: [18.83294338 9.21750736]
Standard errors of the intercept: [0.29941673 0.48587833]
Estimate of A1:
[[ 0.81489937 -0.99247343]
[-0.29382792 0.00755172]]
Standard errors of A1:
[[0.01484226 0.01381515]
[0.02408527 0.02241853]]
Estimate of A2:
[[-0.61360304 0.04000279]
[-0.01806619 -0.00826782]]
Standard errors of A2:
[[0.01239801 0.01702604]
[0.02011886 0.027629 ]]
The fitted VAR(1) equation is
The fitted heater equation is correctly predicting the thermostat’s response to indoor temperature. Recall that the actual heater equation was: . The variable so it can be treated as noise, and the correct linear equation relating to is which is recovered by the second VAR(1) equation.
The temperature equation has a surprising coefficient of -0.75 on , which, interpreted naively, suggests that heating would be lowering temperature. The negative coefficient appears because, in the simulated data, the thermostat turns up the heat in anticipation of cold weather. A higher heater setting therefore also tells us that the house is likely to lose more heat to the outdoors during that hour.
The fitted VAR(2) equation is
We can drop the coefficients which are small (also compare the coefficients with their standard errors; if the standard error of a coefficient is of the same order as the coefficient itself, then it can be ignored) to get
The second equation is again correct in describing how the thermostat is reacting to temperature. The first equation again has the wrong coefficient for . To understand this specific form for the first equation, first note that
Substituting into the temperature equation eliminates and gives the exact second-order equation
For , the two equations for the observed series become
where is the mean-zero weather contribution to the heater setting. Both the VAR(2) fitted equations are close to these expressions. In particular, the VAR(2) recovers the thermostat coefficient of -0.3, the second temperature lag of -0.6, and the coefficient of -1 on heating.
The reason for the negative coefficient is as follows. For the same , a weather forecast that is colder makes the thermostat supply 0.1 more units of heat. Starting from the same , the colder weather lowers the expected next temperature by , and the extra heating restores . The colder hour therefore ends cooler on average, even though the heater delivered more heat.
Once again, the connection to the price puzzle is the following. The Fed may raise interest rates when it anticipates inflationary pressures that the VAR omits, just as the thermostat raises the heat when it anticipates cold weather. A rate increase can then predict higher future inflation even if inflation would have risen more without it.
How can the effect of the heater be correctly measured?¶
There are two ways:
Recording what the thermostat knows. We keep the thermostat, but we also record the outside temperature (which the thermostat knew from its forecast), and fit the model to the three series , and .
An experiment. We switch off the thermostat, and set the power of the heater at random in every hour (with the same average and about the same spread as before). Then the power of the heater has nothing to do with the weather or with the temperature of the room.
We start with the first way. With the outside temperature included, the equations which generated the data are
(The third equation only says that the outside temperature cannot be predicted from the past.) This is a VAR(1) model for , with
Now nothing is hidden. The last terms of the three equations (, and ) are new at time , and they are unrelated to the past values , and .
Below we fit VAR(1) to the data.
#the columns are the room temperature, the heater power and the outside temperature
y_three = np.column_stack([T, H, W])
var1_three = VAR(y_three).fit(1)
print("Estimate of the intercept:", np.round(var1_three.intercept, 2))
print("Standard errors of the intercept:", np.round(var1_three.stderr[0], 2))
print("Estimate of A1 (the rows are the equations for the room temperature, the heater and the outside temperature):")
print(np.round(var1_three.coefs[0], 3))
print("Standard errors of these estimates:")
print(np.round(var1_three.stderr[1:].T, 3))
print("The matrix A1 in the equations which generated the data:")
print(np.array([[0.8, 1.0, 0.2], [-0.3, 0.0, 0.0], [0.0, 0.0, 0.0]]))Estimate of the intercept: [0.05 8.53 9.73]
Standard errors of the intercept: [0.32 0.52 5.23]
Estimate of A1 (the rows are the equations for the room temperature, the heater and the outside temperature):
[[ 0.792 1.032 0.202]
[-0.29 0.07 0.006]
[-0.105 -0.7 -0.062]]
Standard errors of these estimates:
[[0.011 0.038 0.004]
[0.018 0.061 0.007]
[0.183 0.609 0.065]]
The matrix A1 in the equations which generated the data:
[[ 0.8 1. 0.2]
[-0.3 0. 0. ]
[ 0. 0. 0. ]]
The VAR(1) on recovers all three one-hour-ahead equations up to sampling error. In the temperature equation, the fitted coefficients are close to the true values . Once we account for , the heating coefficient changes from -0.75 to 1.032, recovering the expected warming effect. The heater equation gives a coefficient of -0.29 on , close to the thermostat’s -0.3, and its other lag coefficients are consistent with zero. Its response to the current weather enters the heater equation’s error term. Finally, as expected for independent hourly outdoor temperatures, all three lag coefficients in the equation are consistent with zero, and the estimated intercept of 9.73 is within one standard error (5.23) of the true mean of .
If the thermostat is turned off and heating is turned on randomly, then VAR applied to would correctly recover the effect of on . To do this, we shall re-simulate the data with applied randomly. The following function generates the data according to the previous model with a fixed (that can be different from 0.5) or with heating turned on randomly. We then fit VAR(1) to the generated bivariate data . We print out the estimates of (which is the effect of heating on temperature) as well as (effect of temperature on heating ). The main purpose of the heater is to control the temperature of the room. To understand this, we also compute the standard deviation of the temperature time series (if this is small, then the heater is working well).
def simulate_room(n, theta, random_heater = False, seed = 248):
#n hours of the room temperature T, the heater power H and the outside temperature W
#theta: the fraction of the weather which the thermostat offsets in advance
#random_heater = True: there is no thermostat, and the heater power is set at random in every hour
rng = np.random.default_rng(seed)
W = rng.normal(5, 5, n) #outside temperature during hour t (5 degrees on average)
eps = rng.normal(0, 0.3, n) #everything else (doors, windows, people)
random_power = 3 + rng.normal(0, 0.55, n) #used only if random_heater = True
T = np.zeros(n)
H = np.zeros(n)
T[0], H[0] = 20, 3
for t in range(1, n):
T[t] = 0.8 * T[t-1] + 0.2 * W[t-1] + 1.0 * H[t-1] + eps[t] #the room
if random_heater:
H[t] = random_power[t]
else:
H[t] = 3 + 0.3 * (20 - T[t-1]) - 0.2 * theta * (W[t] - 5) #the thermostat (H[t] is set one hour ahead)
return T, H, W
def room_summary(T, H, extra = None):
#fits a VAR(1) model to the temperature and the heater power (and to a third series, if extra is given), and returns:
#the coefficient of the heater in the equation for the temperature, the coefficient of the temperature
#in the equation for the heater, and the standard deviation of the room temperature
series_list = [T, H] if extra is None else [T, H, extra]
A1 = VAR(np.column_stack(series_list)).fit(1).coefs[0]
return {'heater -> temp. (truth 1.0)': A1[0, 1],
'temp. -> heater (truth -0.3)': A1[1, 0],
'sd of temp.': np.std(T)}
n_hours = 2000
T_room, H_room, W_room = simulate_room(n_hours, theta = 0.5)
room_results = {}
for theta in [0, 0.5, 1]:
T_sim, H_sim, W_sim = simulate_room(n_hours, theta = theta)
room_results[f"thermostat, theta = {theta}"] = room_summary(T_sim, H_sim)
T_exp, H_exp, W_exp = simulate_room(n_hours, theta = 0.5, random_heater = True)
room_results["no thermostat, random power"] = room_summary(T_exp, H_exp)
room_results["theta = 0.5, weather recorded"] = room_summary(T_room, H_room, extra = W_room)
print(pd.DataFrame(room_results).T.round(2))
heater -> temp. (truth 1.0) \
thermostat, theta = 0 1.01
thermostat, theta = 0.5 -0.75
thermostat, theta = 1 0.02
no thermostat, random power 1.01
theta = 0.5, weather recorded 1.03
temp. -> heater (truth -0.3) sd of temp.
thermostat, theta = 0 -0.30 1.36
thermostat, theta = 0.5 -0.30 0.76
thermostat, theta = 1 -0.34 0.41
no thermostat, random power 0.00 1.91
theta = 0.5, weather recorded -0.29 0.76
The bivariate VAR(1) correctly estimates the effect of heating on next-hour temperature both with randomized heating and with the thermostat on at . In both cases, the coefficient on is 1.01, close to the true value of 1. When , the thermostat responds only to past indoor temperature, so its heating decision is independent of the outdoor temperature during the hour it heats. When the thermostat uses the weather forecast, the fitted heating coefficient changes to -0.75 at and 0.02 at . Meanwhile, the temperature feedback coefficient stays close to -0.3 whenever the thermostat is on and is 0.00 under random heating. As increases from 0 to 0.5 to 1, the standard deviation of room temperature falls from 1.36 to 0.76 to , compared with under random heating. Including outdoor temperature in the VAR at restores the positive heating coefficient, giving an estimate of 1.03.
VAR(2) applied to the Unemployment-Inflation-Interest Rate data¶
VAR(2) actually fits better to the unemployment-inflation-interest rate data compared to VAR(1). This can be seen from the following code which selects using the BIC.
var_bic = VAR(var_data).fit(maxlags=12, ic="bic")
print(f"BIC selected p = {var_bic.k_ar}")BIC selected p = 2
We fit the VAR(2) model to the same dataset as follows.
var2 = VAR(var_data).fit(2)
print("Estimate of the intercept:", var2.intercept)
print("Estimate of A1:")
print(var2.coefs[0])
print("Estimate of A2:")
print(var2.coefs[1])Estimate of the intercept: [0.17669122 0.18189565 0.08857192]
Estimate of A1:
[[ 0.98494715 -0.01711639 -0.08674496]
[ 0.27976184 0.53755448 0.43267444]
[-0.0515184 0.02463517 1.36058518]]
Estimate of A2:
[[-0.02105631 0.01044626 0.0982918 ]
[-0.22504444 0.09740152 -0.29292927]
[ 0.04222749 -0.00160862 -0.38296451]]
The impulse responses for inflation (in response to a unit interest rate shock) are plotted as follows (along with the corresponding impulse responses for the VAR(1) model).
H = 24
months = range(H + 1)
# Columns of var_data are unemployment, inflation, and the federal funds rate.
var1 = VAR(var_data).fit(1)
var2 = VAR(var_data).fit(2)
# Inflation response to a one-percentage-point funds rate shock
inflation_response_1 = var1.irf(H).irfs[:, 1, 2]
inflation_response_2 = var2.irf(H).irfs[:, 1, 2]
plt.figure(figsize=(9, 4))
plt.plot(months, inflation_response_1, label="VAR(1)")
plt.plot(months, inflation_response_2, "--", label="VAR(2)")
plt.axhline(0, color="black", linewidth=0.8)
plt.xlabel("Months after the funds rate shock")
plt.ylabel("Inflation response (percentage points)")
plt.xticks(months)
plt.legend()
plt.tight_layout()
plt.show()
The conclusion for VAR(2) is similar to that of VAR(1). The impulse responses for inflation are positive for many months after the funds rate shock.