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 86873
공지 [SQL컨셉] 서적 "SQL컨셉"의 샘플 데이타 베이스 SAMPLE DATABASE of ORACLE 가을의 곰을... 2013.02.10 79171
공지 [G_SQL] Sample Database 가을의 곰을... 2012.05.20 95908
27 [java dbms][database] [컴] Apache Derby 사용하기 - 4 - in-memory DB 졸리운_곰 2021.04.15 1564
26 [java dbms][database] [컴] Apache Derby 사용하기 - 3 - Apache Derby Network Server 졸리운_곰 2021.04.15 1637
25 [java dbms][database] [컴] Apache Derby 사용하기 - 2 - sql script tool ij 사용하기 졸리운_곰 2021.04.15 1827
24 [java dbms][database] [컴] Apache Derby 사용하기 - 1 - Derby 설치 file 졸리운_곰 2021.04.15 1157
23 실습 2 - GROUP 졸리운_곰 2020.09.30 1552
22 [SQL 가이드] 데이터베이스 모델의 이해 (Understanding Database model) file 졸리운_곰 2020.06.13 2489
21 [SQL 가이드] 식별자(Identification)의 개념 file 졸리운_곰 2020.06.13 2067
20 [SQL 가이드] 관계(relationship)의 개념 file 졸리운_곰 2020.06.13 1560
19 [SQL 가이드] 속성(attribute)의 개념 file 졸리운_곰 2020.06.13 1707
18 [SQL 가이드] 엔티티의 개념 file 졸리운_곰 2020.06.13 2205
17 [SQL] join의 on절과 where절 차이 졸리운_곰 2020.05.16 1305
16 JOIN*(3개 테이블) and GROUP BY*(보이지않더라도 key칼럼으로) and ORDER BY 졸리운_곰 2020.05.16 1226
15 다중 테이블에서 데이터 검색 - JOIN file 졸리운_곰 2020.05.16 1603
14 IFNULL(MYSQL), ISNULL(MSSQL), NVL(ORACLE) 졸리운_곰 2018.07.24 1779
13 4 Ways to Join Only The First Row in SQL file 졸리운_곰 2018.07.03 1642
12 DBMS별 기존테이블 SELECT해서 새 테이블에 INSERT하여 데이터 ... file 졸리운_곰 2018.01.22 1593
11 SOL 개발자의 현주소 : 개발자가 SQL 작성시 고쳐야 하는 태도 file 졸리운_곰 2018.01.01 2160
10 오라클 운반 최소 단위 BLOCK file 졸리운_곰 2017.07.15 2040
9 재미있는 DB 이야기 ‘놀라운 마방진의 세계’ file 졸리운_곰 2017.07.15 2400
8 재미있는 DB 이야기 ‘사라진 날짜를 찾아라’ file 졸리운_곰 2017.07.15 2236
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED