Python 机器学习 - 拟合具有非平稳特征的神经网络对股票进行预测

2017-01-19 17:43:46 +08:00
 LittleUqeer

今天想和大家分享一下如何利用 Python 拟合具有非平稳特征的神经网络,从而对股票进行预测。

建筑行业市值前六公司

中国建筑 - 601668.SH 中国交建 - 601800.SH 中国中铁 - 601390.SH 中国铁建 - 601186.SH 中国中冶 - 601618.SH 中国电建 - 601669.SH

建模计算分析

import math
import numpy as np
import pandas as pd
import seaborn as sns
sns.set_style('whitegrid') 
import sklearn.neural_network
from datetime import datetime
import matplotlib.pyplot as plt
from sklearn import preprocessing
from pandas import Series,DataFrame
from statsmodels.tsa.stattools import adfuller
from scipy.stats import norm, t, skew, kurtosis, kurtosistest, beta

对中国电建 - 601669.SH 进行预测

# 前复权数据
data = pd.read_csv('建筑.csv',index_col=0)
data.head(3).append(data.tail(3))

China_DJ = data['601669']
new_index = pd.to_datetime(China_DJ.index)
Y= Series(China_DJ.values,new_index)
Y.head(6)

#收益率
Y_pct = Y.pct_change()
Y_pct= Y_pct[1:].copy()
Y_pct.head()

#转换到 0 、 1
f = lambda x: 1 if x > 0 else -1
Y_pct = Y_pct.apply(f)
Y_pct.head()

Y_pct = Y_pct.shift(-1,freq='1d')
Y_pct.head()

#用 X 表示每日价格,来预测未来 601669 的收益
new_index1 = pd.to_datetime(data.index)
X = DataFrame(data.values,new_index1)
X.tail()

X = X[:-2]
X.index

Y.index

NN = sklearn.neural_network.MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(10, 5))

NN = NN.fit(X, Y)
NN

MLPClassifier(activation='relu', alpha=1e-05, batch_size='auto', beta_1=0.9, beta_2=0.999, early_stopping=False, epsilon=1e-08, hidden_layer_sizes=(10, 5), learning_rate='constant', learning_rate_init=0.001, max_iter=200, momentum=0.9, nesterovs_momentum=True, power_t=0.5, random_state=None, shuffle=True, solver='lbfgs', tol=0.0001, validation_fraction=0.1, verbose=False, warm_start=False)

NN.predict(X)

array([ 1, -1, -1, 1, 1, 1, 1, 1, -1, 1, 1, -1, -1, -1, -1, -1, 1, -1, -1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 1, 1, 1, -1, -1, -1, -1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1], dtype=int64)

def check_accuracy(predictions, Y):
    correct = len(Y4[predictions == Y])
    return correct / float(len(Y))

predictions = NN.predict(X)
check_accuracy(predictions, Y)

0.61

imputer = preprocessing.Imputer()
scaler = preprocessing.MinMaxScaler()

X = imputer.fit_transform(X)
X = scaler.fit_transform(X)

NN = NN.fit(X, Y)
NN

MLPClassifier(activation='relu', alpha=1e-05, batch_size='auto', beta_1=0.9, beta_2=0.999, early_stopping=False, epsilon=1e-08, hidden_layer_sizes=(10, 5), learning_rate='constant', learning_rate_init=0.001, max_iter=200, momentum=0.9, nesterovs_momentum=True, power_t=0.5, random_state=None, shuffle=True, solver='lbfgs', tol=0.0001, validation_fraction=0.1, verbose=False, warm_start=False)

NN.predict(X)

array([-1, -1, -1, 1, -1, 1, -1, 1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, 1, -1, 1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, 1, -1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 1, -1, -1], dtype=int64)

predictions = NN.predict(X)
check_accuracy(predictions, Y4)

0.71

可以预测第二天的方向超过 71%的时间

# 前复权数据
OOS_pricing_data = pd.read_csv('建筑 2.csv',index_col=0)
OOS_pricing_data.head(3).append(OOS_pricing_data.tail(3))

Y1 = OOS_pricing_data['601669']
new_index = pd.to_datetime(Y1.index)
Y5 = Series(Y1.values,new_index)
Y5 = Y5.pct_change()
Y5 = Y5[1:]
Y5.head()

#转换到 0 、 1
f = lambda x: 1 if x > 0 else -1
Y5 = Y5.apply(f)
Y5.head()

Y5 = Y5.shift(-1,freq='1d')
Y5.head()

new_index2 = pd.to_datetime(OOS_pricing_data.index)
X11 = DataFrame(OOS_pricing_data.values,new_index2)
X11.head()

X11 = X11[:-1]
X11.index

Y5.index

X11 = imputer.fit_transform(X11)
X11 = scaler.fit_transform(X11)
OOS_predictions = NN.predict(X11)

check_accuracy(OOS_predictions, OOS_Y)

result: 0.5034013605442177

50%

只有 50%的准确率

可能是在不同时期之间的不稳定造成的,这导致学习神经网络,很适合现在的条件训练数据,但不适合在不同条件下测试数据。也有可能是神经网络是适合噪声而没有体现出真正的信号,很难讲。

new_index3 = pd.to_datetime(data.index)
Y6 = pd.DataFrame(data.values,new_index3)
Y6.columns = ['601668','601800','601390','601186','601618','601669']
Y6.head()

corr_df = pd.rolling_corr(Y6 , window=30)
corr_df

看看平稳性

fig = plt.figure(figsize=(16,8.5))
plt.plot(corr_df[:,'601668','601669'])
plt.plot(corr_df[:,'601800','601669'])
plt.plot(corr_df[:,'601390','601669'])
plt.plot(corr_df[:,'601186','601669'])
plt.plot(corr_df[:,'601618','601669'])
ts = corr_df[:, '601618','601669']
plt.hlines(ts.mean(), ts.index[30-1], ts.index[-1], linestyles='dashed')
plt.ylabel('Pearson Correlation Coefficient')
plt.legend(['601668 x 601669', '601800 x 601669', '601390 x 601669', '601186 x 601669', '601618 x 601669','601618 x 601669 AVG'])

adfuller(data['601668'])

adfuller(data['601800'])

adfuller(data['601390'])

adfuller(data['601186'])

adfuller(data['601618'])

adfuller(data['601669'])

源地址: https://uqer.io/community/share/587db6aa23a7d6004da3665b

6120 次点击
所在节点    Python
8 条回复
lbp0200
2017-01-19 17:50:53 +08:00
收藏先
menc
2017-01-19 19:01:17 +08:00
笑尿。
“只有 50%的准确率”
这意味着这个神经网络和抛硬币没有太大的区别
txlty
2017-01-19 19:15:18 +08:00
A 股受政策影响很大,要么千股齐涨,要么千股起跌。所以这个场景,人工智能并不适合预测。更多人选择做美股的量化交易。
不过,我觉得机器学习在 A 股自有 A 股的利用方法。等我做完了发现无效的话,再把代码发出来。
txlty
2017-01-19 19:55:44 +08:00
我见过最奇葩的言论是这个 http://tieba.baidu.com/p/3859044063

不知这哥们成功没。非要说学习“新闻联播”,不是不可以(语义分析?),但政策出台的具体时间根本无法预测。而政策的出现,已经等价于一个结果,而不是预测因素。
txlty
2017-01-19 19:59:58 +08:00
server
2017-01-19 20:05:12 +08:00
这兄弟 又来安利了
sshpandas
2017-01-19 20:18:48 +08:00
人工神经网络不是万金油。
01186
2017-01-20 18:14:16 +08:00
学习新闻联播...笑了...

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/335670

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX