基于LSTM的价格预测模型
导语
本文介绍了LSTM的相关内容和在股票价格预测,希冀加密货币中心化交易所的量化交易能够借鉴。
LSTM的股票价格预测
LSTM(Long Short Term Memory)是一种 特殊的RNN类型,同其他的RNNs相比可以更加方便地学习长期依赖关系,因此有很多人试图将其应用于 时间序列的预测问题 上。
汇丰银行全球资产管理开发副总裁Jakob Aungiers在他的个人网站上比较详细地介绍了LSTM在Time Series Prediction上的运用(http://www.jakob-aungiers.com/articles/a/LSTM-Neural-Network-for-Time-Series-Prediction) ,本文以这篇文章的代码为基础,以Bigquant为平台,介绍一下”LSTM-for-Time-Series-Prediction“的流程。
Keras是实现LSTM最方便的python库(Bigquant平台已经装好了,不用自己安装了)
from keras.layers.core import Dense, Activation, Dropout
from keras.layers.recurrent import LSTM
from keras.models import Sequential
from keras import optimizers加载转换数据
例如希望根据前seq_len天的收盘价预测第二天的收盘价,那么可以将data转换为(len(data)-seq_len)(seq_len+1)的数组,由于LSTM神经网络接受的input为3维数组,因此最后可将input+output转化为(len(data)-seq_len)(seq_len+1)*1的数组
def load_data(instrument,start_date,end_date,field,seq_len,prediction_len,train_proportion,normalise=True):
data=D.history_data(instrument,start_date,end_date,fields)
……
seq_len=seq_len+1
result=[]
for index in range(len(data)-seq_len):
result.append(data[index:index+seq_len])
……
# 规范化之后
x_train = train[:, :-1]
y_train = train[:, -1]
x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))
# 测试数据同样处理构建LSTM神经网络
model = Sequential()
model.add(LSTM(input_dim=layers[0],output_dim=layers[1],return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(layers[1],return_sequences=False))
model.add(Dropout(0.2))
model.add(Dense(input_dim=layers[1],output_dim=layers[2]))
model.add(Activation("linear"))
rms=optimizers.RMSprop(lr=conf.lr, rho=0.9, epsilon=1e-06)
model.compile(loss="mse", optimizer=rms)此神经网络共三层,第一层为LSTM层,输入数据维度是1,输出数据维度为seq_len;第二层也为LSTM层,输入和输出维度均为seq_len层;第三层为Dense层,输入数据维度是seq_len,输出数据维度为1,最终将input与output对应起来。
compile:编译用来配置模型的学习过程,可选参数有loss,optimizer等。模型在使用前必须编译,否则在调用fit或evaluate时会抛出异常。
loss为损失函数,可用mse,mae,binary_crossentropy
optimizers为优化器,即优化参数的算法,可供选择为SGD(随机梯度下降法),RMSprop(处理递归神经网络时的一个良好选择),Adagrad等(具体参见http://keras-cn.readthedocs.io/en/latest/ ,网页提供Keras相关函数的详细介绍)。
model.fit(X_train,y_train,batch_size=conf.batch,nb_epoch=conf.epochs,validation_split=conf.validation_split
fit为训练函数,batch_size:整数,训练时一个batch的样本会被计算一次梯度下降,使目标函数优化一步;nb_epoch:迭代次数;validation_split:0~1之间的浮点数,用来指定训练集的一定比例数据作为验证集
predicted = model.predict(data)
predicted = np.reshape(predicted, (predicted.size,))模型在test_data集上的预测,根据前seq_len长度预测下一时间的close。
另外,在此基础上,若希望预测prediction_len长度的close,则可在第一个predict_close的基础上,以此predict_close和前seq_len-1个true_close为input,预测下一个close,以此类推,可预测一定长度甚至全部长度的时间序列(predict_sequences_multiple,predict_sequence_full)
回测
(以predict_sequences_multiple为例)
思路是这样:看prediction_len长度内的涨跌,若prediction_len最后一天收盘价大于第一天的收盘价,则下买单;反之,不做单或者平仓
效果不是特别好,可能和我没有优化参数有很大关系,希望能抛砖引玉,完整策略代码如下,欢迎指正和讨论:slight_smile:
补充:如果运行出错,请检查M.trade模块是否是最新版本。附件:基于LSTM的股票价格预测模型实例
class conf:
instrument = '000300.HIX' #股票代码
#设置用于训练和回测的开始/结束日期
start_date = '2005-01-01'
end_date='2018-07-19'
field='close'
seq_len=100 #每个input的长度
prediction_len=20 #预测数据长度
train_proportion=0.8 #训练数据占总数据量的比值,其余为测试数据
normalise=True #数据标准化
epochs = 1 #LSTM神经网络迭代次数
batch=100 #整数,指定进行梯度下降时每个batch包含的样本数,训练时一个batch的样本会被计算一次梯度下降,使目标函数优化一步
validation_split=0.1 # 0~1之间的浮点数,用来指定训练集的一定比例数据作为验证集。
lr=0.001 #学习效率# 2. LSTM策略主体
import time
import numpy as np
import matplotlib.pyplot as plt
from numpy import newaxis
from tensorflow.keras.layers import Dense, Activation, Dropout, LSTM
# from tensorflow.keras.layers import
from tensorflow.keras.models import Sequential
from tensorflow.keras import optimizersdef load_data(instrument,start_date,end_date,field,seq_len,prediction_len,train_proportion,normalise=True):
# 加载数据,数据变化,提取数据模块
fields=[field,'amount']
data=D.history_data(instrument,start_date,end_date,fields)
data=data[data.amount>0]
datetime=list(data['date'])
data=list(data[field])
seq_len=seq_len+1
result=[]
for index in range(len(data)-seq_len):
result.append(data[index:index+seq_len])
if normalise:
norm_result=normalise_windows(result)
else:
norm_result=result
result=np.array(result)
norm_result=np.array(norm_result)
row=round(train_proportion*norm_result.shape[0])
data_test=result[int(row):,:]
datetime=datetime[int(row):] test_datetime=[]
for index in range(len(datetime)):
if index % prediction_len==0 and index+seq_len<len(datetime)-prediction_len:
test_datetime.append(datetime[index+seq_len])
train=norm_result[:int(row),:]
np.random.shuffle(train) #随机打乱训练样本
x_train = train[:, :-1]
y_train = train[:, -1]
x_test = norm_result[int(row):, :-1]
y_test = norm_result[int(row):, -1]
x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))
x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1)) return [x_train, y_train, x_test, y_test, data_test, test_datetime]
def normalise_windows(window_data):
#数据规范化
normalised_data = []
for window in window_data:
normalised_window = [((float(p) / float(window[0])) - 1) for p in window]
normalised_data.append(normalised_window)
return normalised_datadef denormalise_windows(normdata,data,seq_len):
#数据反规范化
denormalised_data = []
wholelen=0
for i, rowdata in enumerate(normdata):
denormalise=list()
if isinstance(rowdata,float)|isinstance(rowdata,np.float32):
denormalise = [(rowdata+1)*float(data[wholelen][0])]
denormalised_data.append(denormalise)
wholelen=wholelen+1
else:
for j in range(len(rowdata)):
denormalise.append((float(rowdata[j])+1)*float(data[wholelen][0]))
wholelen=wholelen+1
denormalised_data.append(denormalise)
return denormalised_datadef build_model(layers):
# LSTM神经网络层
# 详细介绍请参考http://keras-cn.readthedocs.io/en/latest/
model = Sequential() # model.add(LSTM(input_dim=layers[0],output_dim=layers[1],return_sequences=True))
model.add(LSTM(layers[1],input_shape=(layers[1],layers[0]),return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(layers[1],return_sequences=False))
model.add(Dropout(0.2))
model.add(Dense(1))
model.add(Activation("linear")) rms=optimizers.RMSprop(lr=conf.lr, rho=0.9, epsilon=1e-06)
model.compile(loss="mse", optimizer=rms)
start = time.time()
print("> Compilation Time : ", time.time() - start)
return modeldef predict_point_by_point(model, data):
#每次只预测1步长
predicted = model.predict(data)
predicted = np.reshape(predicted, (predicted.size,))
return predicteddef predict_sequence_full(model, data, seq_len):
#根据训练模型和第一段用来预测的时间序列长度逐步预测整个时间序列
curr_frame = data[0]
predicted = []
for i in range(len(data)):
predicted.append(model.predict(curr_frame[newaxis,:,:])[0,0])
curr_frame = curr_frame[1:]
curr_frame = np.insert(curr_frame, [seq_len-1], predicted[-1], axis=0)
return predicteddef predict_sequences_multiple(model, data, seq_len, prediction_len):
#根据训练模型和每段用来预测的时间序列长度逐步预测prediction_len长度的序列
prediction_seqs = []
for i in range(int(len(data)/prediction_len)):
curr_frame = data[i*prediction_len]
predicted = []
for j in range(prediction_len):
predicted.append(model.predict(curr_frame[newaxis,:,:])[0,0])
curr_frame = curr_frame[1:]
curr_frame = np.insert(curr_frame, [seq_len-1], predicted[-1], axis=0)
prediction_seqs.append(predicted)
return prediction_seqsdef plot_results(predicted_data, true_data):
#做图函数,用于predict_point_by_point和predict_sequence_full
fig = plt.figure(facecolor='white')
ax = fig.add_subplot(111)
ax.plot(true_data, label='True Data')
plt.plot(predicted_data)
plt.legend()
figure=plt.gcf()
figure.set_size_inches(20,10)
plt.show()def plot_results_multiple(predicted_data, true_data, prediction_len):
#做图函数,用于predict_sequences_multiple
fig = plt.figure(facecolor='white')
ax = fig.add_subplot(111)
ax.plot(true_data, label='True Data')
for i, data in enumerate(predicted_data):
padding = [None for p in range(i * prediction_len)]
plt.plot(padding + data)
plt.legend()
figure=plt.gcf()
figure.set_size_inches(20,10)
plt.show()#主程序
global_start_time = time.time() print('> Loading data... ')X_train,y_train,X_test,y_test,data_test,test_datetime=load_data(conf.instrument,conf.start_date,conf.end_date,conf.field,conf.seq_len,conf.prediction_len,conf.train_proportion,normalise=True)print('> Data Loaded. Compiling...')
print(X_train.shape)
model = build_model([1, conf.seq_len, 1])model.fit(
X_train,
y_train,
batch_size=conf.batch,
nb_epoch=conf.epochs,
validation_split=conf.validation_split)predictions = predict_sequences_multiple(model, X_test, conf.seq_len, conf.prediction_len)
# predictions = predict_sequence_full(model, X_test, conf.seq_len)
# predictions = predict_point_by_point(model, X_test)
if conf.normalise==True:
predictions=denormalise_windows(predictions,data_test,conf.seq_len)
y_test=denormalise_windows(y_test,data_test,conf.seq_len)print('Training duration (s) : ', time.time() - global_start_time)
plot_results_multiple(predictions, y_test, conf.prediction_len)
# plot_results(predictions, y_test)> Loading data...
> Data Loaded. Compiling...
(2553, 100, 1)
> Compilation Time : 9.5367431640625e-07
[2020-05-07 10:13:19.267942] WARNING tensorflow: The `nb_epoch` argument in `fit` has been renamed `epochs`.
Train on 2297 samples, validate on 256 samples
100/2297 [>.............................] - ETA: 2:21 - loss: 0.1309 200/2297 [=>............................] - ETA: 1:19 - loss: 0.0838 300/2297 [==>...........................] - ETA: 57s - loss: 0.0627 400/2297 [====>.........................] - ETA: 46s - loss: 0.0534 500/2297 [=====>........................] - ETA: 38s - loss: 0.0437 600/2297 [======>.......................] - ETA: 33s - loss: 0.0373 700/2297 [========>.....................] - ETA: 29s - loss: 0.0326 800/2297 [=========>....................] - ETA: 25s - loss: 0.0290 900/2297 [==========>...................] - ETA: 23s - loss: 0.02671000/2297 [============>.................] - ETA: 20s - loss: 0.02541100/2297 [=============>................] - ETA: 18s - loss: 0.02431200/2297 [==============>...............] - ETA: 16s - loss: 0.02361300/2297 [===============>..............] - ETA: 14s - loss: 0.02211400/2297 [=================>............] - ETA: 12s - loss: 0.02091500/2297 [==================>...........] - ETA: 11s - loss: 0.01981600/2297 [===================>..........] - ETA: 9s - loss: 0.0188 1700/2297 [=====================>........] - ETA: 8s - loss: 0.01791800/2297 [======================>.......] - ETA: 6s - loss: 0.01721900/2297 [=======================>......] - ETA: 5s - loss: 0.01652000/2297 [=========================>....] - ETA: 3s - loss: 0.01592100/2297 [==========================>...] - ETA: 2s - loss: 0.01532200/2297 [===========================>..] - ETA: 1s - loss: 0.01482297/2297 [==============================] - 32s 14ms/sample - loss: 0.0143 - val_loss: 0.0029
Training duration (s) : 97.36960220336914len(predictions)31# 1. 策略基本参数
# 3.回测
# 目前回测结构主要针对predict_sequences_multiple的预测结果,并且股票最好没有停牌
# 回测其他结果可自行修改handle_data
def initialize(context):
# 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))
# 传入预测数据和真实数据
context.predictions=predictions
context.true_data=y_test
context.date_time=test_datetime
# 设置持仓比
context.percent = 0.7
# 设置持仓天数
context.hold_days=conf.prediction_len
# 传入起止时间
context.start_date=context.date_time[0].strftime('%Y-%m-%d')
context.end_date=context.date_time[-1].strftime('%Y-%m-%d')
# 结束时间预计至少比开始时间多gap点才进场
context.gap=0
context.dt = 0# 回测引擎:每日数据处理函数,每天执行一次
def handle_data(context, data):
current_dt = data.current_dt.strftime('%Y-%m-%d')
can_do=pd.Timestamp(current_dt) in context.date_time
if can_do:
context.dt = current_dt
sid = context.symbol(conf.instrument)
cur_position = context.portfolio.positions[sid].amount # 持仓 row=context.date_time.index(pd.Timestamp(context.dt))
prediction=context.predictions[row]
# 满足开仓条件
if prediction[-1]-prediction[0]>=context.gap and cur_position == 0 and data.can_trade(sid):
context.order_target_percent(sid, 1)
elif prediction[-1]-prediction[0]<context.gap and cur_position > 0 and data.can_trade(sid):
context.order_target(sid, 0)# 调用回测引擎
m8 = M.trade.v4(
instruments=DataSource().write_pickle(conf.instrument),
start_date=test_datetime[0].strftime('%Y-%m-%d'),
end_date=test_datetime[len(test_datetime)-1].strftime('%Y-%m-%d'),
initialize=initialize,
handle_data=handle_data,
volume_limit=0.025,
order_price_field_buy='open', # 表示 开盘 时买入
order_price_field_sell='close', # 表示 收盘 前卖出
capital_base=1000000,
auto_cancel_non_tradable_orders=True,
data_frequency='daily',
price_type='真实价格',
product_type='股票',
plot_charts=True,
backtest_only=False,
benchmark='000300.SHA',
# 通过 options 参数传递预测数据和参数给回测引擎
options={'predictions': predictions}
)
本文由BigQuant宽客学院推出,版权归BigQuant所有。贴主:到哪都是韭菜于2024_12_17 19:17:21编辑贴主:到哪都是韭菜于2024_12_17 19:17:37编辑贴主:到哪都是韭菜于2024_12_17 19:24:18编辑贴主:到哪都是韭菜于2024_12_17 19:27:32编辑
贴主:到哪都是韭菜于2024_12_17 19:28:35编辑
内容来自网友分享,若违规或者侵犯您的权益,请联系我们
所有跟帖: ( 主贴楼主有权删除不文明回复,拉黑不受欢迎的用户 )
楼主前期社区热帖:
>>>>查看更多楼主社区动态...