V2EX = way to explore
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
V2EX  ›  Python

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

  •  
  •   LittleUqeer · 2017-01-19 17:43:46 +08:00 · 6083 次点击
    这是一个创建于 2625 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    不知这哥们成功没。非要说学习“新闻联播”,不是不可以(语义分析?),但政策出台的具体时间根本无法预测。而政策的出现,已经等价于一个结果,而不是预测因素。
    txlty
        5
    txlty  
       2017-01-19 19:59:58 +08:00
    server
        6
    server  
       2017-01-19 20:05:12 +08:00
    这兄弟 又来安利了
    sshpandas
        7
    sshpandas  
       2017-01-19 20:18:48 +08:00
    人工神经网络不是万金油。
    01186
        8
    01186  
       2017-01-20 18:14:16 +08:00
    学习新闻联播...笑了...
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1550 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 23:59 · PVG 07:59 · LAX 16:59 · JFK 19:59
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.