Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Parameter Optimization and Overfitting Prevention

Python Parameter Optimization and Overfitting Prevention

Earlier chapters mentioned the three major backtesting traps, of which overfitting is the most insidious: it throws no error, gives no warning, and even comes with a beautiful backtest report.

This chapter deliberately creates overfitting on real data, then exposes it with two lines of defense: in-sample/out-of-sample separation and Walk-Forward.

All numbers come from actual computations of the dual moving average strategy on Moutai 2019-2024.


Grid Search: Try Every Parameter Combination

The dual moving average has two parameters, fast and slow. Backtest every combination to get a complete "parameter-return" map:

Example

import

yfinance

as

yf

import

pandas

as

pd

close

=

yf.

download

(

"600519.SS"

,

start

=

"2019-01-01"

,

end

=

"2024-12-31"

,

                    progress

=

False

,

multi_level_index

=

False

)

[

"Close"

]

ret

=

close.

pct_change

(

)

fast_list

=

[

5

,

10

,

15

,

20

,

25

,

30

]

slow_list

=

[

40

,

60

,

80

,

100

,

120

]

grid

=

pd.

DataFrame

(

index

=

slow_list

,

columns

=

fast_list

,

dtype

=

float

)

for

f_

in

fast_list:

   

for

s_

in

slow_list:

        ma_f

=

close.

rolling

(

f_

)

.

mean

(

)

        ma_s

=

close.

rolling

(

s_

)

.

mean

(

)

        sig

=

(

ma_f

ma_s

)

.

astype

(

int

)

             

1 for holding, 0 for being out of the market

        r

=

(

sig.

shift

(

1

)

)

.

dropna

(

)

           

Signals are executed the next day

        cum

=

(

1

)

.

cumprod

(

)

        grid.

loc

[

s_

,

f_

]

=

cum.

iloc

[

1

]

**

(

252

/

len

(

r

)

)

1

print

(

(

grid *

100

)

.

round

(

1

)

.

to_string

(

)

)

print

(

f

"Best parameters: fast={grid.stack().idxmax()[1]}, "

      f

"slow={grid.stack().idxmax()[0]}, "

      f

"annualized {grid.stack().max():.2%}"

)

The output is as follows (unit: %):



        5     10    15    20    25    30

40   11.1   4.2   4.8   8.7  10.7   7.7

60    9.8   9.1  10.2  10.9  12.6  14.4

80    6.5   8.4  11.9  11.4  10.8  12.5

100   6.2   7.4   9.3   8.8   8.7   7.4

120   1.9   2.6   3.6   3.7   1.2   2.4



最优参数: fast=30, slow=60, 年化 14.44%

Plot the grid as a heatmap so the "plateaus" and "valleys" of the parameter terrain are clear at a glance:

Example

import

matplotlib.

pyplot

as

plt

fig

,

ax

=

plt.

subplots

(

figsize

=

(

10

,

6

)

)

im

=

ax.

imshow

(

grid.

values

.

astype

(

float

)

,

cmap

=

"RdYlGn"

,

aspect

=

"auto"

)

ax.

set_xticks

(

range

(

len

(

fast_list

)

)

,

[

str

(

x

)

for

x

in

fast_list

]

)

ax.

set_yticks

(

range

(

len

(

slow_list

)

)

,

[

str

(

x

)

for

x

in

slow_list

]

)

ax.

set_xlabel

(

"Fast MA (days)"

)

ax.

set_ylabel

(

"Slow MA (days)"

)

ax.

set_title

(

"Dual MA Grid Search: Annualized Return (%)"

)

for

i

in

range

(

len

(

slow_list

)

)

:

   

for

j

in

range

(

len

(

fast_list

)

)

:

        ax.

text

(

j

,

i

,

f

"{grid.values[i, j]*100:.0f}"

,

                ha

=

"center"

,

va

=

"center"

,

fontsize

=

10

)

fig.

colorbar

(

im

,

ax

=

ax

,

label

=

"Annualized Return"

)

fig.

tight_layout

(

)

plt.

show

(

)

Run the code above and the output chart is as follows:

Dual Moving-Average Parameter Grid Heatmap

Choose parameters by the terrain, not just the highest point:

Terrain Feature Interpretation Response
Isolated spike Typical symptom of parameter overfitting: change a parameter and it collapses Discard it outright
Flat plateau Robust strategy logic, insensitive to parameters Preferred choice, take the region's center value

In this example, the region with fast line 15-30 and slow line 60-80 forms a contiguous zone delivering 10%-14% annualized returns, a healthy plateau terrain; while the entire slow line 120 row collapses, meaning the signal is too sluggish. The optimum 30/60 sits right at the plateau edge - the safe choice is the plateau center (e.g. 20/60 or 25/60), not the maximum on the boundary.


In-sample / out-of-sample split: the first line of defense

The grid uses full-range 2019-2024 data to pick the "optimal parameters"; the problem is: these parameters have seen all the exam questions.

The correct approach is to split the data into two parts: in-sample (IS, 2019-2023) to tune parameters, out-of-sample (OOS, 2024) for the exam:

Example

is_mask

=

close.

index

<

"2024-01-01"

oos_mask

=

close.

index

=

"2024-01-01"

   

Out-of-sample: 2024

Select parameters only in-sample

best_f

,

best_s

=

30

,

60

                 

Derived from the in-sample grid

ma_f

=

close.

rolling

(

best_f

)

.

mean

(

)

ma_s

=

close.

rolling

(

best_s

)

.

mean

(

)

sig

=

(

ma_f

ma_s

)

.

astype

(

int

)

r_is

=

(

sig.

shift

(

1

)

)

[

is_mask

]

.

dropna

(

)

r_oos

=

