如何使用神经网络预测资产价格以获得一致的结果



我正试图建立一个神经网络,使用4个输入因子(石油价格、美元价值、通货膨胀和衡量经济不确定性的指数(来预测金融资产的价格

为了评估模型,我想将我的预测的平均绝对误差与测试数据的实际值进行比较。

但每当我重新运行代码时,我都会得到一个不同的平均绝对误差结果(不改变模型,只是重新调整完全相同的代码(。

我不知道为什么会这样。

这是我的代码:

首先我加载数据

data = pd.read_excel("data/Data_final.xlsx", index_col= "Date", parse_dates = True).dropna()
data = data["2020":"1985"].sort_values("Date", ascending = True)

然后我把数据分成输入变量和输出变量(黄金价格(,并把数据分成训练集和测试集——每次时,我都使用shuffle=False来获得相同的训练和测试数据集

x = data[["WTI_Crude_Oil", "US_CPI_all_Urban", "USDX", "Uncertainty_Index"]]
y = data.iloc[:,0]
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size =0.20, shuffle = False)

之后,我将数据标准化

mean_x = x_train.mean(axis = 0)
x_train = x_train - mean_x
std_x = x_train.std(axis = 0)
x_train = x_train / std_x
# normalize test data as well using mean and std of train data to avoid look ahead bias 
x_test = x_test - mean_x
x_test = x_test / std_x

然后我正在建立我的模型

from keras import models
from keras import layers
model = models.Sequential()
model.add(layers.Dense(64, activation = "relu", input_shape = (x_train.shape[1],)))
model.add(layers.Dense(16, activation = "relu"))
model.add(layers.Dense(1))
model.compile(optimizer = "rmsprop", loss = "mse", metrics = ["mae"])

然后我拟合并评估模型

model.fit(x_train, y_train, epochs = 600)
test_mse_score, test_mae_score = model.evaluate(x_test, y_test)

我的目标是减少平均绝对误差,但每次运行代码时,我都会得到不同的平均绝对误差。我的代码中的错误在哪里?更好地理解的数据片段

试试这个:

from pandas_datareader import data as wb
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pylab import rcParams
from sklearn.preprocessing import MinMaxScaler

start = '2019-06-30'
end = '2020-06-30'
tickers = ['SBUX']
thelen = len(tickers)
price_data = []
for ticker in tickers:
prices = wb.DataReader(ticker, start = start, end = end, data_source='yahoo')[['Open','Adj Close']]
price_data.append(prices.assign(ticker=ticker)[['ticker', 'Open', 'Adj Close']])
#names = np.reshape(price_data, (len(price_data), 1))
df = pd.concat(price_data)
df.reset_index(inplace=True)
for col in df.columns: 
print(col) 

#used for setting the output figure size
rcParams['figure.figsize'] = 20,10
#to normalize the given input data
scaler = MinMaxScaler(feature_range=(0, 1))
#to read input data set (place the file name inside  ' ') as shown below
df.head()
df['Date'] = pd.to_datetime(df.Date,format='%Y-%m-%d')
# df.index = names['Date']
#3plt.figure(figsize=(16,8))
# plt.plot(df['Adj Close'], label='Closing Price')

ntrain = 80
df_train = df.head(int(len(df)*(ntrain/100)))
ntest = -80
df_test = df.tail(int(len(df)*(ntest/100)))

#importing the packages 
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, Dropout, LSTM
#dataframe creation
seriesdata = df.sort_index(ascending=True, axis=0)
new_seriesdata = pd.DataFrame(index=range(0,len(df)),columns=['Date','Adj Close'])
length_of_data=len(seriesdata)
for i in range(0,length_of_data):
new_seriesdata['Date'][i] = seriesdata['Date'][i]
new_seriesdata['Adj Close'][i] = seriesdata['Adj Close'][i]
#setting the index again
new_seriesdata.index = new_seriesdata.Date
new_seriesdata.drop('Date', axis=1, inplace=True)
#creating train and test sets this comprises the entire data’s present in the dataset
myseriesdataset = new_seriesdata.values
totrain = myseriesdataset[0:255,:]
tovalid = myseriesdataset[255:,:]
#converting dataset into x_train and y_train
scalerdata = MinMaxScaler(feature_range=(0, 1))
scale_data = scalerdata.fit_transform(myseriesdataset)
x_totrain, y_totrain = [], []
length_of_totrain=len(totrain)
for i in range(60,length_of_totrain):
x_totrain.append(scale_data[i-60:i,0])
y_totrain.append(scale_data[i,0])
x_totrain, y_totrain = np.array(x_totrain), np.array(y_totrain)
x_totrain = np.reshape(x_totrain, (x_totrain.shape[0],x_totrain.shape[1],1))

#LSTM neural network
lstm_model = Sequential()
lstm_model.add(LSTM(units=50, return_sequences=True, input_shape=(x_totrain.shape[1],1)))
lstm_model.add(LSTM(units=50))
lstm_model.add(Dense(1))
lstm_model.compile(loss='mean_squared_error', optimizer='adadelta')
lstm_model.fit(x_totrain, y_totrain, epochs=10, batch_size=1, verbose=2)
#predicting next data stock price
myinputs = new_seriesdata[len(new_seriesdata) - (len(tovalid)+1) - 60:].values
myinputs = myinputs.reshape(-1,1)
myinputs  = scalerdata.transform(myinputs)
tostore_test_result = []
for i in range(60,myinputs.shape[0]):
tostore_test_result.append(myinputs[i-60:i,0])
tostore_test_result = np.array(tostore_test_result)
tostore_test_result = np.reshape(tostore_test_result,(tostore_test_result.shape[0],tostore_test_result.shape[1],1))
myclosing_priceresult = lstm_model.predict(tostore_test_result)
myclosing_priceresult = scalerdata.inverse_transform(myclosing_priceresult)

totrain = df_train
tovalid = df_test
#predicting next data stock price
myinputs = new_seriesdata[len(new_seriesdata) - (len(tovalid)+1) - 60:].values
#  Printing the next day’s predicted stock price. 
print(len(tostore_test_result));
print(myclosing_priceresult);

结果:

Date
ticker
Open
Adj Close
Epoch 1/10
193/193 - 3s - loss: 0.2868
Epoch 2/10
193/193 - 3s - loss: 0.2671
Epoch 3/10
193/193 - 3s - loss: 0.2465
Epoch 4/10
193/193 - 3s - loss: 0.2253
Epoch 5/10
193/193 - 3s - loss: 0.2040
Epoch 6/10
193/193 - 3s - loss: 0.1827
Epoch 7/10
193/193 - 3s - loss: 0.1617
Epoch 8/10
193/193 - 3s - loss: 0.1413
Epoch 9/10
193/193 - 3s - loss: 0.1217
Epoch 10/10
193/193 - 3s - loss: 0.1033
1
[[67.15351]]

最新更新