Introduction to Python Multi-Factor Strategies
All the previous strategies revolved around the time-series dimension: staring at one stock's historical prices to find signals. Multi-factor strategies switch to the 'cross-sectional' dimension: score all stocks in the market at the same moment, buy the high scorers and sell the low ones.
This is the mainstream framework of quant institutions; this article uses a small pool of 20 A-shares to walk through the full standard process of factor construction - IC testing - layered backtesting. The results are likewise presented honestly - including a momentum factor that fails.
What Is a Factor
A factor is a stock characteristic we believe can predict future returns. Common factor categories used in the industry:
| Factor Category | Representative Factors | Logic |
|---|---|---|
| Momentum | Past 6-12 month gains | The strong stay strong (in mature overseas markets) |
| Value | Inverse of P/E and P/B ratios | Cheap stocks are undervalued |
| Quality | ROE, gross margin, debt ratio | Good companies deserve a premium |
| Size | Total market capitalization (small-cap factor) | Small companies have greater elasticity |
This article uses the most intuitive momentum factor as a teaching case: score stocks by their gains over the past 120 days (about 6 months).
Example
import
yfinance
as
yf
import
pandas
as
pd
A stock pool of 20 cross-industry A-shares (consumer / finance / pharma / new energy / tech, etc.)
pool
=
[
"600519.SS"
,
"000858.SZ"
,
"000568.SZ"
,
"601398.SS"
,
"600036.SS"
,
"601318.SS"
,
"600276.SS"
,
"300760.SZ"
,
"300750.SZ"
,
"002594.SZ"
,
"300274.SZ"
,
"002415.SZ"
,
"000063.SZ"
,
"000651.SZ"
,
"000333.SZ"
,
"601668.SS"
,
"601899.SS"
,
"600309.SS"
,
"600900.SS"
,
"688981.SS"
]
close
=
yf.
download
(
pool
,
start
=
"2022-01-01"
,
end
=
"2024-12-31"
,
progress
=
False
,
multi_level_index
=
False
)
[
"Close"
]
Momentum factor: past 120-day gains (a factor value matrix with one row per day and one column per stock)
momentum
=
close / close.
shift
(
120
)
1
(
"Factor matrix shape:"
,
momentum.
shape
)
IC: A Checkup Report on a Factor's Predictive Power
Whether a factor is good cannot rely on belief - you must compute IC (Information Coefficient): at each month end, compute the cross-sectional correlation between 'factor values' and 'next month's returns'.
A positive and stable IC means stocks with high factor values do indeed rise more the next month; an IC near 0 means the factor is mysticism.
Example
Month-end sampling: factor values and next month's returns
me
=
close.
resample
(
"ME"
)
.
last
(
)
mom_m
=
momentum.
resample
(
"ME"
)
.
last
(
)
fwd
=
me.
shift
(
1
)
/ me -
1
Next Month's Returns
ics
=
[
]
for
d
in
mom_m.
index
[
7
:-
1
]
:
The first 6 months are reserved for momentum warm-up
f
=
mom_m.
loc
[
d
]
.
dropna
(
)
fr
=
fwd.
loc
[
d
]
.
dropna
(
)
common
=
f.
index
.
intersection
(
fr.
index
)
if
len
(
common
)
=
15
:
Spearman rank correlation: more robust to extreme values
ics.
append
(
f.
loc
[
common
]
.
corr
(
fr.
loc
[
common
]
,
method
=
"spearman"
)
)
ics
=
pd.
Series
(
ics
)
(
f
"Monthly IC samples {len(ics)} | IC mean {ics.mean():.4f} | IC std {ics.std():.4f}"
)
(
f
"ICIR = {ics.mean()/ics.std():.4f} | IC>0 ratio {(ics>0).mean():.2%}"
)
The output is shown below:
月度 IC 样本数 28 | IC 均值 -0.0639 | IC 标准差 0.3561
ICIR = -0.1795 | IC>0 占比 46.43%
The result is surprising yet reasonable: IC is negative. In this sample of 20 A-shares over 2022-2024, stocks that rose more in the past are instead more likely to fall the next month.
| Pointer | This Example | Commonly Believed |
|---|---|---|
| IC Absolute Value | 0.064 | Greater than 0.03 means informative |
| IC Direction | Negative (reversal effect) | The momentum factor is usually positive in US stocks |
| ICIR | -0.18 | An absolute value greater than 0.3 is relatively stable |
This is precisely the famous characteristic of A-shares: weak short-term momentum and a strong reversal effect, a conclusion reached by much academic and practical research. Copying the knowledge that 'the momentum factor works in US stocks' onto A-shares will be slapped in the face by the data.
A negative IC does not mean the work was wasted - a negative-IC factor used in reverse becomes a positive-IC one. Use layered backtesting to verify this finding.
Layered Backtesting: Turning a Factor into Portfolios
Layered backtesting is the 'live-fire exercise' of factor testing: at each month end, split stocks into 5 groups by factor value, hold them equal-weighted for one month, and see whether the group returns are orderly.
Example
layers
=
{
i:
[
]
for
i
in
range
(
5
)
}
for
d
in
mom_m.
index
[
7
:-
1
]
:
f
=
mom_m.
loc
[
d
]
.
dropna
(
)
fr
=
fwd.
loc
[
d
]
.
dropna
(
)
common
=
f.
index
.
intersection
(
fr.
index
)
if
len
(
common
)
<
15
:
continue
ranked
=
f.
loc
[
common
]
.
rank
(
pct
=
True
)
for
i
in
range
(
5
)
:
Group i: stocks whose factor rank falls in the (i/5, (i+1)/5] interval
grp
=
ranked
[
(
ranked
i *
0.2
)
&
(
ranked
<=
(
i +
1
)
0.2
)
]
.
index
layers
[
i
]
.
append
(
fr.
loc
[
grp
]
.
mean
(
)
)
layer_ret
=
pd.
DataFrame
(
layers
,
index
=
mom_m.
index
[
7
:-
1
]
)
(
"Monthly average return by group:"
)
for
i
in
range
(
5
)
:
(
f
"Group {i+1}: {layer_ret[i].mean():.4%}/month"
)
q1
=
(
1
- layer_ret
[
0
]
.
mean
(
)
)
**
12
1
q5
=
(
1
- layer_ret
[
4
]
.
mean
(
)
)
**
12
1
(
f
"Group1 annualized {q1:.2%} | Group5 annualized {q5:.2%} | long-short annualized spread {q5-q1:.2%}"
)
The output is shown below:
Monthly average return for each group:
第 1 组(动量最低): 1.5296%/月
第 2 组: 1.4587%/月
第 3 组: 1.5851%/月
第 4 组: 0.8594%/月
第 5 组(动量最高): 0.3194%/月
第1组年化 19.98% | 第5组年化 3.90% | 多空年化差 -16.08%
Plot the cumulative net value of the five groups:
Example
import
matplotlib.
pyplot
as
plt
cum_layers
=
(
1
- layer_ret.
fillna
(
0
)
)
.
cumprod
(
)
fig
,
ax
=
plt.
subplots
(
figsize
=
(
12
,
6
)
)
colors
=
[
"#c0563f"
,
"#e0a458"
,
"#8a95a1"
,
"#3a9d8f"
,
"#14805e"
]
for
i
in
range
(
5
)
:
label
=
f
"Group {i+1}"
(
" (Low Momentum)"
if
i
==
0
else
" (High Momentum)"
if
i
==
4
else
""
)
ax.
plot
(
cum_layers.
index
,
cum_layers
[
i
]
,
color
=
colors
[
i
]
,
linewidth
=
1.5
,
label
=
label
)
ax.
set_title
(
"Momentum Factor: Layered Portfolio Cumulative Return (2022-2024)"
)
ax.
set_xlabel
(
"Date"
)
ax.
set_ylabel
(
"Cumulative Return"
)
ax.
legend
(
)
ax.
grid
(
alpha
=
0.25
)
plt.
show
(
)
Run the code above and the output chart is as follows:

The five curves overall show a layering of 'the lower the momentum, the better the performance' - fully consistent with the negative IC, with two independent chains of evidence corroborating each other.
The Methodological Value of This Article
Finding a factor that fails is more valuable than seeing a profitable backtest:
| Step | Practice in This Article | Significance |
|---|---|---|
| Construct the Factor | 120-day momentum | Turn an idea into a computable number |
| IC Testing | Mean -0.064, ICIR -0.18 | Judge effectiveness with data rather than belief |
| Layered Backtesting | Clear monotonicity across the five groups | Verify the cross-sectional relationship between factor and returns |
| Conclusion | A-share momentum reversal over 2022-2024 | Factors depend on market and period, and must be tested locally |
Reminder: the sample in this article has only 20 stocks and 3 years of data, so the conclusion cannot be extrapolated directly to the whole market. In engineering practice it would be expanded to all A-shares, add industry and market-cap neutralization, and use professional tools like alphalens, but the process is exactly the same as in this article.