2025년, 코딩은 선택이 아닌 필수!

2025년 모든 학교에서 코딩이 시작 됩니다. 먼저 준비하는 사람만이 기술을 선도해 갑니다~

머신러닝/7. 머신러닝 활용하기

5.삼성전자 주식 인공지능으로 예측하기

파아란기쁨1 2022. 6. 16. 09:57
반응형

소스코드 - https://colab.research.google.com/drive/1K26iPPSXiPn5cfYV8JC4MhxeZLRX-yZR?usp=sharing 

 

삼성전자주식예측.ipynb

Colaboratory notebook

colab.research.google.com

 

 

실제 데이터 수집 : https://finance.yahoo.com 

 

Yahoo Finance - Stock Market Live, Quotes, Business & Finance News

At Yahoo Finance, you get free stock quotes, up-to-date news, portfolio management resources, international market data, social interaction and mortgage rates that help you manage your financial life.

finance.yahoo.com

samsung 를 검색하면 다음과 같이 데이터 조회가 된다.

Historical Data 를 클릭한 후 Downlad Data 클릭하여 파일 다운로드 (기간은 5년으로 설정하자)

 

다음으로 실습을 진행 해 보자.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import LSTM, Dropout, Dense, Activation
# from keras.callbacks import TensorBoard, ModelCheckpoint, ReduceLROnPlateau
import datetime


data = pd.read_csv('samsung.csv')
data.head()

데이터를 로드해서 데이터 형태를 조회 해 보면 우리가 다운받은 내용이 조회 되는 것을 확인 할 수 있다.

high_prices = data['High'].values
low_prices = data['Low'].values
mid_prices = (high_prices + low_prices) / 2

최고값과 최소값을 이용하여 평균값을 만든다.

seq_len = 50
sequence_length = seq_len + 1

result = []
for index in range(len(mid_prices) - sequence_length):
    result.append(mid_prices[index: index + sequence_length])

LSTM의 기본개념은 최근 50일치 데이터를 기준으로 내일 주식시장을 예측 하게 된다.

이것을 윈도우라고 하는데 51개의 데이터를 하나의 윈도우로 하여 50개의 데이터를 가지고 51번째 데이터가 결과값이 되는 형태로 생각을 하면 된다.

 

normalized_data = []
for window in result:
    normalized_window = [((float(p) / float(window[0])) - 1) for p in window]
    normalized_data.append(normalized_window)

result = np.array(normalized_data)

# split train and test data
row = int(round(result.shape[0] * 0.9))
train = result[:row, :]
np.random.shuffle(train)

x_train = train[:, :-1]
x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))
y_train = train[:, -1]

x_test = result[row:, :-1]
x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))
y_test = result[row:, -1]

x_train.shape, x_test.shape

모델 정규화 과정을 거친다.

정규화 과정은  다음과 같다.

51개의 데이터중 첫번째 데이터의 값을 0번째 값(window[0]) 으로 잡고  그것을 기준으로 50개의 데이터를 비율로 만들어 본다. 마지막에 1을 빼 줌으로 0번째 값을 0으로 만들어서 0보다 큰지 작은지를 만들어 줄 수가 있다.

그 다음올 train 데이터(90%)와 test 데이터(10%)를 나눠 준다.

 

train 데이터는 50개의 데이터를 보고 51번째 데이터를 만들 것이므로 x_train 에 50개를 넣고, y_train에 마지막 51번째 데이터를 넣어준다.

 

이렇게 하면 1056개의 train셋과 117개의 test셋이 나눠 지는 것을 확인 할 수 있다.

이 의미는 1056일의 데이터를 가지고 117일의 주식데이터를 예측해 보는 것이다.

 

model = Sequential()

model.add(LSTM(50, return_sequences=True, input_shape=(50, 1)))

model.add(LSTM(64, return_sequences=False))

model.add(Dense(1, activation='linear'))

model.compile(loss='mse', optimizer='rmsprop')

model.summary()

그 다음으로 모델을 만들어 본다.

LSTM 모듈을 이용하여 첫번째 LSTM은 유닛수가 50개

두번째 LSTM은 유닛수가 64개 => 이부분은 조정하면서 성능을 테스트 해 봐야 한다.

마지막으로 output은 1개의 결과값이다.(다음날 1일치의 데이터를 예측한다.)

모델을 출력해 보면 50개가 입력 되어 1개가 나오는 모델이 되는 것을 확인 할 수 있다.

 

model.fit(x_train, y_train,
    validation_data=(x_test, y_test),
    batch_size=10,
    epochs=20)

fit 을 이용하여 모델을 훈련시키자.

pred = model.predict(x_test)

fig = plt.figure(facecolor='white', figsize=(20, 10))
ax = fig.add_subplot(111)
ax.plot(y_test, label='True')
ax.plot(pred, label='Prediction')
ax.legend()
plt.show()

그 다음 테스트 데이터를 예측해 봅니다.

예측한 데이터를 pred 변수에 넣은 후 그래프를 그려 보면 다음과 같이 그래프가 그려 지는 것을 확인 할 수 있습니다.

파란색이 실제 데이터이고 주황색이 예측데이터 입니다.

50일치의 데이터를 가지고 하루치의 데이터를 예측하는 모델입니다.

마지막 117일간의 실제데이터와 예측 데이터가 비슷한 모양을 가지고 있는 것을 확인 할 수 있네요.

 

 

어때요 많이 비슷하지 않나요?

 

 

반응형