利用 LSTM 神经网络预测股价走势

“我从小在法国长大,我会说一口流利的??”
在价稳量缩的盘整区间中突然出现一带量突破的大红K,表示股价可能要上涨了 在跳空缺口后出现岛状反转,表示股价可能要下跌了 在连涨几天的走势突然出现带有长上下影线的十字线,表示股价有反转的可能 

import pandas as pd
foxconndf= pd.read_csv('./foxconn_2013-2017.csv', index_col=0 )
foxconndf.dropna(how='any',inplace=True)
from sklearn import preprocessing
def normalize(df):
    newdf= df.copy()
    min_max_scaler = preprocessing.MinMaxScaler()
    
    newdf['open'] = min_max_scaler.fit_transform(df.open.values.reshape(-1,1))
    newdf['low'] = min_max_scaler.fit_transform(df.low.values.reshape(-1,1))
    newdf['high'] = min_max_scaler.fit_transform(df.high.values.reshape(-1,1))
    newdf['volume'] = min_max_scaler.fit_transform(df.volume.values.reshape(-1,1))
    newdf['close'] = min_max_scaler.fit_transform(df.close.values.reshape(-1,1))
    
    return newdf
foxconndf_norm= normalize(foxconndf)

import numpy as np
def data_helper(df, time_frame):
    
    # 数据维度: 开盘价、收盘价、最高价、最低价、成交量, 5维
    number_features = len(df.columns)
    # 将dataframe 转换为 numpy array
    datavalue = df.as_matrix()
    result = []
    # 若想要观察的 time_frame 為20天, 需要多加一天作为验证答案
    for index in range( len(datavalue) - (time_frame+1) ): # 从 datavalue 的第0个跑到倒数第 time_frame+1 个
        result.append(datavalue[index: index + (time_frame+1) ]) # 逐笔取出 time_frame+1 个K棒数值做為一笔 instance
    
    result = np.array(result)
    number_train = round(0.9 * result.shape[0]) # 取 result 的前90% instance 作为训练数据
    
    x_train = result[:int(number_train), :-1] # 训练数据中, 只取每一个 time_frame 中除了最后一笔的所有数据作为feature
    y_train = result[:int(number_train), -1][:,-1] # 训练数据中, 取每一个 time_frame 中最后一笔数据的最后一个数值(收盘价)作为答案
    
    # 测试数据
    x_test = result[int(number_train):, :-1]
    y_test = result[int(number_train):, -1][:,-1]
    
    # 将数据组成变好看一点
    x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], number_features))
    x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], number_features))  
    return [x_train, y_train, x_test, y_test]
# 以20天为一区间进行股价预测
X_train, y_train, X_test, y_test = data_helper(foxconndf_norm, 20)
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.layers.recurrent import LSTM
import keras
def build_model(input_length, input_dim):
    d = 0.3
    model = Sequential()
    model.add(LSTM(256, input_shape=(input_length, input_dim), return_sequences=True))
    model.add(Dropout(d))
    model.add(LSTM(256, input_shape=(input_length, input_dim), return_sequences=False))
    model.add(Dropout(d))
    model.add(Dense(16,kernel_initializer="uniform",activation='relu'))
    model.add(Dense(1,kernel_initializer="uniform",activation='linear'))
    model.compile(loss='mse',optimizer='adam', metrics=['accuracy'])
    return model
# 20天、5维
model = build_model( 20, 5 )
# 一个batch有128个instance,总共跑50个迭代
model.fit( X_train, y_train, batch_size=128, epochs=50, validation_split=0.1, verbose=1)

def denormalize(df, norm_value):
    original_value = df['close'].values.reshape(-1,1)
    norm_value = norm_value.reshape(-1,1)
    
    min_max_scaler = preprocessing.MinMaxScaler()
    min_max_scaler.fit_transform(original_value)
    denorm_value = min_max_scaler.inverse_transform(norm_value)
    
    return denorm_value
# 用训练好的 LSTM 模型对测试数据集进行预测
pred = model.predict(X_test)
# 将预测值与实际股价还原回原来的区间值
denorm_pred = denormalize(foxconndf, pred)
denorm_ytest = denormalize(foxconndf, y_test)
import matplotlib.pyplot as plt
%matplotlib inline  
plt.plot(denorm_pred,color='red', label='Prediction')
plt.plot(denorm_ytest,color='blue', label='Answer')
plt.legend(loc='best')
plt.show()

时间框架长度的调整 Keras 模型里全连结层的 activation 与 optimizaer 的调整 Keras 模型用不同的神经网路(种类、顺序、数量)来组合 batch_size的调整、epochs的调整 …


E N D

评论
