Python量化交易中使用遗传算法进行多目标参数优化

半杯拿铁
半杯拿铁
发布时间:2026-12-06 | 759人浏览过
原创

使用 deap 库构建遗传算法框架,通过定义适应度函数与变异算子,在交易策略参数空间中搜索夏普比率最大且回撤最小的最优解集。

Python量化交易中使用遗传算法进行多目标参数优化

多目标优化中的适应度设计

量化策略通常面临收益与风险的权衡,需将多个指标合并为单一适应度值或采用 Pareto 前沿分析。本节重点说明如何构建包含年化收益率、最大回撤及夏普比率的综合评估逻辑。

Python量化交易中使用遗传算法进行多目标参数优化

在遗传算法中,个体代表一组策略参数(如均线周期、止损阈值)。适应度函数需返回一个元组或多维向量,以支持非支配排序。若简化处理,可赋予不同权重,例如:Fitness = w1 * Sharpe - w2 * MaxDrawdown。需注意,历史回测数据的质量直接影响适应度计算的准确性,建议使用滚动窗口验证以避免过拟合。

基于 deap 的完整实现流程

代码应保存为 ga_optimizer.py,安装依赖后直接运行即可输出迭代过程中的最佳参数组合。

Python量化交易中使用遗传算法进行多目标参数优化

from deap import base, creator, tools
import random

# 定义最大化适应度
creator.create("FitnessMax", base.Fitness, weights=(1.0, -1.0)) # 假设第一目标最大化,第二目标最小化(如回撤)
creator.create("Individual", list, fitness=creator.FitnessMax)

toolbox = base.Toolbox()

# 参数范围:[short_window, long_window, threshold]
toolbox.register("attr_float", random.uniform, 5, 50)
toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_float, n=3)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)

# 模拟适应度计算
def evaluate(individual):
    # 此处替换为实际的回测引擎调用
    ret = individual[0] * 0.1 
    drawdown = abs(individual[1] - 20) 
    return ret, drawdown

toolbox.register("evaluate", evaluate)
toolbox.register("mate", tools.cxUniform, indpb=0.5)
toolbox.register("mutate", tools.mutGaussian, mu=0, sigma=1, indpb=0.2)
toolbox.register("select", tools.selNSGA2)

pop = toolbox.population(n=50)
hof = tools.ParetoFront()

for gen in range(10):
    offspring = toolbox.select(pop, len(pop))
    offspring = list(map(toolbox.clone, offspring))
    for child1, child2 in zip(offspring[::2], offspring[1::2]):
        if random.random() < 0.5:
            toolbox.mate(child1, child2)
            del child1.fitness.values
            del child2.fitness.values
    for mutant in offspring:
        if random.random() < 0.2:
            toolbox.mutate(mutant)
            del mutant.fitness.values
            
    invalids = [ind for ind in offspring if not ind.fitness.valid]
    for ind in invalids:
        ind.fitness.values = toolbox.evaluate(ind)
        hof.add(ind)
    pop = offspring
    print(f"Gen {gen}: Best Fitness = {hof[0].fitness.values}")

程序运行后将打印每一代的 Pareto 最优解集。输入为初始随机参数,输出为经过10代进化后的近似最优参数组合。若发现结果波动较大,请检查变异算子的 sigma 值是否过大,导致参数偏离合理区间。

初始化种群时,设定参数的上下界范围。交叉操作模拟基因重组,变异操作引入随机扰动以防局部最优。每代结束后,记录当前最优个体的参数及其对应的绩效指标。

变异率对收敛稳定性的影响

较高的变异率有助于跳出局部最优,但可能导致种群多样性过高而难以收敛;较低的变异率则容易陷入早熟收敛。

在实际调试中,建议观察最终几代的适应度变化曲线。若曲线平稳但非全局最优,可适当提高变异概率。同时,固定随机种子可确保实验的可复现性,便于对比不同参数设置的效果。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表