You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于LSTM的比特币价格预测:3个月后收盘价实现问询

如何修改LSTM代码预测比特币3个月后的收盘价

你的现有代码是基于window_len=5的历史数据预测下一个时间步的收盘价,要改成预测3个月后的价格,核心是调整数据配对逻辑(让历史窗口对应3个月后的目标值),以下是具体修改步骤:

1. 确定时间步换算

首先明确你的数据时间粒度:

  • 若为日K线:3个月约60-66个交易日(按每月22个交易日估算),定义future_steps = 60
  • 若为周K线:3个月约13周,定义future_steps = 13
  • 若为月K线:直接定义future_steps = 3

2. 修改数据准备函数(核心修改)

原代码中prepare_data函数的目标值(y)是窗口结束后第1个时间步的收盘价,现在要改成窗口结束后第future_steps个时间步的收盘价,同时截断无对应目标的窗口:

def prepare_data(df, target_col, window_len, zero_base, test_size, future_steps):
    train_data, test_data = train_test_split(df, test_size=test_size)
    
    # 生成滑动窗口数据,截断最后future_steps个窗口(这些窗口无对应未来目标)
    X_train = extract_window_data(train_data, window_len, zero_base)[:-future_steps]
    X_test = extract_window_data(test_data, window_len, zero_base)[:-future_steps]
    
    # 目标值改为window_len + future_steps后的收盘价,与每个窗口一一对应
    y_train = train_data[target_col][window_len + future_steps:].values
    y_test = test_data[target_col][window_len + future_steps:].values
    
    if zero_base:
        # 归一化基准改为每个窗口起始位置的收盘价,对应调整索引
        y_train = y_train / train_data[target_col][:-window_len - future_steps].values - 1
        y_test = y_test / test_data[target_col][:-window_len - future_steps].values - 1

    return train_data, test_data, X_train, X_test, y_train, y_test

3. 调整参数与训练逻辑

在主代码中添加future_steps参数,并修改数据准备的调用:

np.random.seed(42)
window_len = 5
test_size = 0.2
zero_base = True
lstm_neurons = 100
epochs = 200
batch_size = 32
loss = 'mse'
dropout = 0.2
optimizer = 'adam'
# 根据数据粒度设置,这里以日频为例
future_steps = 60

train, test, X_train, X_test, y_train, y_test = prepare_data(
    hist, target_col, window_len=window_len, zero_base=zero_base, 
    test_size=test_size, future_steps=future_steps)

# 模型结构无需修改,仍为单值预测
model = build_lstm_model(
    X_train, output_size=1, neurons=lstm_neurons, dropout=dropout, loss=loss,
    optimizer=optimizer)

history = model.fit(
    X_train, y_train, validation_data=(X_test, y_test), 
    epochs=epochs, batch_size=batch_size, verbose=1, shuffle=True)

4. 修正预测值反归一化逻辑

原代码的反归一化基准索引需要对应调整,匹配新的目标值逻辑:

# 生成预测结果并反归一化
preds = model.predict(X_test)
preds = test[target_col].values[:-window_len - future_steps] * (preds + 1)
preds = pd.Series(index=test[target_col].index[window_len + future_steps:], data=preds.flatten())

# 提取对应时间段的实际收盘价用于对比
targets = test[target_col][window_len + future_steps:]
line_plot(targets, preds, '实际收盘价', '3个月后预测收盘价', lw=3)

关键注意事项

  • 数据量检查:确保训练/测试数据长度至少大于window_len + future_steps,否则会出现空数组报错
  • 预测局限性:LSTM仅基于历史价格预测长期趋势,比特币价格受政策、舆情等外部因素影响极大,建议结合交易量、恐慌指数等特征提升效果
  • 时间步校准:根据你实际使用的数据集粒度(日/周/月)精准调整future_steps数值

内容的提问来源于stack exchange,提问作者Saad Sajjad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 13:00:50