Python Quantitative Data Cleaning and Processing
Raw financial data is almost always 'dirty': trading halts cause missing values, dividends cause gaps, and extreme markets cause outliers.
Garbage in, garbage out - the quality of the input data directly determines the credibility of backtest conclusions.
This article uses real Moutai data to demonstrate the four most common cleaning operations.
Common Problems in Financial Data
After obtaining a dataset, you usually need to check for and handle the following four types of problems:
| Problem | Source | Handling Method |
|---|---|---|
| Missing Values | Trading halts, early listing period, missing data from the source | Forward fill or drop |
| Outliers | Genuine extreme markets, data errors | First distinguish real from false, then decide how to handle |
| Price Gaps | Dividends, bonus shares and ex-rights | Use adjusted prices instead |
| Irregular Frequency | Different markets have different trading calendars | Resampling and alignment |
The previous article already covered the causes of price gaps and adjusted-price handling; this article focuses on the other three types.
Handling Missing Values
First create missing values artificially, then demonstrate the standard workflow. For financial time series, forward fill is the first choice: during a trading halt there is no new price, so substituting the most recent valid price is the most reasonable.
Example
import
yfinance
as
yf
import
numpy
as
np
Download Moutai's adjusted closing prices (2019-2024)
close
=
yf.
download
(
"600519.SS"
,
start
=
"2019-01-01"
,
end
=
"2024-12-31"
,
progress
=
False
,
multi_level_index
=
False
)
[
"Close"
]
Artificially remove 3 days of data to simulate trading-halt gaps
dirty
=
close.
copy
(
)
dirty.
iloc
[
10
:
13
]
=
np.
nan
(
"Missing count after punching holes:"
,
int
(
dirty.
isna
(
)
.
sum
(
)
)
)
Forward fill: fill with the most recent valid price
filled
=
dirty.
ffill
(
)
(
"Missing count after ffill:"
,
int
(
filled.
isna
(
)
.
sum
(
)
)
)
(
filled.
iloc
[
9
:
14
]
.
round
(
2
)
.
to_string
(
)
)
The output is shown below:
挖空后缺失数: 3
ffill 填充后缺失数: 0
Date
2019-01-15 550.41
2019-01-16 550.41
2019-01-17 550.41
2019-01-18 550.41
2019-01-21 572.93
All three missing rows are filled with the January 15 closing price of 550.41, until a new price appears on January 21.
Note: do not use backward fill (bfill) on backtest data - it fills 'future prices' into 'past dates', a typical look-ahead bias. Likewise, filling a time series with the mean or median introduces unnatural structure beyond the information that should be known at that point in time.
Outlier Detection
The most common outlier criterion in return series is the 3σ principle: points deviating from the mean by more than 3 standard deviations are treated as anomalies.
But be extra careful with financial data: points beyond 3σ are not necessarily errors, they may just be genuine extreme markets.
Example
Daily Returns
ret
=
close.
pct_change
(
)
.
dropna
(
)
Filter out outliers with the 3σ principle
mu
,
sd
=
ret.
mean
(
)
,
ret.
std
(
)
outliers
=
ret
[
(
ret - mu
)
.
abs
(
)
3
- sd
]
(
f
"Daily return mean {mu:.4%} std {sd:.4%}"
)
(
f
"3σ outliers: {len(outliers)}"
)
(
outliers.
round
(
4
)
.
to_string
(
)
)
The output is shown below:
日收益率均值 0.0901% 标准差 1.8671%
22 3-sigma outliers:
Date
2020-07-16 -0.0790
2021-09-27 0.0950
2022-10-24 -0.0756
2022-11-01 0.0830
2024-09-24 0.0880
2024-09-26 0.0929
2024-09-30 0.0729
2024-10-09 -0.0742
...(共 22 个)
Spot-checking a few dates confirms this: July 16, 2020 was a sharp drop in the liquor sector, and late September 2024 was a policy-driven broad surge - these are all real market moves and must never be deleted.
The correct workflow is: first use 3σ or the interquartile range (IQR) to fish out outliers, then check one by one whether they are data errors (such as a misplaced decimal point, a price of 0, or a missed adjustment), and only correct those confirmed to be errors.
Common pitfall: beginners often delete the ±10% limit-up/limit-down days as outliers, which removes the most genuine institutional feature of A-shares. The purpose of outlier detection is to 'discover', not to 'delete'.
Frequency Conversion
When studying weekly or monthly strategies, you need to resample daily data to a lower frequency. pandas resample does it in one line:
Example
Weekly: take the last trading day of each week (W-FRI means the week ends on Friday)
weekly
=
close.
resample
(
"W-FRI"
)
.
last
(
)
Monthly: take the last trading day of each month
monthly
=
close.
resample
(
"ME"
)
.
last
(
)
(
"Last 3 weekly rows:"
)
(
weekly.
tail
(
3
)
.
round
(
2
)
.
to_string
(
)
)
(
"Last 3 monthly rows:"
)
(
monthly.
tail
(
3
)
.
round
(
2
)
.
to_string
(
)
)
The output is shown below:
Last 3 lines of the week:
Date
2024-12-20 1433.74
2024-12-27 1440.31
2025-01-03 1436.57
Freq: W-FRI
Last 3 lines of the monthly line:
Date
2024-10-31 1417.04
2024-11-30 1415.14
2024-12-31 1436.57
Freq: ME
When resampling, aggregation rules depend on the field: prices use last (or first), volume uses sum, the highest price uses max, and the lowest price uses min.
Plotting daily and weekly lines together shows that the weekly line is the 'skeleton' of the daily line:
Example
import
matplotlib.
pyplot
as
plt
plt.
figure
(
figsize
=
(
12
,
6
)
)
plt.
plot
(
close.
loc
[
"2024-01-01"
:
]
,
label
=
"Daily"
,
color
=
"#1f2933"
,
linewidth
=
1.0
,
alpha
=
0.6
)
plt.
plot
(
weekly.
loc
[
"2024-01-01"
:
]
,
label
=
"Weekly (W-FRI)"
,
color
=
"#14805e"
,
linewidth
=
2
)
plt.
title
(
"Maotai: Daily vs Weekly Resampled Close (2024)"
)
plt.
xlabel
(
"Date"
)
plt.
ylabel
(
"Price (CNY)"
)
plt.
legend
(
)
plt.
grid
(
alpha
=
0.25
)
plt.
show
(
)
Run the code above and the output chart is as follows:

Tip: the reverse operation (low to high frequency) can only be 'guessed' through interpolation and produces no real information; avoid using interpolated high-frequency data in backtests.
Date Alignment Across Multiple Stocks
Different stocks may have inconsistent trading calendars (halts, different listing dates), so subtracting directly misaligns them. pandas automatically aligns by index and fills NaN during arithmetic; the approach is to align first, then clean:
Example
import
yfinance
as
yf
Download the adjusted closing prices of two stocks
prices
=
yf.
download
(
[
"600519.SS"
,
"000858.SZ"
]
,
start
=
"2023-01-01"
,
end
=
"2024-12-31"
,
progress
=
False
,
multi_level_index
=
False
)
[
"Close"
]
After alignment, apply a uniform forward fill to ensure both prices exist for every day
prices
=
prices.
ffill
(
)
.
dropna
(
)
(
"Row count after alignment:"
,
len
(
prices
)
)
Only after alignment can you safely compute ratios, cointegration, spreads and the like
ratio
=
prices
[
"600519.SS"
]
/ prices
[
"000858.SZ"
]
(
ratio.
tail
(
3
)
.
round
(
4
)
.
to_string
(
)
)
The output is shown below:
对齐后行数: 483
Date
2024-12-26 11.1941
2024-12-27 11.2004
2024-12-30 11.2749
Remember this order: align first, then fill, then compute. Operating on unaligned data lets NaN silently swallow a large number of samples.