Python 机器学习 - 拟合具有非平稳特征的神经网络对股票进行预测 - V2EX
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
LittleUqeer

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

  •  
  •   LittleUqeer Jan 19, 2017 7143 views
    This topic created in 3404 days ago, the information mentioned may be changed or developed.

    今天想和大家分享一下如何利用 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

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

    不知这哥们成功没。非要说学习“新闻联播”,不是不可以(语义分析?),但政策出台的具体时根本无法预测。而政策的出现,已经等价于一个结果,而不是预测因素。
    txlty
        5
    txlty  
       Jan 19, 2017
    server
        6
    server  
       Jan 19, 2017
    这兄弟 又来安利了
    sshpandas
        7
    sshpandas  
       Jan 19, 2017
    人工神经网络不是万金油。
    01186
        8
    01186  
       Jan 20, 2017
    学习新闻联播...笑了...
    About     Help     Advertise     Blog     API     FAQ     Solana     1014 Online   Highest 6679       Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 45ms UTC 23:07 PVG 07:07 LAX 16:07 JFK 19:07
    Do have faith in what you're doing.
    ubao msn snddm index pchome yahoo rakuten mypaper meadowduck bidyahoo youbao zxmzxm asda bnvcg cvbfg dfscv mmhjk xxddc yybgb zznbn ccubao uaitu acv GXCV ET GDG YH FG BCVB FJFH CBRE CBC GDG ET54 WRWR RWER WREW WRWER RWER SDG EW SF DSFSF fbbs ubao fhd dfg ewr dg df ewwr ewwr et ruyut utut dfg fgd gdfgt etg dfgt dfgd ert4 gd fgg wr 235 wer3 we vsdf sdf gdf ert xcv sdf rwer hfd dfg cvb rwf afb dfh jgh bmn lgh rty gfds cxv xcv xcs vdas fdf fgd cv sdf tert sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf shasha9178 shasha9178 shasha9178 shasha9178 shasha9178 liflif2 liflif2 liflif2 liflif2 liflif2 liblib3 liblib3 liblib3 liblib3 liblib3 zhazha444 zhazha444 zhazha444 zhazha444 zhazha444 dende5 dende denden denden2 denden21 fenfen9 fenf619 fen619 fenfe9 fe619 sdf sdf sdf sdf sdf zhazh90 zhazh0 zhaa50 zha90 zh590 zho zhoz zhozh zhozho zhozho2 lislis lls95 lili95 lils5 liss9 sdf0ty987 sdft876 sdft9876 sdf09876 sd0t9876 sdf0ty98 sdf0976 sdf0ty986 sdf0ty96 sdf0t76 sdf0876 df0ty98 sf0t876 sd0ty76 sdy76 sdf76 sdf0t76 sdf0ty9 sdf0ty98 sdf0ty987 sdf0ty98 sdf6676 sdf876 sd876 sd876 sdf6 sdf6 sdf9876 sdf0t sdf06 sdf0ty9776 sdf0ty9776 sdf0ty76 sdf8876 sdf0t sd6 sdf06 s688876 sd688 sdf86