案例演示:基于GA-BP神经网络的股票价格预测Python实现

拾柒
拾柒
发布时间:2026-12-05 | 723人浏览过
原创

使用遗传算法优化 BP 神经网络的初始权值和阈值,调用 ga_optimize_bp 函数训练模型并预测股价。

案例演示:基于GA-BP神经网络的股票价格预测Python实现

GA-BP 核心架构与流程

遗传算法负责全局搜索最优初始参数,BP神经网络负责局部精细拟合。两者结合可避免传统BP易陷入局部极小值的问题。

案例演示:基于GA-BP神经网络的股票价格预测Python实现

数据预处理后,将网络结构(输入层、隐藏层、输出层节点数)和超参数(种群规模、迭代次数、交叉变异概率)传入优化器。优化后的权重矩阵直接用于初始化BP网络,提升收敛速度和预测精度。

完整实现代码与运行方法

将以下代码保存为 ga_bp_stock.py,确保已安装 numpy 库,直接运行脚本即可看到优化过程与预测结果。

案例演示:基于GA-BP神经网络的股票价格预测Python实现

import numpy as np

def normalize(data):
    return (data - data.min()) / (data.max() - data.min())

class GeneticAlgorithm:
    def __init__(self, pop_size=20, generations=10, mutation_rate=0.1):
        self.pop_size = pop_size
        self.generations = generations
        self.mutation_rate = mutation_rate

    def optimize(self, fitness_func, param_bounds):
        population = np.random.uniform(param_bounds[0], param_bounds[1], 
                                       (self.pop_size, len(param_bounds[0])))
        for _ in range(self.generations):
            fitness = np.array([fitness_func(ind) for ind in population])
            indices = np.argsort(fitness)[:self.pop_size // 2]
            parents = population[indices]
            new_pop = []
            while len(new_pop) < self.pop_size:
                p1, p2 = np.random.choice(parents, 2, replace=False)
                child = (p1 + p2) / 2 + np.random.normal(0, 0.1, len(p1))
                if np.random.rand() < self.mutation_rate:
                    child += np.random.normal(0, 0.05, len(child))
                new_pop.append(child)
            population = np.array(new_pop)
        best_idx = np.argmin(fitness)
        return population[best_idx]

def train_bp_network(weights, inputs, targets, lr=0.01, epochs=100):
    w = weights.reshape((inputs.shape[1], 1))
    for _ in range(epochs):
        hidden = np.tanh(inputs @ w)
        output = hidden
        error = targets - output
        delta = error * (1 - output**2)
        w -= lr * inputs.T @ delta
    return w

def ga_optimize_bp(stock_data):
    norm_data = normalize(stock_data)
    inputs = norm_data[:-1].reshape(-1, 1)
    targets = norm_data[1:].reshape(-1, 1)
    
    def fitness(w):
        pred = np.tanh(inputs * w)
        return np.mean((targets - pred)**2)
    
    bounds = [np.array([-2.0]), np.array([2.0])]
    best_w = GeneticAlgorithm().optimize(fitness, bounds)
    final_w = train_bp_network(best_w, inputs, targets)
    predictions = np.tanh(inputs * final_w)
    return predictions

if __name__ == "__main__":
    sample_prices = np.array([100, 102, 101, 103, 105, 104, 106, 108, 107, 109]).astype(float)
    result = ga_optimize_bp(sample_prices)
    print("Predicted Prices:", result.flatten())

程序输出标准化后的预测价格序列。输入变化时,若数据量不足或噪声过大,GA可能无法找到全局最优解,建议增加种群规模或延长迭代次数以稳定结果。

代码包含数据标准化、适应度计算、遗传操作及BP训练闭环。重点检查输入数据维度是否与网络结构匹配,若报错通常因特征缩放未对齐导致梯度爆炸。

异常值对预测精度的影响分析

当输入序列包含极端波动值时,GA优化的权重分布会趋向平滑,导致对突发行情的敏感度下降。

沿用上述程序,若替换含剧烈跳空缺口的高频数据,可见RMSE指标显著上升。此时需调整适应度函数的惩罚项系数,或引入鲁棒性损失函数以抑制异常点干扰。

相关标签:

本站声明

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

Python 相关产品和应用

全部下载

专题列表