Python Quantitative Statistics Fundamentals
Statistics is the inner foundation of quantitative strategies: the distribution shape of returns determines how to build risk models, stationarity determines which methods are usable, and cointegration determines whether pairs trading can be done.
This article uses real data to answer three questions: Do returns follow a normal distribution? Is the price series stationary? What kind of two stocks can be paired?
Do returns follow a normal distribution?
Many classic models (such as Markowitz portfolio theory) rest on the assumption that "returns follow a normal distribution"; this assumption is worth testing first.
Use Moutai's 2019-2024 daily returns to compute three characteristic values:
Example
import
yfinance
as
yf
from
scipy
import
stats
close
=
yf.
download
(
"600519.SS"
,
start
=
"2019-01-01"
,
end
=
"2024-12-31"
,
progress
=
False
,
multi_level_index
=
False
)
[
"Close"
]
ret
=
close.
pct_change
(
)
.
dropna
(
)
(
f
"Sample size {len(ret)} | mean {ret.mean():.4%} | std dev {ret.std():.4%}"
)
(
f
"Skewness {ret.skew():.4f} | kurtosis {ret.kurtosis():.4f} (both are 0 for a normal distribution)"
)
Jarque-Bera normality test
jb
,
pvalue
=
stats.
jarque_bera
(
ret
)
(
f
"Jarque-Bera statistic {jb:.1f}, p-value {pvalue:.2e}"
)
The output is shown below:
样本数 1452 | 均值 0.0901% | 标准差 1.8671%
偏度 0.3425 | 峰度 2.7022(正态分布两者均为 0)
Jarque-Bera 统计量 465.7,p 值 7.41e-102
All three pieces of evidence point to the same conclusion:
| Pointer | Actual value | Normal distribution requirement | Interpretation |
|---|---|---|---|
| Skewness | 0.3425 | 0 | Distribution slightly right-skewed |
| Kurtosis | 2.7022 | 0 | Significant "peaked with fat tails" |
| Jarque-Bera p-value | 7.41e-102 | Greater than 0.05 | Strongly reject the normality assumption |
The intuitive meaning of "peaked with fat tails": on most days volatility is small (peaked), but extreme days occur far more often than the normal assumption implies (fat tails).
Overlay the return histogram with a normal curve of the same mean and standard deviation, and the fat tails are clearly visible:
Example
import
matplotlib.
pyplot
as
plt
import
numpy
as
np
from
scipy
import
stats
plt.
figure
(
figsize
=
(
12
,
6
)
)
plt.
hist
(
ret
,
bins
=
80
,
density
=
True
,
alpha
=
0.55
,
color
=
"#14805e"
,
label
=
"Daily Returns"
)
Normal density curve with the same mean and standard deviation
xs
=
np.
linspace
(
ret.
min
(
)
,
ret.
max
(
)
,
400
)
plt.
plot
(
xs
,
stats.
norm
.
(
xs
,
ret.
mean
(
)
,
ret.
std
(
)
)
,
color
=
"#1f2933"
,
linewidth
=
1.8
,
linestyle
=
"--"
,
label
=
"Normal Distribution"
)
plt.
title
(
"Maotai Daily Returns vs Normal Distribution (2019-2024)"
)
plt.
xlabel
(
"Daily Return"
)
plt.
ylabel
(
"Density"
)
plt.
legend
(
)
plt.
grid
(
alpha
=
0.25
)
plt.
show
(
)
Run the code above and the output chart is as follows:

The center of the chart stands above the normal curve, and there are noticeably more extreme values on both sides. That's why risk management can't look only at standard deviation,Maximum Drawdownsuch "tail metrics" must be computed separately.
Stationarity: the foundation of time series
The statistical properties (mean, variance) of a stationary series don't change over time; the mean of a non-stationary series drifts, so the concept of "average" has limited meaning for it.
Use the ADF test (Augmented Dickey-Fuller) to judge stationarity; the null hypothesis is "the series is non-stationary":
Example
from
statsmodels.
tsa
.
stattools
import
adfuller
Test the price series and the return series separately
for
name
,
series
in
[
(
"Price"
,
close
)
,
(
"Returns"
,
ret
)
]
:
stat
,
pvalue
,
*_
=
adfuller
(
series.
dropna
(
)
)
verdict
=
"Stationary"
if
pvalue
<
0.05
else
"Non-stationary"
print
(
f"{name} series: ADF statistic {stat:.4f}, p-value {pvalue:.4f} -> {verdict}"
)
The output is shown below:
价格序列: ADF 统计量 -2.6077, p 值 0.0914 -> 非平稳
收益率序列: ADF 统计量 -25.5904, p 值 0.00e+00 -> 平稳
The conclusion is a classic fact of financial time series: prices are non-stationary, returns are stationary.
This explains why all models are built on returns rather than prices: regression and mean estimation on non-stationary series produce many spurious results.
Intuition: Moutai's price rose from 1000 yuan to 1500 yuan, so a "mean of 1250 yuan" has no predictive meaning; but "average daily return 0.09%, volatility 1.87%" is a relatively stable feature. Modeling must rest on stable features.
Limitations of correlation
Article 7 compared the three liquor stocks with a correlation heatmap; does a high Pearson correlation coefficient mean you can trade them? Not enough.
Correlation has two fatal limitations:
First, correlation only measures the "magnitude of rising and falling together", it doesn't guarantee the difference between the two is stable - two stocks can rise and fall together while their gap keeps widening and never reverts.
Second, correlation drifts; assets highly correlated in a bull market may decouple instantly in a crisis.
To judge "whether the gap between the two will revert", you need a stronger tool than correlation - cointegration.
Cointegration: the foundation of pairs trading
Cointegration answers the question: for two individually non-stationary series, is their linear combination (the spread) stationary?
If the spread is stationary, it means the spread falls back after rising high and rises back after falling low - this is exactly the Source of pairs-trading profit: sell high, buy low, wait for the spread to revert.
statsmodels' coint function directly performs the cointegration test; the null hypothesis is "no cointegration relationship". Run a scan over same-industry candidate pairs:
Example
from
statsmodels.
tsa
.
stattools
import
coint
import
yfinance
as
yf
candidates
=
[
(
"Wuliangye"
,
"Luzhou Laojiao"
,
"000858.SZ"
,
"000568.SZ"
)
,
(
"ICBC"
,
"China Merchants Bank"
,
"601398.SS"
,
"600036.SS"
)
,
(
"Midea Group"
,
"Gree Electric"
,
"000333.SZ"
,
"000651.SZ"
)
,
(
"Kweichow Moutai"
,
"Wuliangye"
,
"600519.SS"
,
"000858.SZ"
)
,
]
for
n1
,
n2
,
c1
,
c2
in
candidates:
px
=
yf.
download
(
[
c1
,
c2
]
,
start
=
"2022-01-01"
,
end
=
"2024-12-31"
,
progress
=
False
,
multi_level_index
=
False
)
[
"Close"
]
x
,
y
=
px
[
c1
]
.
dropna
(
)
,
px
[
c2
]
.
dropna
(
)
idx
=
x.
index
.
intersection
(
y.
index
)
t
,
p
,
_
=
coint
(
x.
loc
[
idx
]
,
y.
loc
[
idx
]
)
verdict
=
"Passed"
if
p
<
0.05
else"Not passed"
(
f
"{n1} vs {n2}: p = {p:.4f} {verdict}"
)
The output is shown below:
五粮液 vs 泸州老窖: p = 0.2166 未通过
工商银行 vs 招商银行: p = 1.0000 未通过
美的集团 vs 格力电器: p = 0.0617 未通过
贵州茅台 vs 五粮液: p = 0.2300 未通过
Using the same method to scan oil and petrochemicals (PetroChina vs Sinopec p=0.4855), insurance (Ping An vs China Life p=0.1590), telecom operators (China Mobile vs China Telecom p=0.3953) and other industries, none of the seven candidate pairs passed the 5% significance test.
This "total wipeout" result is very educational:
| Common misconception | Fact |
|---|---|
| Same-industry stocks can be paired | None of the seven same-industry candidates passed the test |
| High correlation equals cointegration | These pairs all have correlations above 0.7, yet are still not cointegrated |
| Cointegration lasts forever once found | Even if it passed historically, structural changes can make it fail |
Among the seven, Midea Group and Gree Electric are the closest (p=0.0617), used as the teaching demo case for pairs trading in the next article - but it doesn't reach the 5% significance level, and this point runs through the next article's conclusions.
Hedge ratio and spread
Beyond the cointegration test, pairs trading also needs to estimate the hedge ratio: how many shares of Gree correspond to one share of Midea. The simplest method is the linear regression slope:
Example
import
numpy
as
np
import
yfinance
as
yf
px
=
yf.
download
(
[
"000333.SZ"
,
"000651.SZ"
]
,
start
=
"2022-01-01"
,
end
=
"2024-12-31"
,
progress
=
False
,
multi_level_index
=
False
)
[
"Close"
]
Estimate using only 2022 data to avoid using future information
a
=
px
[
"000333.SZ"
]
.
loc
[
"2022"
]
Midea
b
=
px
[
"000651.SZ"
]
.
loc
[
"2022"
]
Gree
beta
=
np.
polyfit
(
b
,
a
,
1
)
[
0
]
(
f
"Hedge ratio beta = {beta:.4f}"
)
Spread = Midea price - beta x Gree price
spread
=
px
[
"000333.SZ"
]
- beta * px
[
"000651.SZ"
]
(
"Last 3 days of the spread:"
)
(
spread.
tail
(
3
)
.
round
(
2
)
.
to_string
(
)
)
The output is shown below:
对冲比率 beta = 2.8141
Spread last 3 days:
Date
2024-12-26 9.06
2024-12-27 9.05
2024-12-30 8.29
Meaning: go long 1 share of Midea while shorting 2.81 shares of Gree; the value of this combination is the spread. The next article will build complete trading rules around this spread.