The Engle-Granger cointegration test checks whether two or more non-stationary price series share a long-run equilibrium. It runs in two steps: an OLS regression of one series on the other, then a unit root test on the residuals. If the residuals are stationary, the series are cointegrated, which means the gap between them keeps returning to its average.
This guide runs the Engle-Granger cointegration test in Python on the DAX and its constituents, with daily EODHD data from March 2010 to November 2026. Only 1 of 33 stocks, Allianz, was cointegrated with the index at the 5% level. The guide then builds two portfolios that track the DAX, one based on cointegration and one that minimizes tracking error variance (TEVM), and measures both out of sample over more than 14 years. TEVM tracked the index more closely: an annualized tracking error of 2.04%, against 2.61% for the cointegration portfolio.
Quick jump:
- 1 What cointegration means
- 2 How the Engle-Granger cointegration test works
- 3 How to get your EODHD API key
- 4 Getting the data for the Engle-Granger cointegration test
- 5 Running the Engle-Granger cointegration test on each DAX stock
- 6 Building tracking portfolios: cointegration vs TEVM
- 7 Results: which method tracked the DAX better
- 8 What would change these results
- 9 Conclusion
- 10 FAQs
What cointegration means
A price series is non-stationary when its mean and variance change over time. Most stock prices and indices behave this way: they drift, and past levels don’t tell you where they will return to. A stationary series, by contrast, keeps returning to a stable mean.
Two non-stationary series X and Y are cointegrated if some linear combination of them, such as Y – bX, is stationary. Each series can wander on its own, but the spread between them keeps coming back. That property is what pairs trading and index tracking rely on: investors expect a temporary gap to close.
Cointegration is different from correlation. Correlation measures how closely the returns of two series move together, usually over short horizons. Two stocks can be highly correlated and still drift apart over years, and two cointegrated series can have periods of low return correlation while their price levels stay tied.
How the Engle-Granger cointegration test works
The Engle-Granger method, introduced by Robert Engle and Clive Granger in 1987, has two steps:
- Regress one series on the other with ordinary least squares (OLS), using price levels or log prices, not returns: ln(Index) = a + b × ln(Stock) + e.
- Test the residuals e for a unit root with an Augmented Dickey-Fuller (ADF) test. If the test rejects the unit root, the residuals are stationary and the series are cointegrated.
The ADF test on residuals needs its own critical values, because the residuals come from an estimated regression. In Python, statsmodels.tsa.stattools.coint runs both steps and returns the test statistic, its p-value and the right critical values.
The Johansen test is the main alternative. It tests several series at once and can find more than one cointegrating relationship, while Engle-Granger tests one relationship at a time and depends on which series is on the left side of the regression.
How to get your EODHD API key
1. Use the “demo” API key to test our data from a limited set of tickers without registering:
AAPL.US | TSLA.US | VTI.US | AMZN.US | BTC-USD | EUR-USD
Real-Time Data and all of the APIs (except Bulk) are included without API calls limitations with these tickers and the demo key.
2. Register to get your free API key (limited to 20 API calls per day) with access to:
End-Of-Day Historical Data with only the past year for any ticker, and the List of tickers per Exchange.
3. To unlock your API key, we recommend to choose the subscription plan which covers your needs.
This example needs 16 years of end-of-day prices for 40 tickers and the index constituents from the Fundamentals API, so it needs the All-In-One plan, or the EOD Historical All-World and Fundamentals Data Feed plans together.
Getting the data for the Engle-Granger cointegration test
The index constituents come from the Fundamentals API (GDAXI.INDX, Components section), and the prices from the end-of-day API, with each stock on XETRA:
import os
import sys
import pandas as pd
import requests
API_KEY = os.environ["EODHD_API_KEY"]
BASE = "https://eodhd.com/api"
def get(path, **params):
resp = requests.get(f"{BASE}/{path}", params={"api_token": API_KEY, "fmt": "json", **params}, timeout=60)
resp.raise_for_status()
return resp.json()
def adjusted_close(ticker, start, end):
df = pd.DataFrame(get(f"eod/{ticker}", **{"from": start, "to": end}))
return df.set_index(pd.to_datetime(df["date"]))["adjusted_close"].astype(float)
start, end = sys.argv[1:3]
components = get("fundamentals/GDAXI.INDX", filter="Components")
codes = [c["Code"] for c in components.values()]
print(f"Constituents returned: {len(codes)}")
prices = {"DAX": adjusted_close("GDAXI.INDX", start, end)}
for code in codes:
prices[code] = adjusted_close(f"{code}.XETRA", start, end)
df = pd.DataFrame(prices).sort_index()
first = df.apply(lambda s: s.first_valid_index().date())
print(first.sort_values(ascending=False).head(15).to_string())
df.to_csv("dax_prices.csv")
Run with python get_dax_data.py 2010-01-01 2026-11-06. The endpoint returned 39 constituent codes on the day of the run, and the first lines of the output show which of them have a shorter history:
Constituents returned: 39
DTG 2021-12-13
ENR 2020-09-28
SHL 2018-03-16
G24 2015-10-01
ZAL 2014-10-01
VNA 2013-07-11
BNR 2010-03-29
AIR 2010-01-04
Six stocks, Daimler Truck, Siemens Energy, Siemens Healthineers, Scout24, Zalando and Vonovia, started trading after the start of the sample, so the analysis drops them and starts on March 29, 2010, the first date with prices for Brenntag. That leaves 33 stocks and 4,216 trading days.
Running the Engle-Granger cointegration test on each DAX stock
The first test checks each stock against the index, one at a time, with log prices on both sides:
import sys
import numpy as np
import pandas as pd
import statsmodels.api as sm
from statsmodels.tsa.stattools import adfuller, coint
prices = pd.read_csv(sys.argv[1], index_col=0, parse_dates=True)
# Keep the stocks with prices since the start of the sample
late = [c for c in prices.columns if prices[c].first_valid_index() > pd.Timestamp("2010-03-31")]
df = prices.drop(columns=late).dropna()
print(f"Dropped (listed later): {', '.join(late)}")
print(f"Sample: {df.index[0].date()} to {df.index[-1].date()}, {len(df)} days, {df.shape[1] - 1} stocks\n")
logp = np.log(df)
ret = df.pct_change().dropna()
# Step 1: Engle-Granger, one stock at a time
rows = []
for stock in logp.columns.drop("DAX"):
t_stat, p_value, crit = coint(logp["DAX"], logp[stock])
rows.append({"stock": stock, "t_stat": t_stat, "p_value": p_value, "crit_5pct": crit[1]})
eg = pd.DataFrame(rows).sort_values("p_value")
print("ADF p-value of the index itself:", round(adfuller(logp["DAX"], result_object=False)[1], 3))
print(f"Cointegrated with the DAX at 5%: {(eg['p_value'] < 0.05).sum()} of {len(eg)}")
print(eg.head(8).to_string(index=False, float_format="{:.3f}".format), "\n")
The output, with statsmodels 0.15.0 and pandas 3.0.5:
Dropped (listed later): ZAL, VNA, G24, SHL, ENR, DTG
Sample: 2010-03-29 to 2026-11-06, 4216 days, 33 stocks
ADF p-value of the index itself: 0.849
Cointegrated with the DAX at 5%: 1 of 33
stock t_stat p_value crit_5pct
ALV -3.791 0.014 -3.338
DTE -3.260 0.060 -3.338
SIE -3.172 0.075 -3.338
MUV2 -3.144 0.080 -3.338
DB1 -2.922 0.130 -3.338
EOAN -2.901 0.136 -3.338
RHM -2.576 0.247 -3.338
HNR1 -2.541 0.261 -3.338

The ADF p-value of 0.849 for the log index means the test can’t reject a unit root, which is consistent with a non-stationary DAX and is the starting condition for a cointegration test. Of the 33 stocks, only Allianz (ALV) had a test statistic below the 5% critical value of -3.338. Deutsche Telekom, Siemens and Munich Re came close, with p-values between 0.06 and 0.08.
That result isn’t surprising. A single stock carries its own business risk, so over 16 years its price can drift far from the index even when the two are highly correlated day to day.
Building tracking portfolios: cointegration vs TEVM
A portfolio of many stocks has a better chance of staying tied to the index than any single stock. The two methods below build that portfolio from all 33 stocks with a rolling regression:
- Cointegration: regress the log index on the log prices of the stocks, then use the coefficients as weights, scaled to sum to 1. This follows the approach in Alexander and Dimitriu (2002).
- TEVM (tracking error variance minimization): regress the index returns on the stock returns. The OLS coefficients minimize the variance of the daily difference between portfolio and index, before the code scales them to sum to 1.
Both use a calibration window of 500 trading days, about two years, and rebalance every 10 trading days. The code then applies each set of weights only to the next 10 days, which the regression hasn’t seen, so the result is out of sample:
# Step 2: rolling tracking portfolios, measured on the 10 days after each fit
WINDOW, STEP = 500, 10
stocks = logp.columns.drop("DAX")
out = {"coint": [], "tevm": []}
adf_p = []
for i in range(WINDOW, len(ret) - STEP + 1, STEP):
fit_lp = logp.iloc[i - WINDOW + 1:i + 1]
fit_r = ret.iloc[i - WINDOW:i]
m_c = sm.OLS(fit_lp["DAX"], sm.add_constant(fit_lp[stocks])).fit()
m_t = sm.OLS(fit_r["DAX"], sm.add_constant(fit_r[stocks])).fit()
adf_p.append(adfuller(m_c.resid, result_object=False)[1])
w_c = m_c.params[stocks] / m_c.params[stocks].sum()
w_t = m_t.params[stocks] / m_t.params[stocks].sum()
nxt = ret.iloc[i:i + STEP]
out["coint"].append(nxt[stocks] @ w_c)
out["tevm"].append(nxt[stocks] @ w_t)
idx = ret["DAX"]
rows = []
for name, label in [("coint", "Cointegration"), ("tevm", "TEVM")]:
p = pd.concat(out[name])
b = idx.loc[p.index]
diff = p - b
rows.append({"method": label,
"tracking_error_ann": diff.std() * np.sqrt(252),
"correlation": p.corr(b),
"portfolio_total": (1 + p).prod() - 1,
"index_total": (1 + b).prod() - 1})
res = pd.DataFrame(rows)
first_day = pd.concat(out["coint"]).index[0].date()
print(f"Out of sample from {first_day}, {len(adf_p)} rebalances")
print(f"Calibration windows with stationary residuals (ADF p < 0.05): {np.mean(np.array(adf_p) < 0.05):.0%}")
print(res.to_string(index=False, float_format="{:.4f}".format))
The output:
Out of sample from 2012-03-08, 371 rebalances
Calibration windows with stationary residuals (ADF p < 0.05): 100%
method tracking_error_ann correlation portfolio_total index_total
Cointegration 0.0261 0.9902 2.5638 2.8702
TEVM 0.0204 0.9940 2.9078 2.8702
Results: which method tracked the DAX better
| Out of sample, March 2012 to November 2026 | Cointegration | TEVM |
|---|---|---|
| Annualized tracking error | 2.61% | 2.04% |
| Correlation of daily returns with the DAX | 0.9902 | 0.9940 |
| Total return of the portfolio | 256.38% | 290.78% |
| Total return of the DAX | 287.02% | 287.02% |
| Cumulative difference at the end | -7.92% | +0.97% |

Both portfolios followed the index closely, with correlations above 0.99. On each of those measures, though, TEVM came closer: a lower tracking error, a higher correlation, and a cumulative gap of only 0.97% to the DAX at the end. The cointegration portfolio stayed below the index on 96.8% of the days, with a cumulative gap that reached -14.43% before narrowing to -7.92% at the end.
The 2024 edition of this article, built on the DAX 30, concluded that the cointegration approach tracked better than TEVM. This test uses today’s constituents, a longer sample and weights applied only to the days after each fit, and the result reversed. This test doesn’t isolate which of those differences caused the change. One likely factor is the objective: TEVM fits the daily differences that tracking error measures, while the cointegration method fits price levels.
What would change these results
Several choices in this test affect the outcome, and each is worth varying before drawing a firm conclusion:
- Survivorship. The test uses the constituents returned on the day of the run, applied back to 2010. Companies that left the index during that time aren’t in the portfolios, which likely makes both of them look better than a real-time version would.
- Critical values with many stocks. The calibration windows all showed stationary residuals with a standard ADF test, but with 33 regressors the proper Engle-Granger critical values are much stricter than the standard ADF ones. That share overstates how often the full portfolio was cointegrated.
- Weights. The regressions don’t restrict the weights, so some can be negative, which means short positions. A long-only version needs a constrained optimization instead of plain OLS.
- Window and rebalancing. A 500-day window and a 10-day rebalance follow the original article. Longer windows give more stable weights, and less frequent rebalancing lowers trading costs, which this test doesn’t include.
- Number of stocks. Many tracking portfolios use only a subset of the constituents. With fewer stocks, the difference between the two methods can change.
Conclusion
The Engle-Granger cointegration test is a two-step check: regress one price series on another, then test the residuals for a unit root. On 16 years of DAX data, only Allianz passed it at the 5% level against the index. Over long periods, a single stock rarely keeps a stable link with a broad index.
For index tracking, both approaches built portfolios with a correlation above 0.99 to the DAX. In this out-of-sample test, the TEVM portfolio tracked the index more closely than the cointegration portfolio, with a tracking error of 2.04% against 2.61%.
With the EODHD end-of-day and fundamentals data, you can rerun the test on other indices, windows and subsets of stocks. For the endpoints used here, see the End-of-Day Historical Data API documentation and the Fundamentals API documentation.
FAQs
Q: What is the Engle-Granger cointegration test?
It is a two-step test for a long-run relationship between non-stationary series. First, regress one series on the other with OLS. Second, test the residuals for a unit root with an ADF test. Stationary residuals mean the series are cointegrated.
Q: How do I run the Engle-Granger test in Python?
Use statsmodels.tsa.stattools.coint(y, x) on the price levels or log prices. It returns the test statistic, the p-value and the 1%, 5% and 10% critical values, and applies the critical values that the Engle-Granger test requires.
Q: What is the difference between cointegration and correlation?
Correlation measures how closely returns move together. Cointegration means the price levels share a long-run equilibrium, so the spread between them keeps returning to its average. Two series can be highly correlated without being cointegrated.
Q: What is the difference between the Engle-Granger and Johansen tests?
Engle-Granger tests one relationship at a time and depends on which variable is the dependent one in the regression. Johansen tests several series together and can find more than one cointegrating relationship.
Q: Which is better for index tracking, cointegration or tracking error minimization?
It depends on the setup. In this test on the DAX from 2012 to 2026, the TEVM portfolio had a lower out-of-sample tracking error (2.04%) than the cointegration portfolio (2.61%), and ended with a cumulative gap of 0.97% to the index.