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 86852
공지 [SQL컨셉] 서적 "SQL컨셉"의 샘플 데이타 베이스 SAMPLE DATABASE of ORACLE 가을의 곰을... 2013.02.10 79152
공지 [G_SQL] Sample Database 가을의 곰을... 2012.05.20 95892
15 [hadoop] Cloudera Quick Start VM in Hyper-V file 졸리운_곰 2022.11.14 3819
14 [hadoop][java][MapReduce] 맵리듀스 원리와 그 과정 졸리운_곰 2021.02.28 1662
13 [hadoop][mapreduce][csv file] [Reference] : Hadoop MapReduce Join & Counter with Example file 졸리운_곰 2021.02.23 1538
12 [hadoop][mapreduce][csv file] Hadoop & Mapreduce Examples: Create First Program in Java file 졸리운_곰 2021.02.23 1857
11 하둡 맵리듀스(MapReduce) 알아보자 file 졸리운_곰 2019.04.22 2560
10 [하둡] 맵리듀스(MapReduce) 이해하기 file 졸리운_곰 2019.04.22 1984
9 맵/리듀스 (Map/Reduce) 이해하기 file 졸리운_곰 2019.04.22 2652
8 아파치 하둡 HDFS 사용법(Cloudera 사용) file 졸리운_곰 2017.04.19 1610
7 클라우데라 배포판을 이용한 하둡 및 빅데이터 오픈소스 설치하기 file 졸리운_곰 2017.02.14 2030
6 빅데이터 플랫폼 아키텍처의 두 가지 file 졸리운_곰 2016.05.29 1689
5 Hadoop 적용 사례 기사 정리 졸리운_곰 2016.05.29 2012
4 빅데이터 잡설 , 하둡은 어디로 갈꺼나 … file 졸리운_곰 2016.05.29 1744
3 하둡, 데이터 분석에 활용하기까지 file 졸리운_곰 2016.05.29 2150
2 A Guide to Python Frameworks for Hadoop file 졸리운_곰 2016.04.30 3077
1 Writing an Hadoop MapReduce Program in Python file 졸리운_곰 2016.04.30 2193
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED