반응형
파이썬 & 머신러닝(LSTM)을 이용한 향후 주가 'x'일 예측
나는 언젠가 애플의 주가를 예측하기 위해 이 튜토리얼을 따랐다. 코드는 다음과 같습니다:
#Import the libraries
import math
import pandas_datareader as web
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, LSTM
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
#Get the stock quote
df = web.DataReader('AAPL', data_source='yahoo', start='2012-01-01', end='2020-12-07')
#Show the data
df
#Get the number of rows and columns in the data set
df.shape
#Visualize the closing price history
#We create a plot with name 'Close Price History'
plt.figure(figsize=(16,8))
plt.title('Close Price History')
#We give the plot the data (the closing price of our stock)
plt.plot(df['Close'])
#We label the axis
plt.xlabel('Date', fontsize=18)
plt.ylabel('Close Price USD ($)', fontsize=18)
#We show the plot
plt.show()
#Create a new dataframe with only the 'Close' column
data = df.filter(['Close'])
#Convert the dataframe to a numpy array
dataset = data.values
#Get the number of rows to train the model on
training_data_len = math.ceil( len(dataset) * 0.8 )
training_data_len
#Scale the data
scaler = MinMaxScaler(feature_range=(0,1))
scaled_data = scaler.fit_transform(dataset)
scaled_data
#Create the training data set
#Create the scaled training data set
train_data = scaled_data[0:training_data_len, :]
#Split the data into x_train and y_train data sets
x_train = []
y_train = []
#We create a loop
for i in range(60, len(train_data)):
x_train.append(train_data[i-60:i, 0]) #Will conaint 60 values (0-59)
y_train.append(train_data[i, 0]) #Will contain the 61th value (60)
if i <= 60:
print(x_train)
print(y_train)
print()
#Convert the x_train and y_train to numpy arrays
x_train, y_train = np.array(x_train), np.array(y_train)
#Reshape the data
x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))
x_train.shape
#Build the LSTM model
model = Sequential()
model.add(LSTM(50, return_sequences=True, input_shape=(x_train.shape[1], 1)))
model.add(LSTM(50, return_sequences=False))
model.add(Dense(25))
model.add(Dense(1))
#Compile the model
model.compile(optimizer='adam', loss='mean_squared_error')
#Train the model
model.fit(x_train, y_train, batch_size=1, epochs=1)
#Create the testing data set
#Create a new array containing scaled values from index 1738 to 2247
test_data = scaled_data[training_data_len - 60:]
#Create the data set x_test and y_test
x_test = []
y_test = dataset[training_data_len:, :]
for i in range(60, len(test_data)):
x_test.append(test_data[i-60:i, 0])
#Convert the data to a numpy array
x_test = np.array(x_test)
#Reshape the data
x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))
#Get the model's predicted price values for the x_test data set
predictions = model.predict(x_test)
predictions = scaler.inverse_transform(predictions)
predictions
#Evaluate model (get the root mean quared error (RMSE))
rmse = np.sqrt( np.mean( predictions - y_test )**2 )
rmse
#Plot the data
train = data[:training_data_len]
valid = data[training_data_len:]
valid['Predictions'] = predictions
#Visualize the data
plt.figure(figsize=(16,8))
plt.title('Model')
plt.xlabel('Date', fontsize=18)
plt.ylabel('Close Price USD ($)', fontsize=18)
plt.plot(train['Close'])
plt.plot(valid[['Close', 'Predictions']])
plt.legend(['Train', 'Validation', 'Predictions'], loc='lower right')
plt.show()
이제 그래프의 예측 부분을 확장하여 미래 날짜('x'일 후)도 표시하려고 합니다. 다음 날의 예상 가격을 받고 그 가격을 입력에 사용하여 다음 날을 얻고 그 날을 사용하여 다음 날을 얻음으로써 할 수 있을 것 같습니다. 어떻게 하면 좋을까요? 모델 교육에 사용된 데이터 세트에 익일 사전 가격을 추가할 생각이었지만 성공하지 못했습니다. 도와주셔서 고맙습니다.
당신의 직감이 맞아요. 나는 당신이 생각하고 있던 것을 다음과 같이 했습니다:
X_FUTURE = 100
predictions = np.array([])
last = x_test[-1]
for i in range(X_FUTURE):
curr_prediction = model.predict(np.array([last]))
print(curr_prediction)
last = np.concatenate([last[1:], curr_prediction])
predictions = np.concatenate([predictions, curr_prediction[0]])
predictions = scaler.inverse_transform([predictions])[0]
print(predictions)
나는 기본적으로 새로운 예측을 통해 시프팅 어레이를 구성했다
그 후에 나는 새로운 예측을 포함하는 데이터 프레임을 구성했다:
import datetime
from datetime import timedelta
dicts = []
curr_date = data.index[-1]
for i in range(X_FUTURE):
curr_date = curr_date + timedelta(days=1)
dicts.append({'Predictions':predictions[i], "Date": curr_date})
new_data = pd.DataFrame(dicts).set_index("Date")
그리고 나는 그 결과를 플롯했다:
#Plot the data
train = data
#Visualize the data
plt.figure(figsize=(16,8))
plt.title('Model')
plt.xlabel('Date', fontsize=18)
plt.ylabel('Close Price USD ($)', fontsize=18)
plt.plot(train['Close'])
plt.plot(new_data['Predictions'])
plt.legend(['Train', 'Predictions'], loc='lower right')
plt.show()
왜 그렇게 안 좋아 보이는가(어쨌든 우리는 미래를 모른다...?). 나는 시계열 예측에 그다지 전문가는 아니지만, 나는 그 모델이 시계열 아래에서 어떤 좋은 패턴도 배우지 못했다고 생각한다. 하지만 예를 들어 그것은 해야 할 일을 한다
당신은 제안된 것을 할 수 있지만, 니카이도가 보여준 결과가 별로 좋지 않을 것이라는 것을 보여주었듯이, 내가 한 테스트를 구성해 보면, 만약 마지막 날에 가격이 올랐다면, 그리고 마지막 날에 주가가 하락한다면, 그것은 계속해서 내려갈 것이다. 모형이 좋은 패턴을 학습하지 못했거나 모형이 마지막 날이 예측에 가장 중요한 날이라는 것을 학습했기 때문일 수 있습니다.
반응형
'개발하자' 카테고리의 다른 글
Conda env의 주피터 서버에서 러스트 커널에 연결할 수 없음 (0) | 2023.04.26 |
---|---|
ModuleNotFoundError: 'fastapi'라는 이름의 모듈이 없습니다 (0) | 2023.04.25 |
Terraform - 네트워크 피어링을 위한 Azure Kubernetes AKS vnet ID를 찾는 방법 (0) | 2023.04.24 |
Kubernetes : 패치를 사용하여 서비스 포트를 변경하는 방법 (0) | 2023.04.23 |
Write typescript type for given shape (0) | 2023.04.23 |