(

sig.

shift

(

1

)

)

[

oos_mask

]

.

dropna

(

)

cum_is

=

(

1

)

.

cumprod

(

)

cum_oos

=

(

1

)

.

cumprod

(

)

print

(

f

"In-sample optimum: 30/60, IS annualized {cum_is.iloc[-1] ** (252/len(r_is)) - 1:.2%}"

)

print

(

f

"This parameter 2024 out-of-sample: annualized {cum_oos.iloc[-1] ** (252/len(r_oos)) - 1:.2%}"

)

print

(

f

"2024 buy-and-hold: {close[oos_mask].iloc[-1]/close[oos_mask].iloc[0]-1:.2%}"

)

The output is shown below:



样本内最优: 30/60, IS 年化 19.62%

该参数 2024 样本外: 年化 -0.40%

2024 买入持有: -6.18%

In-sample annualized 19.62%, out-of-sample drops straight to -0.40% - a shrinkage of 20 percentage points.

This is the true face of overfitting: the parameters fit the 2019-2023 market structure perfectly, but the 2024 market changed. To be fair, out-of-sample beat buy-and-hold by 6 percentage points, so the strategy isn't worthless, but expecting "19.6% annualized" will disappoint.

Discipline: out-of-sample data can be used only once. Repeatedly "peeking" at out-of-sample results and going back to tune parameters turns out-of-sample into a bigger in-sample, making the defense useless.


Walk-Forward: let time test the parameters

In/out-of-sample splits the data only once, so conclusions are easily affected by how it's cut. Walk-Forward (rolling-forward validation) replays the full "use history to pick parameters, execute in the future" process once every year:

2019 2020 2021 2022 2023 2024 Round 1 Training Test 2020 Round 2 Training 2019-2020 Test 2021 Round 3 Training 2019-2021 Test 2022 Round 4 Training 2019-2022 Test 2023 Round 5 Training 2019-2023 Testing Training window (select parameters) Test window (real execution)

Implementation just needs a loop over the years:

Example

for

year

in

range

(

2020

,

2025

)

:

    tr_mask

=

close.

index

<

f

"{year}-01-01"

te_mask

=

(

close.

index

=

f

"{year}-01-01"

)

& \

             

(

close.

index

<

f

"{year + 1}-01-01"

)

               

Test: that year

   

Step 1: find the parameters with the highest annualized return on the training set

    best_p

,

best_v

=

None

,

9e9

   

for

f_

in

fast_list:

       

for

s_

in

slow_list:

            ma_f

,

ma_s

=

close.

rolling

(

f_

)

.

mean

(

)

,

close.

rolling

(

s_

)

.

mean

(

)

            sig

=

(

ma_f

ma_s

)

.

astype

(

int

)

            r_tr

=

(

sig.

shift

(

1

)

)

[

tr_mask

]

.

dropna

(

)

            v

=

(

(

1

)

.

cumprod

(

)

.

iloc

[

1

]

**

(

252

/

len

(

r_tr

)

)

1

)

           

if

v

best_v:

                best_v

,

best_p

=

v

,

(

f_

,

s_

)

   

Step 2: execute in the test year with the selected parameters

    ma_f

,

ma_s

=

close.

rolling

(

best_p

[

0

]

)

.

mean

(

)

,

close.

rolling

(

best_p

[

1

]

)

.

mean

(

)

    sig

=

(

ma_f

ma_s

)

.

astype

(

int

)

    r_te

=

(

sig.

shift

(

1

)

)

[

te_mask

]

.

dropna

(

)

    v_te

=

(

1

)

.

cumprod

(

)

.

iloc

[

1

]

**

(

252

/

len

(

r_te

)

)

1

   

print

(

f

"{year}: selected {best_p} | training-period performance {best_v:.2%} | out-of-sample {v_te:.2%}"

)

The output is shown below:



2020 年: 选中 (25, 60) | 训练期表现 41.58% | 样本外 68.12%

2021 年: 选中 (30, 60) | 训练期表现 58.09% | 样本外 3.01%

2022 年: 选中 (30, 60) | 训练期表现 37.00% | 样本外 -5.58%

2023 年: 选中 (30, 60) | 训练期表现 24.84% | 样本外 0.81%

2024 年: 选中 (30, 60) | 训练期表现 19.62% | 样本外 -8.40%

This table is the most important one in the whole article:

Observation Meaning
Four of five years selected the same parameter set (30, 60) The parameters have some stability, not pure noise
Training-period performance fell steadily from 41.58% to 19.62% A parameter's "historical track record" decays naturally; don't extrapolate linearly
Out-of-sample is sometimes good, sometimes bad (68% to -8%) Parameters can't handle market regime shifts; Moutai after 2022 is no longer the Moutai of 2019

The value of Walk-Forward lies not in picking better parameters, but in giving an unbiased expectation of parameter decay: the average out-of-sample performance after repeated yearly re-optimization is the trustworthy level of this strategy in this market.


Monte Carlo permutation: is this really the strategy's merit?

The last line of defense answers a philosophical question: could good results just be luck? The method is brutally simple - randomly shuffle the strategy signals hundreds of times and look at the return distribution of a "guessing strategy".

If the real strategy's return only ranks in the top 30% of the random distribution, it's no different from a coin flip; only ranking in the top 5% lets you say with confidence that the signal contains real information.

Test Approach Question Answered
Grid terrain Check whether the parameter-return surface is flat Are the parameters robust?
In-sample / out-of-sample Set aside a stretch of data and test only once Can the results be extrapolated?
Walk-Forward Replay the full process year by year on a rolling basis What is the long-run trustworthy level?
Monte Carlo permutation Shuffle signals and compare to the random distribution Is it pure luck?