Use tsa.filters.hpfilter to Calculate Output Gap in Python
Paste a GDP, production, or output time series, choose a smoothing parameter, and instantly estimate the Hodrick-Prescott trend, cyclical component, and latest output gap. The calculator mirrors the core idea behind statsmodels.tsa.filters.hpfilter and visualizes the result for quick macroeconomic analysis.
Calculator Inputs
Enter a time series and click the button to estimate the HP trend and current output gap.
Chart Output
The chart overlays the original series and HP trend, while a second axis displays the estimated output gap for each observation.
How to use tsa.filters.hpfilter to calculate output gap in Python
The output gap is one of the most practical macroeconomic indicators for analysts, policy teams, investors, and researchers. It measures how far actual output is from an estimated trend or potential level of output. In applied Python work, one of the most common ways to estimate that trend is with the Hodrick-Prescott filter, typically accessed through the statsmodels function statsmodels.tsa.filters.hpfilter. If your goal is to use tsa.filters.hpfilter to calculate output gap in Python, the basic workflow is straightforward: collect a time series such as real GDP, estimate the smooth trend, subtract the trend from the original series, and then express the gap either in levels or as a percentage of trend.
Conceptually, the HP filter decomposes an observed series into two parts. The first is the trend component, which changes smoothly over time. The second is the cyclical component, which captures short run deviations around that trend. In macroeconomic usage, that cyclical component is often interpreted as the output gap. When output is above trend, the gap is positive. When output is below trend, the gap is negative. Economists use that result to evaluate overheating, slack, recession depth, and the timing of stabilization policy.
Key idea: in statsmodels, hpfilter returns two arrays: the cyclical component and the trend component. If you want the output gap, you usually use the cyclical component directly, or convert it into a percent gap with 100 * cycle / trend.
What the Python function does
In practice, the Python pattern looks like this: you import the filter from statsmodels, pass in a one dimensional series, and specify the smoothing parameter lamb. The function then solves for a trend that balances two objectives. First, the trend should stay fairly close to the observed data. Second, the trend should be smooth, which means changes in the trend growth rate are penalized. The smoothing parameter determines how strongly smoothness is enforced. A very high lambda gives you a smoother trend. A low lambda allows the trend to follow the data more closely.
import pandas as pd import statsmodels.api as sm gdp = pd.Series([100, 101.2, 102.5, 103.1, 102.9, 104.3, 105.1, 106.4]) cycle, trend = sm.tsa.filters.hpfilter(gdp, lamb=1600) output_gap_level = cycle output_gap_percent = 100 * (gdp - trend) / trend
This is why the calculator above asks for your data frequency and lambda. The same raw series can produce materially different gaps if the smoothing choice changes. That is not a bug. It is one of the defining judgment calls in real world output gap estimation.
Recommended lambda values by frequency
One of the first decisions is the lambda value. Quarterly macroeconomic work usually applies 1600, annual work often uses 6.25, and monthly work often uses 129600. These are the standard benchmark settings used in much of the empirical literature. They are not universal truths, but they are common and make your work easier to compare with published studies.
| Data frequency | Common HP lambda | Typical use case | Interpretation |
|---|---|---|---|
| Annual | 6.25 | Long run growth and potential output analysis | Less smoothing because annual data already compress short run noise |
| Quarterly | 1600 | GDP and business cycle work | Standard benchmark in many macro applications |
| Monthly | 129600 | Industrial production or monthly activity indicators | High smoothing because monthly data contain more short run fluctuation |
Those benchmark values matter because output gap estimates can be sensitive. For example, if you choose a lambda that is too low, what should have been cyclical variation can leak into the trend. If you choose one that is too high, structural changes may be over-smoothed and the cyclical component may become exaggerated. In other words, the HP filter is useful, but it is not purely mechanical. Good practice means matching lambda to the data frequency and then checking whether the result is economically plausible.
Where the data come from
If you are estimating an output gap for an economy, the underlying series should generally be inflation adjusted output, such as real GDP. In the United States, the Bureau of Economic Analysis publishes official GDP estimates and chain type quantity indexes. For production based analysis, industrial production or broader activity measures can also be used. For potential output comparisons, many researchers also benchmark against official or semi official estimates from public institutions such as the Congressional Budget Office.
Helpful official sources include the U.S. Bureau of Economic Analysis GDP data, the Congressional Budget Office economy and budget data, and Federal Reserve research and policy materials at FederalReserve.gov. These sources are especially useful if you want to compare a simple HP filter estimate against institutional measures of potential output and slack.
Level gap versus percent gap
There are two common ways to present the output gap. The first is the level gap:
- Level gap = actual output minus HP trend
The second is the percent gap:
- Percent gap = 100 × (actual output minus trend) ÷ trend
Percent gaps are often easier to compare across time and across economies because they standardize the deviation relative to the level of output. If actual GDP is 0.8 percent below trend, that has a direct policy interpretation. If the level gap is negative 150 billion in one period and negative 100 billion in another, the meaning depends more heavily on the overall size of the economy. For dashboard and reporting work, percent gaps are usually more intuitive.
Why practitioners still use the HP filter
The HP filter has limitations, but it remains widely used because it is simple, fast, and transparent. It helps researchers separate trend growth from cyclical movement without building a large structural model. That makes it attractive in exploratory analysis, cross country comparisons, and internal briefing notes. It also integrates smoothly with Python, pandas, NumPy, and statsmodels, so analysts can move from data ingestion to diagnostics very quickly.
- Load a clean real output series into pandas.
- Choose a frequency appropriate lambda.
- Run
sm.tsa.filters.hpfilter(series, lamb=value). - Store the returned cycle and trend.
- Express the cycle as a level gap or percent gap.
- Plot actual output, trend, and the gap for interpretation.
Real benchmark statistics analysts commonly use
To place HP filter output gaps in context, analysts often compare them with official estimates of economic slack and production loss. Public agencies update these series regularly. The exact values change over revisions, but the point is that output gap analysis is not abstract. It connects to real policy and business cycle episodes.
| Indicator | Representative statistic | Why it matters for output gap work |
|---|---|---|
| U.S. real GDP contraction in 2020 | Approximately -2.2% annual change | A deep decline in actual output usually widens a negative output gap |
| Common quarterly HP lambda | 1600 | The standard setting used in many published macro studies |
| Common annual HP lambda | 6.25 | Useful for lower frequency long horizon output analysis |
| Common monthly HP lambda | 129600 | Designed to smooth higher frequency monthly variation |
Those figures are practical anchor points. If your HP filtered GDP series shows only a tiny gap during a clearly severe contraction, that may signal a data issue, a frequency mismatch, or excessive smoothing. If the filter produces a huge positive gap during a period of stable inflation and modest growth, you may need to inspect whether the trend is being pulled by endpoint behavior.
The endpoint problem and why it matters
One of the biggest cautions with tsa.filters.hpfilter is endpoint bias. The HP filter uses information from neighboring observations to estimate the trend, so estimates at the end of the sample are less stable than those in the middle. For macro surveillance, this matters a lot because policymakers and analysts care most about the latest observation. If your sample ends in a major shock, the final trend and gap values may later be revised noticeably when new data arrive.
Best practice: treat the latest HP filter output gap as provisional. Recompute it whenever new data are added, and consider comparing it with production function, state space, or institutional potential output estimates.
Python workflow example with pandas
A clean applied workflow starts with a date indexed pandas Series. If you have quarterly GDP data downloaded from BEA or a CSV file, convert the date column, sort the data, and then run the filter. After that, create a chart of actual output and trend plus a bar or line chart of the output gap. This gives decision makers both a level view and a cyclical view.
import pandas as pd
import statsmodels.api as sm
import matplotlib.pyplot as plt
df = pd.read_csv("real_gdp.csv")
df["date"] = pd.to_datetime(df["date"])
df = df.sort_values("date").set_index("date")
cycle, trend = sm.tsa.filters.hpfilter(df["real_gdp"], lamb=1600)
df["trend"] = trend
df["gap_percent"] = 100 * cycle / trend
fig, ax = plt.subplots(2, 1, figsize=(10, 8), sharex=True)
df[["real_gdp", "trend"]].plot(ax=ax[0], title="Actual Output vs HP Trend")
df["gap_percent"].plot(ax=ax[1], title="Output Gap (%)")
plt.tight_layout()
plt.show()
This pattern is easy to adapt. If you are working with monthly industrial production, switch the lambda to 129600. If you are working with annual data for a small panel of countries, use 6.25 unless you have a strong reason to do otherwise.
When the HP filter is appropriate and when it is not
The HP filter is most useful when you need a fast empirical decomposition and your audience understands that the result is a model based estimate rather than a direct observation. It is not the only method for estimating the output gap. Alternatives include production function approaches, unobserved components models, Kalman filtering, Beveridge-Nelson decompositions, and institution specific potential output frameworks. Those methods may be better if you need richer economic structure, labor and capital inputs, or explicit treatment of trend shocks.
- Use HP filtering for fast baseline analysis and dashboarding.
- Use official potential output series when institutional comparability matters.
- Use state space or structural models when policy inference must be more rigorous.
How to interpret the result responsibly
A positive output gap usually suggests output is running above trend and may coincide with tighter labor markets, capacity pressure, and inflation risk. A negative gap indicates slack, underutilized resources, and weaker demand conditions. But the gap should never be read in isolation. Pair it with inflation, wages, employment, productivity, and credit conditions. A small positive gap in a low inflation environment might not signal overheating. A large negative gap with stable productivity may imply strong cyclical weakness rather than structural damage. Context matters.
Why this calculator is useful
The calculator on this page gives you a practical approximation of the HP filter logic that analysts use in Python. It accepts your raw series, lets you choose the frequency based lambda, computes the estimated trend, and returns the latest gap in either level or percent terms. It also plots the series so you can visually inspect whether the trend appears plausible. That visual check is essential because output gap estimation is as much about informed interpretation as it is about arithmetic.
If you are building production code, the next step is to run the same workflow in Python with statsmodels, save the cycle and trend to your dataset, and create reproducible charts and reports. In short, to use tsa.filters.hpfilter to calculate output gap in Python, you only need a well prepared series, an appropriate lambda, and a clear decision about whether to report the gap in levels or percentages. The technical steps are simple. The analytical value comes from choosing sensible inputs and interpreting the result with care.