forked from happineer/system_trading
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcollect_stock_data_time_unit_kosdaq.py
287 lines (247 loc) · 11.7 KB
/
collect_stock_data_time_unit_kosdaq.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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
# built-in module
import sys
import pdb
import os
from datetime import datetime
import pandas as pd
import time
# UI(PyQt5) module
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QAxContainer import *
from PyQt5 import uic
from PyQt5 import QtGui
from PyQt5.QtCore import pyqtSlot
from kiwoom.kw import Kiwoom
from config import config_manager
from util.tt_logger import TTlog
from util.slack import Slack
from database.db_manager import DBM
from pymongo import MongoClient
import pymongo
import random
from collections import defaultdict
from kiwoom.constant import KiwoomServerCheckTimeError
import multiprocessing
from util import constant
# load main UI object
ui = uic.loadUiType(config_manager.MAIN_UI_PATH)[0]
# main class
class TopTrader(QMainWindow, ui):
def __init__(self):
super().__init__()
# self.setupUi(self) # load app screen
duration = sys.argv[1]
self.logger = TTlog(logger_name="TT"+duration).logger
self.mongo = MongoClient()
self.tt_db = self.mongo.TopTrader
self.slack = Slack(config_manager.get_slack_token())
today = datetime.today()
self.end_date = datetime(today.year, today.month, today.day, 16, 0, 0)
self.kw = Kiwoom()
self.login()
self.get_screen_no = {
"min1": "3000",
"min3": "3001",
"min5": "3002",
"min10": "3003",
"min60": "3004",
"day": "3005",
"week": "3006",
"month": "3007",
"year": "3008"
}
if duration.startswith("min"):
self.collect_n_save_data_min(duration)
else:
self.collect_n_save_data(duration)
def login(self):
err_code = self.kw.login()
if err_code != 0:
self.logger.error("Login Fail")
exit(-1)
self.logger.info("Login success")
def upsert_db(self, col, datas):
self.logger.info("Upsert Data to DB")
s_time = time.time()
for doc in datas:
# col.update(condition, new_data, upsert=True)
col.update({'date': doc['date'], 'code': doc['code']}, doc, upsert=True)
e_time = time.time()
print("Time: ", int(e_time-s_time))
def get_stock_list(self, market):
kospi_code_list = self.kw.get_code_list_by_market(market)
stock_list = [[c, self.kw.get_master_stock_name(c)] for c in kospi_code_list]
stock_list = [(c, name) for c, name in stock_list if not any(map(lambda x: x in name, constant.FILTER_KEYWORD))]
stock_list.sort()
return stock_list
def get_last_data(self, cur, duration):
current_flag = True
if duration.startswith("min"):
first_date = datetime(2018, 7, 23, 0, 0, 0)
else:
first_date = datetime(2018, 6, 1, 0, 0, 0)
# 최초 저장하는 경우
if cur.count() == 0:
s_date, e_date, s_index = first_date, self.end_date, 0
else:
data = cur.next()
if (data['last'] + 1) != data['total']:
# 지난번에 저장하다가 중간에 멈춘 경우
if data['end_date'] != self.end_date:
s_date, e_date, s_index = data['start_date'], data['end_date'], data['last'] + 1
current_flag = False
# 이번에 저장하다가 중간에 멈춘 경우
else:
s_date, e_date, s_index = data['start_date'], self.end_date, data['last'] + 1
else:
# 지난번에 저장을 완료, 이번에 저장해야 하는 경우
if data['end_date'] != self.end_date:
s_date, e_date, s_index = data['end_date'], self.end_date, 0
# 이번에 저장을 완료
else:
s_date, e_date, s_index = data['end_date'], self.end_date, data['last'] + 1
return s_date, e_date, s_index, current_flag
def collect_n_save_data_min(self, duration):
"""
코스피 종목의 분단위 데이터를 수집한다.
1. 한번도 db에 저장한적이 없다면 6/1일부터 오늘까지의 데이터를 저장한다.
2. 지난번에 저장하다가 중간에 멈췄다면, 나머지 작업을 모두 완료 후, 해당시점의 e_date 부터 오늘까지의 데이터를 전 종목에 대해 저장한다.
3. 이번에 저장하다가 중간에 멈췄다면, 이전 e_date 부터 오늘까지의 데이터를 전 종목에 대해 저장한다.
4. 지난번에 저장을 완료했다면, 해당시점의 e_date 부터 오늘까지의 데이터를 전 종목에 대해 저장한다.
:param duration: min1, min3, min5, min10, min60 중 하나의 값
:return:
"""
# stock_list = self.get_stock_list(constant.KOSPI)
# stock_list += self.get_stock_list(constant.KOSDAQ)
stock_list = self.get_stock_list(constant.KOSDAQ)
cur = self.tt_db.time_series_temp2.find({'type': duration})
s_date, e_date, s_index, current_flag = self.get_last_data(cur, duration)
if not current_flag:
msg = "[{}] {} ~ {}. start to collect stock data. this is previous process.".format(
duration, s_date, e_date, e_date, self.end_date
)
else:
msg = "[{}] {} ~ {}. start to collect stock data. this is current process.".format(
duration, s_date, e_date
)
self.slack.log(msg)
col = {
"min1": self.tt_db.time_series_min1,
"min3": self.tt_db.time_series_min3,
"min5": self.tt_db.time_series_min5,
"min10": self.tt_db.time_series_min10,
"min60": self.tt_db.time_series_min60
}[duration]
fn = self.kw.stock_price_by_min
total = len(stock_list)
msg = "[{}] {} / {} -> start to collect stock data".format(duration, s_index, total)
self.slack.log(msg)
for i, stock in enumerate(stock_list[s_index:], s_index):
code, stock_name = stock
self.logger.info("%s/%s - %s/%s" % (i, total, code, stock_name))
self.logger.info("period : {} ~ {}".format(s_date, e_date))
self.logger.info("time_series_{}".format(duration))
try:
doc = fn(code, tick=duration.strip("min"), screen_no=self.get_screen_no[duration],
start_date=s_date, end_date=e_date)
except KiwoomServerCheckTimeError as e:
self.logger.error("[KiwoomServerCheckTimeError] {}".format(duration))
self.tt_db.urgent2.update({'type': 'error'},
{'type': 'error', 'error_code': e.error_code},
upsert=True)
exit(0)
try:
self.upsert_db(col, doc)
except pymongo.errors.InvalidOperation as e:
# cannot do an empty bulk write ?
self.logger.error(e)
self.tt_db.time_series_temp2.update({'type': duration},
{'type': duration,
'code': code,
'stock_name': stock_name,
'last': i,
'start_date': s_date,
'end_date': e_date,
'total': total},
upsert=True)
self.tt_db.urgent2.update({'type': 'error'},
{'type': 'error', 'error_code': 0},
upsert=True)
exit(0) # Program exit
def collect_n_save_data(self, duration):
"""
코스피 종목의 분단위 데이터를 제외한 나머지 데이터를 수집한다.
1. 한번도 db에 저장한적이 없다면 6/1일부터 오늘까지의 데이터를 저장한다.
2. 지난번에 저장하다가 중간에 멈췄다면, 나머지 작업을 모두 완료 후, 해당시점의 e_date 부터 오늘까지의 데이터를 전 종목에 대해 저장한다.
3. 이번에 저장하다가 중간에 멈췄다면, 이전 e_date 부터 오늘까지의 데이터를 전 종목에 대해 저장한다.
4. 지난번에 저장을 완료했다면, 해당시점의 e_date 부터 오늘까지의 데이터를 전 종목에 대해 저장한다.
:param duration: str - day, week, month, year 중 하나의 값
:return:
"""
stock_list = self.get_stock_list(constant.KOSPI)
stock_list += self.get_stock_list(constant.KOSDAQ)
cur = self.tt_db.time_series_temp2.find({'type': duration})
s_date, e_date, s_index, current_flag = self.get_last_data(cur, duration)
if not current_flag:
msg = "[{}] {} ~ {}. start to collect stock data. this is previous process.".format(
duration, s_date, e_date, e_date, self.end_date
)
else:
msg = "[{}] {} ~ {}. start to collect stock data. this is current process.".format(
duration, s_date, e_date
)
self.slack.log(msg)
col = {
"day": self.tt_db.time_series_day,
"week": self.tt_db.time_series_week,
"month": self.tt_db.time_series_month,
"year": self.tt_db.time_series_year
}[duration]
fn = {
"day": self.kw.stock_price_by_day,
"week": self.kw.stock_price_by_week,
"month": self.kw.stock_price_by_month
# "year": self.kw.stock_price_by_year
}[duration]
total = len(stock_list)
msg = "[{}] {} / {} -> start to collect stock data".format(duration, s_index, total)
self.slack.log(msg)
for i, stock in enumerate(stock_list[s_index:], s_index):
code, stock_name = stock
self.logger.info("%s/%s - %s/%s" % (i, total, code, stock_name))
self.logger.info("time_series_{}".format(duration))
try:
doc = fn(code, screen_no=self.get_screen_no[duration], start_date=s_date, end_date=e_date)
except KiwoomServerCheckTimeError as e:
self.logger.error("[KiwoomServerCheckTimeError] {}".format(duration))
self.tt_db.urgent2.update({'type': 'error'},
{'type': 'error', 'error_code': e.error_code},
upsert=True)
exit(0)
self.upsert_db(col, doc)
self.tt_db.time_series_temp2.update({'type': duration},
{'type': duration,
'code': code,
'stock_name': stock_name,
'last': i,
'start_date': s_date,
'end_date': e_date,
'total': total},
upsert=True)
self.tt_db.urgent2.update({'type': 'error'},
{'type': 'error', 'error_code': 0},
upsert=True)
exit(0) # Program exit
# Print Exception Setting
sys._excepthook = sys.excepthook
def exception_hook(exctype, value, traceback):
sys._excepthook(exctype, value, traceback)
sys.exit(1)
sys.excepthook = exception_hook
if __name__ == "__main__":
global app
app = QApplication(sys.argv)
tt = TopTrader()
tt.show()
sys.exit(app.exec_())