RNN 과거 주가데이터 학습하여 다음날 종가 예측하기

 

 

김성훈교수님의 아래 예제를 참고하여 수정 및 주석을 추가했습니다.

https://github.com/hunkim/DeepLearningZeroToAll/blob/master/lab-12-5-rnn_stock_prediction.py

 

 










...
 

빨간색이 실제 주가이고 파란색이 예측한 주가이다.

 

 

[전체소스코드]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
import tensorflow as tf
import numpy as np
import matplotlib
import os
import matplotlib.pyplot as plt
 
 
# 랜덤에 의해 똑같은 결과를 재현하도록 시드 설정
# 하이퍼파라미터를 튜닝하기 위한 용도(흔들리면 무엇때문에 좋아졌는지 알기 어려움)
tf.set_random_seed(777)
 
 
def MinMaxScaler(data):
    # 데이터 모든숫자들을 최소 값만큼 뺀다.
    numerator = data - np.min(data, 0)
    # 최대값과 최소 값의 차이(A)를 구한다
    denominator = np.max(data, 0- np.min(data, 0)
    # 너무 큰 값이 나오지 않도록 나눈다
    return numerator / (denominator + 1e-7)
 
    
# 하이퍼파라미터
seq_length = 7       # 1개 시퀀스의 길이(시계열데이터 입력 개수)
data_dim = 5         # Variable 개수
hidden_dim = 10      # 각 셀의 출력 크기
output_dim = 1       # 결과 분류 총 수
learning_rate = 0.01 # 학습률
epoch_num = 500      # 에폭 횟수(학습용전체데이터를 몇 회 반복해서 학습할 것인가 입력)
 
 
# 데이터를 로딩한다.
# 시작가, 고가, 저가, 거래량, 종가
xy = np.loadtxt('stock_daily_price.csv', delimiter=',')
 
 
# 데이터 전처리
xy = xy[::-1# 제일앞이 뒤로, 제일뒤가 앞으로 순서를 뒤집는다.
print("xy[0][0]: ", xy[0][0])
xy = MinMaxScaler(xy)
print("xy[0][0]: ", xy[0][0])
= xy
= xy[:, [-1]] # 마지막 열이 정답(주식 종가)이다.
print("x[0]: ", x[0])
print("y[0]: ",y[0])
 
 
dataX = []
dataY = []
for i in range(0len(y) - seq_length):
    _x = x[i : i+seq_length]
    _y = y[i + seq_length] # 다음 나타날 주가(정답)
    if i is 0:
        print(_x, "->", _y)
    dataX.append(_x)
    dataY.append(_y)
 
 
# 학습용/테스트용 데이터 생성
# 70%를 학습용 데이터로 사용
train_size = int(len(dataY) * 0.7)
# 나머지(30%)를 테스트용 데이터로 사용
test_size = len(dataY) - train_size
 
# 데이터를 잘라 학습용 데이터 생성
trainX = np.array(dataX[0:train_size])
trainY = np.array(dataY[0:train_size])
 
# 데이터를 잘라 테스트용 데이터 생성
testX = np.array(dataX[train_size:len(dataX)])
testY = np.array(dataY[train_size:len(dataY)])
 
 
# 텐서플로우 플레이스홀더 생성
# 학습용/테스트용으로 X, Y를 생성한다
= tf.placeholder(tf.float32, [None, seq_length, data_dim])
print("X: ", X)
= tf.placeholder(tf.float32, [None, 1])
print("Y: ", Y)
 
# 검증용 측정지표를 산출하기 위한 targets, predictions를 생성한다
targets = tf.placeholder(tf.float32, [None, 1])
print("targets: ", targets)
predictions = tf.placeholder(tf.float32, [None, 1])
print("predictions: ", predictions)
 
 
# 모델(LSTM 네트워크) 생성
def lstm_cell():
    # LSTM셀을 생성한다.
    # num_units: 각 Cell 출력 크기
    # forget_bias: The bias added to forget gates.
    # state_is_tuple: True ==> accepted and returned states are 2-tuples of the c_state and m_state.
    # state_is_tuple: False ==> they are concatenated along the column axis.
    # cell = tf.contrib.rnn.BasicLSTMCell(num_units=hidden_dim, state_is_tuple=True, activation=tf.sigmoid)
    # cell = tf.contrib.rnn.BasicLSTMCell(num_units=hidden_dim, state_is_tuple=True, activation=tf.tanh)
    cell = tf.contrib.rnn.BasicLSTMCell(num_units=hidden_dim, forget_bias=0.8, state_is_tuple=True, activation=tf.tanh)
    return cell
 
# 몇개의 층으로 쌓인 Stacked RNNs 생성, 여기서는 1개층만
multi_cells = tf.contrib.rnn.MultiRNNCell([lstm_cell() for _ in range(1)], state_is_tuple=True)
 
# RNN Cell(여기서는 LSTM셀임)들을 연결
hypothesis, _states = tf.nn.dynamic_rnn(multi_cells, X, dtype=tf.float32)
print("hypothesis: ", hypothesis)
 
Y_pred = tf.contrib.layers.fully_connected(hypothesis[:, -1], output_dim, activation_fn=None)
 
 
loss = tf.reduce_sum(tf.square(Y_pred - Y))
optimizer = tf.train.AdamOptimizer(learning_rate)
train = optimizer.minimize(loss)
 
# RMSE(Root Mean Square Error)
# rmse = tf.sqrt(tf.reduce_mean(tf.square(targets-predictions))) # 아래 코드와 같다
rmse = tf.sqrt(tf.reduce_mean(tf.squared_difference(targets, predictions)))
 
 
with tf.Session() as sess:
    init = tf.global_variables_initializer()
    sess.run(init)
    
    # 학습한다
    for epoch in range(epoch_num):
        _, step_loss = sess.run([train, loss], feed_dict={X: trainX, Y: trainY})
        print("[step: {} loss: {}".format(epoch, step_loss))
    
    # 테스트한다
    test_predict = sess.run(Y_pred, feed_dict={X: testX})
    
    # 테스트용 데이터 기준으로 측정지표 rmse를 산출한다
    rmse_val = sess.run(rmse, feed_dict={targets: testY, predictions: test_predict})
    print("rmse: ", rmse_val)
    
    plt.plot(testY, 'r')
    plt.plot(test_predict, 'b')
    plt.xlabel("Time Period")
    plt.ylabel("Stock Price")
    plt.show()
 
 
cs

 

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

 

그리고 추가로 업그레이드한 버전은 아래 글을 참고해주세요.

[Tensorflow] LSTM RNN을 이용하여 아마존 주가 예측하기

http://blog.naver.com/wideeyed/221160038616

 

 

끝.

 

 

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
공지 오라클 기본 샘플 데이터베이스 졸리운_곰 2014.01.02 87147
공지 [SQL컨셉] 서적 "SQL컨셉"의 샘플 데이타 베이스 SAMPLE DATABASE of ORACLE 가을의 곰을... 2013.02.10 79348
공지 [G_SQL] Sample Database 가을의 곰을... 2012.05.20 96073
27 [DB modeling, DB 모델링] [DB] DB 설계 과정 file 졸리운_곰 2025.03.10 1545
26 [DB modeling, DB 모델링] [DATABASE] 기본키(PK), 외래키(FK) file 졸리운_곰 2025.01.29 1904
25 [DB modeling, DB 모델링] 바쁜 데이터 전문가를 위한 7가지 무료 데이터베이스 다이어그래밍 도구 : 7 free database diagramming tools for busy data folks file 졸리운_곰 2025.01.19 1040
24 [DB modeling, DB 모델링] ERD 다이어그램 그리는 방법 file 졸리운_곰 2024.10.29 1410
23 [데이터베이스 모델링] 정규화와 응집도에 대한 고찰 file 졸리운_곰 2024.08.10 1745
22 [데이터베이스 모델링] [SQL] 데이터베이스 관계(Relationship) 기본 (1:1, 1:N, N:N 테이블 생성 예시 포함) file 졸리운_곰 2024.07.12 2106
21 [데이터베이스 모델링] 테이블정의양식 file 졸리운_곰 2024.02.23 1235
20 [데이터베이스 모델링] DAsP - 물리 데이터 모델링 [논리-물리 모델 변환] file 졸리운_곰 2022.05.07 1898
19 [데이터베이스 모델링] 관계형 데이터 모델링 하향식과 상향식 졸리운_곰 2022.05.07 1825
18 [데이터베이스 모델링] 모델링 IE 표기법 (까치발, 까마귀발, crow-feet) file 졸리운_곰 2022.04.26 2163
17 설문 조사를위한 데이터베이스 설계 file 졸리운_곰 2020.09.05 5733
16 [dbguide] 프로세스모델링 작성 절차 (데이터베이스 시스템분석설계 프로세스 모델링) file 졸리운_곰 2020.07.27 1782
15 [dbguide] 데이터모델링 작성 절차 (데이터베이스 모델링 절차) file 졸리운_곰 2020.07.27 1791
14 데이터 품질진단 절차 및 기법 file 졸리운_곰 2020.07.26 2066
13 [번역] 데이터 구조와 설계 — 튜토리얼 file 졸리운_곰 2020.07.26 1815
12 EA( Enterprise Architecture) 전사 아키텍처 file 졸리운_곰 2020.07.25 1790
11 데이터품질관리지침Ver[1].2.1.pdf file 졸리운_곰 2020.07.25 1846
10 테이블 설계의 기초 졸리운_곰 2020.07.25 2131
9 데이터베이스 디자인의 기초 file 졸리운_곰 2020.07.25 1690
8 Enterprise Data Model for Logistics file 졸리운_곰 2019.06.16 1267
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED