# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load in import matplotlib.pyplot as plt
import statsmodels.tsa.seasonal as smt
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import random
import datetime as dt
from sklearn import linear_model
from sklearn.metrics import mean_absolute_error
import plotly # import the relevant Keras modules
from keras.models import Sequential
from keras.layers import Activation, Dense
from keras.layers import LSTM
from keras.layers import Dropout # Input data files are available in the "../input/" directory.
# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory from subprocess import check_output
import os
os.chdir('F:\\kaggleDataSet\\price-volume\\Stocks')
#read data
# kernels let us navigate through the zipfile as if it were a directory # trying to read a file of size zero will throw an error, so skip them
# filenames = [x for x in os.listdir() if x.endswith('.txt') and os.path.getsize(x) > 0]
# filenames = random.sample(filenames,1)
filenames = ['prk.us.txt', 'bgr.us.txt', 'jci.us.txt', 'aa.us.txt', 'fr.us.txt', 'star.us.txt', 'sons.us.txt', 'ipl_d.us.txt', 'sna.us.txt', 'utg.us.txt']
filenames = [filenames[1]]
print(filenames)
data = []
for filename in filenames:
df = pd.read_csv(filename, sep=',')
label, _, _ = filename.split(sep='.')
df['Label'] = filename
df['Date'] = pd.to_datetime(df['Date'])
data.append(df)

traces = []
for df in data:
clr = str(r()) + str(r()) + str(r())
df = df.sort_values('Date')
label = df['Label'].iloc[0]
trace = plotly.graph_objs.Scattergl(x=df['Date'],y=df['Close'])
traces.append(trace) layout = plotly.graph_objs.Layout(title='Plot',)
fig = plotly.graph_objs.Figure(data=traces, layout=layout)
plotly.offline.init_notebook_mode(connected=True)
plotly.offline.iplot(fig, filename='dataplot')

df = data[0]
window_len = 10 #Create a data point (i.e. a date) which splits the training and testing set
split_date = list(data[0]["Date"][-(2*window_len+1):])[0] #Split the training and test set
training_set, test_set = df[df['Date'] < split_date], df[df['Date'] >= split_date]
training_set = training_set.drop(['Date','Label', 'OpenInt'], 1)
test_set = test_set.drop(['Date','Label','OpenInt'], 1) #Create windows for training
LSTM_training_inputs = []
for i in range(len(training_set)-window_len):
temp_set = training_set[i:(i+window_len)].copy() for col in list(temp_set):
temp_set[col] = temp_set[col]/temp_set[col].iloc[0] - 1
LSTM_training_inputs.append(temp_set)
LSTM_training_outputs = (training_set['Close'][window_len:].values/training_set['Close'][:-window_len].values)-1 LSTM_training_inputs = [np.array(LSTM_training_input) for LSTM_training_input in LSTM_training_inputs]
LSTM_training_inputs = np.array(LSTM_training_inputs) #Create windows for testing
LSTM_test_inputs = []
for i in range(len(test_set)-window_len):
temp_set = test_set[i:(i+window_len)].copy() for col in list(temp_set):
temp_set[col] = temp_set[col]/temp_set[col].iloc[0] - 1
LSTM_test_inputs.append(temp_set)
LSTM_test_outputs = (test_set['Close'][window_len:].values/test_set['Close'][:-window_len].values)-1 LSTM_test_inputs = [np.array(LSTM_test_inputs) for LSTM_test_inputs in LSTM_test_inputs]
LSTM_test_inputs = np.array(LSTM_test_inputs)
def build_model(inputs, output_size, neurons, activ_func="linear",dropout=0.10, loss="mae", optimizer="adam"):
model = Sequential()
model.add(LSTM(neurons, input_shape=(inputs.shape[1], inputs.shape[2])))
model.add(Dropout(dropout))
model.add(Dense(units=output_size))
model.add(Activation(activ_func))
model.compile(loss=loss, optimizer=optimizer)
return model
# initialise model architecture
nn_model = build_model(LSTM_training_inputs, output_size=1, neurons = 32)
# model output is next price normalised to 10th previous closing price
# train model on data
# note: eth_history contains information on the training error per epoch
nn_history = nn_model.fit(LSTM_training_inputs, LSTM_training_outputs, epochs=5, batch_size=1, verbose=2, shuffle=True)

plt.plot(LSTM_test_outputs, label = "actual")
plt.plot(nn_model.predict(LSTM_test_inputs), label = "predicted")
plt.legend()
plt.show()
MAE = mean_absolute_error(LSTM_test_outputs, nn_model.predict(LSTM_test_inputs))
print('The Mean Absolute Error is: {}'.format(MAE))

#https://github.com/llSourcell/How-to-Predict-Stock-Prices-Easily-Demo/blob/master/lstm.py
def predict_sequence_full(model, data, window_size):
#Shift the window by 1 new prediction each time, re-run predictions on new window
curr_frame = data[0]
predicted = []
for i in range(len(data)):
predicted.append(model.predict(curr_frame[np.newaxis,:,:])[0,0])
curr_frame = curr_frame[1:]
curr_frame = np.insert(curr_frame, [window_size-1], predicted[-1], axis=0)
return predicted predictions = predict_sequence_full(nn_model, LSTM_test_inputs, 10) plt.plot(LSTM_test_outputs, label="actual")
plt.plot(predictions, label="predicted")
plt.legend()
plt.show()
MAE = mean_absolute_error(LSTM_test_outputs, predictions)
print('The Mean Absolute Error is: {}'.format(MAE))

结论
LSTM不能解决时间序列预测问题。对一个时间步长的预测并不比滞后模型好多少。如果我们增加预测的时间步长,性能下降的速度就不会像其他更传统的方法那么快。然而,在这种情况下,我们的误差增加了大约4.5倍。它随着我们试图预测的时间步长呈超线性增长。

吴裕雄--天生自然 PYTHON数据分析:所有美国股票和etf的历史日价格和成交量分析的更多相关文章

  1. 吴裕雄--天生自然 PYTHON数据分析:糖尿病视网膜病变数据分析(完整版)

    # This Python 3 environment comes with many helpful analytics libraries installed # It is defined by ...

  2. 吴裕雄--天生自然 python数据分析:健康指标聚集分析(健康分析)

    # This Python 3 environment comes with many helpful analytics libraries installed # It is defined by ...

  3. 吴裕雄--天生自然 python数据分析:葡萄酒分析

    # import pandas import pandas as pd # creating a DataFrame pd.DataFrame({'Yes': [50, 31], 'No': [101 ...

  4. 吴裕雄--天生自然 PYTHON数据分析:人类发展报告——HDI, GDI,健康,全球人口数据数据分析

    import pandas as pd # Data analysis import numpy as np #Data analysis import seaborn as sns # Data v ...

  5. 吴裕雄--天生自然 python数据分析:医疗费数据分析

    import numpy as np import pandas as pd import os import matplotlib.pyplot as pl import seaborn as sn ...

  6. 吴裕雄--天生自然 PYTHON数据分析:基于Keras的CNN分析太空深处寻找系外行星数据

    #We import libraries for linear algebra, graphs, and evaluation of results import numpy as np import ...

  7. 吴裕雄--天生自然 python数据分析:基于Keras使用CNN神经网络处理手写数据集

    import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mp ...

  8. 吴裕雄--天生自然 PYTHON数据分析:钦奈水资源管理分析

    df = pd.read_csv("F:\\kaggleDataSet\\chennai-water\\chennai_reservoir_levels.csv") df[&quo ...

  9. 吴裕雄--天生自然 PYTHON数据分析:医疗数据分析

    import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.rea ...

随机推荐

  1. Day of Week

    题目1043:Day of Week 时间限制:1 秒 内存限制:32 兆 特殊判题:否 提交:1544 解决:609 题目描述: We now use the Gregorian style of ...

  2. Ansi、Unicode、UTF8字符串之间的转换和写入文本文件

    转载请注明出处http://www.cppblog.com/greatws/archive/2008/08/31/60546.html 最近有人问我关于这个的问题,就此写一篇blog Ansi字符串我 ...

  3. 20194651—自动生成四则运算题第一版报告chris

    1.需求分析: (1)自动生成四则运算算式(+ - *  /),或两则运算(+  -). (2)剔除重复算式. (3)题目数量可定制. (4)相关参数可控制. (5)生成的运算题存储到外部文件中. 2 ...

  4. Flyway 的使用及Spring Boot集成Flyway

    一.简单介绍 Flyway 是一个开源.跨环境的数据库迁移工具,它强烈主张简单性和约定性而不是配置. Flyway 是一个便于多人开发对数据库管理的工具,将sql语句写入文件中,只需要在控制台输入指令 ...

  5. Go语言实现:【剑指offer】数组中出现次数超过一半的数字

    该题目来源于牛客网<剑指offer>专题. 数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字.例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}.由于数字2在数组 ...

  6. error C2662

    原因:关于const的问题 具体错误:函数的参数列表中参数签名为const,但是却调用了该参数的非const的成员函数 例子: 即使我们知道NoConst()并不会改变类的data成员,编译器依旧会报 ...

  7. 02-msyql-存储引擎

    1.优化器针对索引算法 1.1MySQL索引自优化-AHI(自适应HASH索引) MySQL的InnoDB引擎,能够创建只有Btree. AHI作用: 自动评估"热"的内存索引pa ...

  8. 《Head first设计模式》之观察者模式

    观察者模式定义了对象之间的一对多依赖,这样一来,当一个对象改变状态时,它的所有依赖者都会收到通知并自动更新. 客户有一个WeatherData对象,负责追踪温度.湿度和气压等数据.现在客户给我们提了个 ...

  9. 10-SpringMVC04

    FreeMarker 1.入门案例 1. 导包:freemarker.jar 2. 需要创建模板文件的路径:src/main/resources/template 3. 创建一个模板对象:hello. ...

  10. 02_TypeScript数据类型

    typescript中为了使编写的代码更规范,更有利于维护,增加了类型校验,写ts代码必须指定类型.   1.布尔类型(boolean) var flag:boolean = true;   2.数字 ...