참조한 동영상
질문할 글은 파란색으로 되있음
#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('005930.KS', data_source='yahoo', start='2012-01-01', end='2020-01-01')
#Show teh data
print("df: \n",df)
#Get the number of rows and columns in the data set
print("df.shape:\n",df.shape)
#Visualize the closing price history
plt.figure(figsize=(16,8))
plt.title('Close Price History')
plt.plot(df['Close'])
plt.xlabel('Date', fontsize=18)
plt.ylabel('Close Price USD ($)', fontsize=18)
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) * .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 = []
for i in range(60, len(train_data)):
x_train.append(train_data[i-60:i, 0])
y_train.append(train_data[i, 0])
#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 1543 to 2002
test_data = scaled_data[training_data_len - 60: , :]
#Create the data sets 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 models predicted price values
predictions = model.predict(x_test)
predictions = scaler.inverse_transform(predictions)
#Get the root mean squared 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', 'Val', 'Predictions'], loc='lower right')
plt.show()
#Show the valid and predicted prices
valid
targetStock = web.DataReader('005930.KS', data_source='yahoo', start='2012-01-01', end='2020-01-01')
#Create a new dataframe
new_df = targetStock.filter(['Close'])
#Get teh last 60 day closing price values and convert the dataframe to an array
last_60_days = new_df[-60:].values
#Scale the data to be values between 0 and 1
last_60_days_scaled = scaler.transform(last_60_days)
#Create an empty list
X_test = []
#Append teh past 60 days
X_test.append(last_60_days_scaled)
#Convert the X_test data set 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 predicted scaled price
pred_price = model.predict(X_test)
#undo the scaling
pred_price = scaler.inverse_transform(pred_price)
print("내일가격: ",pred_price)
# 400일치 가격을 알고싶으면
# 내일가격을 append 해서 또한번 계산 하기를 400번 하면 된다. 라고 생각했음
for i in range(0,400):
last_60_days=np.delete(last_60_days,0)
last_60_days=np.append(last_60_days,pred_price)
last_60_days=np.reshape(last_60_days,(60,1))
#print("shape ",i+1," of last60: ",last_60_days.shape)
#print(i+1," of last60: ",last_60_days)
last_60_days_scaled = scaler.transform(last_60_days)
#Create an empty list
X_test = []
#Append teh past 60 days
X_test.append(last_60_days_scaled)
#Convert the X_test data set to a numpy array
X_test = np.array(X_test)
# print("X_test shape: ",X_test.shape)
# print("X_test: ",X_test)
#Reshape the data
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
# print("X_test.shape[0]: ",X_test.shape[0])
# print(" X_test.shape[1]: ", X_test.shape[1])
#Get the predicted scaled price
pred_price = model.predict(X_test)
#undo the scaling
pred_price = scaler.inverse_transform(pred_price)
print("내일가격", i+2, ":"," ",pred_price)
이렇게 짰더니 주가가 그냥 0원을 향해서 수직 하락함
왜 이런거임?
회사가 망할 거라는 걸 예측해버렸음
한 300년 후를 예측해버리내 - dc App
자세히 알려주세요 형님
이런 것 시행착오 엄청 오래 했었는데.. 안가르쳐줌 ㅇㅅㅇ 암튼 통계나 분류가 중요.
알려주세요 형님
열심히 하는중에 소금 뿌리는거 같아서 미안한데 저런건 잘 만들어봐야 이평선이랑 별 차이 없어
대충이런건 그게 문제 아니냐 범위값초과 - dc App
망해서 주가 0원 찍을거란거잖아
예측값으로 예측을 하면 안되지. 그게 문제. 근데 아무리봐도 0을 향해 가는게 아니라 기울기가 0이 되는건데. 저게 이평선이나 다름없다는 강력한 근거. 자기추종을 하니까 평균이 계속 비슷비슷하게 수렴하는거.
형님 답을 주셔서 ㄳ 합니다
ㄴ 오히려 내가 고마움. 저런거 예측이 정상성(재현률)이 낮은건 알았는데 구체적으로 증거라고 할까 그런게 대강 감으로 잡는거였거든. 근데 저거 결과를 보니 확 와닿음. 이평선을 학습하는거라는 증거가 저거라는거. 참고로 sin(x)를 대상으로 해보면 정상성이 있어서 자기참조를 해도 제대로 진동함. 다만 sin(x)도 몇번씩 새로 학습해보면 종종 발산하거나 수렴하는 수가 있음.
저거 결과도 내가 기울기가 0이 된다고는 썼지만 그건 그냥 수렴이고 여러번 해보면 발산도 나올거임. 아마도... 그냥 완전 상방 완전 하방 잡히면 발산이지 뭐.