test_kzz.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. # coding:utf-8
  2. import pandas as pd
  3. import numpy as np
  4. from sklearn.preprocessing import MinMaxScaler
  5. from keras.models import Sequential
  6. from keras.layers import Dense, LSTM
  7. from keras.callbacks import EarlyStopping
  8. import matplotlib.pyplot as plt
  9. from sqlalchemy import create_engine
  10. # 加载数据
  11. engine_tech = create_engine('mysql+pymysql://root:r6kEwqWU9!v3@localhost:3307/qmt_stocks_tech?charset=utf8')
  12. df = pd.read_sql_table('600000.SH_1d', con=engine_tech)
  13. print(df)
  14. # 计算MACD指标
  15. ema12 = df['close_back'].ewm(span=12, adjust=False).mean()
  16. ema26 = df['close_back'].ewm(span=26, adjust=False).mean()
  17. macd = ema12 - ema26
  18. signal = macd.ewm(span=9, adjust=False).mean()
  19. df['macd'] = macd
  20. df['signal'] = signal
  21. # 准备数据
  22. data = df[['close_back', 'macd', 'signal', 'willr', 'volume_back', 'dif', 'dea', 'rsi_6', 'rsi_12', 'rsi_24']].values
  23. print(data)
  24. data = data[~np.isnan(data).any(axis=1), :]
  25. print('处理后', data)
  26. scaler = MinMaxScaler(feature_range=(0, 1))
  27. data = scaler.fit_transform(data)
  28. train_size = int(len(data) * 0.7)
  29. train_data = data[:train_size, :]
  30. test_data = data[train_size:, :]
  31. def create_dataset(dataset, look_back):
  32. X, Y = [], []
  33. for i in range(len(dataset) - look_back - 1):
  34. X.append(dataset[i:(i + look_back), :])
  35. Y.append(dataset[i + look_back, 0])
  36. return np.array(X), np.array(Y)
  37. look_back = 90
  38. train_X, train_Y = create_dataset(train_data, look_back)
  39. test_X, test_Y = create_dataset(test_data, look_back)
  40. # LSTM模型
  41. model = Sequential()
  42. model.add(LSTM(units=50, input_shape=(train_X.shape[1], train_X.shape[2])))
  43. model.add(Dense(units=1))
  44. model.compile(optimizer='adam', loss='mean_squared_error')
  45. # 训练模型
  46. early_stop = EarlyStopping(monitor='val_loss', patience=10)
  47. history = model.fit(train_X, train_Y, epochs=100, batch_size=1, validation_data=(test_X, test_Y), callbacks=[early_stop], verbose=2)
  48. # 绘制损失函数
  49. plt.plot(history.history['loss'], label='train')
  50. plt.plot(history.history['val_loss'], label='test')
  51. plt.legend()
  52. plt.show()
  53. # 预测未来30天的涨跌
  54. last_data = data[-look_back:, :]
  55. last_data = np.expand_dims(last_data, axis=0)
  56. predictions = []
  57. for i in range(30):
  58. prediction = model.predict(last_data)
  59. predictions.append(prediction)
  60. last_data = np.concatenate([last_data[:, 1:, :], prediction.reshape(1, 1, 3)], axis=1)
  61. predictions = scaler.inverse_transform(np.array(predictions).reshape(-1, 1))
  62. # 绘制预测结果
  63. plt.plot(predictions, label='predicted')
  64. plt.plot(df['back_close'].tail(30).reset_index(drop=True), label='actual')
  65. plt.legend()
  66. plt.show()