-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnaver_stock.py
192 lines (172 loc) · 6.36 KB
/
naver_stock.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
# -*- coding: utf-8 -*-
"""
nv: 현재가
cd: 종목코드
eps: nv/eps PER(배)
bps: nv/bps PBR(배)
ov: 시가
sv: 전일?
pcv: 전일
cv: 전일 대비
cr: 전일 대비 증감 %
aq: 거래량
aa: 거래대금
ms: 장상태 ('OPEN', 'CLOSE')
hv: 고가
lv: 저가
ul: 상한가
ll: 하한가
nm: 이름
keps:
dv:
cnsEps:
nav:
rf:
mt:
tyn:
"""
import json
from utils import data_to_dic, get_json, format_num, get_query, encode, \
run_threads
from collections import namedtuple
from os.path import exists
from os import remove
import re
import sys
from workflow import Workflow
if sys.version_info[0] == 3:
pass
else:
reload(sys)
sys.setdefaultencoding("utf-8")
Item = namedtuple('Item', ['title', 'subtitle', 'url', 'icon'])
class Stock(Workflow):
LIST_URL = u'https://ac.finance.naver.com/ac?q=%s&q_enc=euc-kr&st=111&frm=stock&r_format=json&r_enc=euc-kr&r_unicode=0&t_koreng=1&r_lt=111'
SEARCH_URL = u'https://finance.naver.com/item/main.nhn?code=%s'
POLLING_URL = u'http://polling.finance.naver.com/api/realtime?query=SERVICE_ITEM:%s'
FAVORITE_FILE = './favorite.json'
def __init__(self):
super(Stock, self).__init__()
self.search_cache = {}
def add(self, title, subtitle='', url=None, icon=None):
self.add_item(title, subtitle, valid=True, modifier_subtitles={'ctrl': '즐겨찾기에 추가합니다.', 'alt': '즐겨찾기에서 삭제합니다.'}, arg=url, icon=icon)
def build_item(self, item):
url = self.SEARCH_URL % encode(item['label'])
if 'nv' in item and 'pcv' in item and 'ov' in item:
if item['nv'] > item['pcv'] or (item['nv'] == item['pcv'] > item['ov']):
sign = '+'
if item['ms'] == 'OPEN':
icon = './icons/red-arrow-up.png'
else:
icon = './icons/grey-arrow-up.png'
elif item['nv'] < item['pcv'] or (item['nv'] == item['pcv'] < item['ov']):
sign = '-'
if item['ms'] == 'OPEN':
icon = './icons/blue-arrow-down.png'
else:
icon = './icons/grey-arrow-down.png'
else:
sign = ' '
icon = ''
space = 40 - len(item['name'].encode('euc-kr'))
if 'nv' in item:
item['current_value'] = '₩ ' + format_num(item['nv'])
if 'cr' in item:
item['change_rate'] = format_num(item['cr'], 2)
if 'cv' in item:
item['change_value'] = format_num(item['cv'])
if 'aq' in item:
item['volume'] = format_num(item['aq'])
if 'hv' in item:
item['high_value'] = format_num(item['hv'])
if 'lv' in item:
item['low_value'] = format_num(item['lv'])
if 'nv' in item and 'eps' in item:
item['per'] = format_num(float(item['nv']) / float(item['eps']), 2) + '배'
if 'nv' in item and 'bps' in item:
item['pbr'] = format_num(float(item['nv']) / float(item['bps']), 2) + '배'
# 종목 현재가 (+ 비율% 변동)
title = (u'{name:<%s}\t{current_value:<15}\t( {sign} {change_rate} %%, {change_value})' % space).format(
name=item['name'],
current_value=item.get('current_value'),
sign=sign,
change_rate=item.get('change_rate'),
change_value=item.get('change_value'))
subtitle = u'{market} 거래량: {volume} 고가: {high_value} 저가: {low_value} PER: {per} PBR: {pbr}'.format(
market=item['market'],
volume=item.get('volume'),
high_value=item.get('high_value'),
low_value=item.get('low_value'),
per=item.get('per'),
pbr=item.get('pbr'))
return Item(title, subtitle, url, icon)
# except Exception:
# return Item(item['name'], item['market'], url, icon)
def load_favorites(self):
if exists(self.FAVORITE_FILE):
with open(self.FAVORITE_FILE, 'r') as f:
return json.load(f)
else:
return []
def get_items(self, query):
if query in self.search_cache:
return self.search_cache[query]
url = self.LIST_URL % query
data = get_json(url)[u'items']
items = data_to_dic(data)
self.search_cache[query] = items
return items
def fetch(self, code):
data = get_json(self.POLLING_URL % code)
data_points = data['result']['areas'][0]['datas']
if data_points:
return data_points[0]
else:
return {}
def search(self, *args):
query = get_query(args)
if query:
items = self.get_items(query)
else:
items = self.load_favorites()
details = run_threads(self.fetch, [(item['code'], ) for item in items])
for item, detail in zip(items, details):
item.update(detail)
for item in items:
# TODO: support non korean stock market
if 'nv' in item:
self.add(**self.build_item(item)._asdict())
def search_for_delete(self):
self.add('삭제하고 싶은 종목을 선택하세요.')
self.search()
def set_favorite(self, url):
label = re.search(r'code=([^&]*)', url).groups()[0]
item = self.get_items(label)[0]
if exists(self.FAVORITE_FILE):
with open(self.FAVORITE_FILE, 'r') as f:
favorites = json.load(f)
favorites.append(item)
else:
favorites = [item]
with open(self.FAVORITE_FILE, 'w') as f:
json.dump(favorites, f, indent=4)
def del_favorite(self, url):
label = re.search(r'code=([^&]*)', url).groups()[0]
if exists(self.FAVORITE_FILE):
with open(self.FAVORITE_FILE, 'r') as f:
favorites = json.load(f)
favorites = [item for item in favorites if item['code'] != label]
else:
favorites = []
with open(self.FAVORITE_FILE, 'w') as f:
json.dump(favorites, f, indent=4)
def reset_favorite(self):
if exists(self.FAVORITE_FILE):
remove(self.FAVORITE_FILE)
def main():
command = sys.argv[1]
stock = Stock()
getattr(stock, command)(*sys.argv[2:])
stock.send_feedback()
if __name__ == '__main__':
main()