使用keras的LSTM進行預測----實戰練習

代碼

import numpy as np
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM

import marksix_1
import talib as ta


lt = marksix_1.Marksix()
lt.load_data(period=500)

# 指標序列
m = 2
series = lt.adapter(loc='0000001', zb_name='mod', args=(m, lt.get_mod_list(m)), tf_n=0)

# 實時線
close = np.cumsum(series).astype(float)

# 布林線
timeperiod = 5
upper, middle, lower = ta.BBANDS(close, timeperiod=timeperiod, nbdevup=2, nbdevdn=2, matype=0)

# 趨勢
qushi1 = np.where(close-middle < 0, 0, 1)# 實時線在均線上、下方
qushi2 = np.where(middle[1:] - middle[:-1] < 0, 0, 1) # 均線上、下行(長度少了1)

# 標籤轉化爲0,1
y = np.where(series==-1, 0, 1)

# 構造特徵(注意,已經歸一化,所有爲非負數)
f = upper-lower
f = f[timeperiod:] # 去掉了前面timeperiod個nan數據!!!
f = (f - f.min()) / (f.max() - f.min()) # 歸一化
y = y[timeperiod:]
qushi1 = qushi1[timeperiod:]
qushi2 = qushi2[timeperiod-1:]
features = np.column_stack([y, qushi1, qushi2, f]) # 特徵:[標籤、趨勢一、趨勢二、布林寬度]

# 
data_len = len(series)
time_steps = 3

# 將數據轉化爲[樣本數, 時間步數, 特徵數]的形式
X = [features[i:i+time_steps] for i in range(data_len-time_steps-timeperiod)] # [samples, time steps * features]
X = np.reshape(X, (data_len - time_steps-timeperiod, time_steps, -1)) # [samples, time steps, features]

# 標籤長度一致
y = y[time_steps:]

# one-hot編碼
y = np.eye(2)[y]

# 劃分訓練數據、測試數據
train_X, test_X = X[:-20], X[-20:]
train_y, test_y = y[:-20], y[-20:]

# =================================
model = Sequential()
model.add(LSTM(64, input_shape=(X.shape[1], X.shape[2])))
model.add(Dense(y.shape[1], activation='softmax')) # 輸出各種的機率(softmax)
model.compile(loss='categorical_crossentropy',     # 單標籤,多分類(categorical_crossentropy)
              optimizer='adam', 
              metrics=['accuracy'])

model.fit(train_X, train_y, epochs=500, batch_size=1, verbose=2)

#檢查模型在測試集上的表現是否良好
test_loss, test_acc = model.evaluate(test_X, test_y)
print('test_acc:', test_acc)

 

效果圖

 

 

結論

只測試了mod 2的狀況,效果很差.測試

訓練數據精度能夠達到三分之二左右,測試數據的精度只有四分之一。頭腦風暴,幾乎能夠反其道而行之!可能不失爲可行之策。編碼

 

下一步:lua

1.畫出後20個數據k線圖,看是不是震盪區間,亦或是趨勢區間spa

2.換別的指標看看3d

相關文章
相關標籤/搜索