-
Notifications
You must be signed in to change notification settings - Fork 165
/
hq.py
291 lines (253 loc) · 10.9 KB
/
hq.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
288
289
290
291
# coding=utf-8
#
# Just for practising
#
import datetime
import os
import random
import socket
import sys
import threading
import pandas as pd
from pytdx.base_socket_client import BaseSocketClient, update_last_ack_time
from pytdx.heartbeat import HqHeartBeatThread
from pytdx.log import DEBUG, log
from pytdx.params import TDXParams
from pytdx.parser.get_block_info import (GetBlockInfo, GetBlockInfoMeta,
get_and_parse_block_info)
from pytdx.parser.get_company_info_category import GetCompanyInfoCategory
from pytdx.parser.get_company_info_content import GetCompanyInfoContent
from pytdx.parser.get_finance_info import GetFinanceInfo
from pytdx.parser.get_history_minute_time_data import GetHistoryMinuteTimeData
from pytdx.parser.get_history_transaction_data import GetHistoryTransactionData
from pytdx.parser.get_index_bars import GetIndexBarsCmd
from pytdx.parser.get_minute_time_data import GetMinuteTimeData
from pytdx.parser.get_security_bars import GetSecurityBarsCmd
from pytdx.parser.get_security_count import GetSecurityCountCmd
from pytdx.parser.get_security_list import GetSecurityList
from pytdx.parser.get_security_quotes import GetSecurityQuotesCmd
from pytdx.parser.get_transaction_data import GetTransactionData
from pytdx.parser.get_xdxr_info import GetXdXrInfo
from pytdx.parser.get_report_file import GetReportFile
from pytdx.parser.setup_commands import SetupCmd1, SetupCmd2, SetupCmd3
from pytdx.util import get_real_trade_date, trade_date_sse
try:
# Python 3
from collections.abc import Iterable
except ImportError:
# Python 2.7
from collections import Iterable
if __name__ == '__main__':
sys.path.append(os.path.dirname(
os.path.dirname(os.path.realpath(__file__))))
class TdxHq_API(BaseSocketClient):
def setup(self):
SetupCmd1(self.client).call_api()
SetupCmd2(self.client).call_api()
SetupCmd3(self.client).call_api()
# API List
# Notice:,如果一个股票当天停牌,那天的K线还是能取到,成交量为0
@update_last_ack_time
def get_security_bars(self, category, market, code, start, count):
cmd = GetSecurityBarsCmd(self.client, lock=self.lock)
cmd.setParams(category, market, code, start, count)
return cmd.call_api()
@update_last_ack_time
def get_index_bars(self, category, market, code, start, count):
cmd = GetIndexBarsCmd(self.client, lock=self.lock)
cmd.setParams(category, market, code, start, count)
return cmd.call_api()
'''
category->
K线种类
0 5分钟K线 1 15分钟K线 2 30分钟K线 3 1小时K线 4 日K线
5 周K线
6 月K线
7 1分钟
8 1分钟K线 9 日K线
10 季K线
11 年K线
market -> 市场代码 0:深圳,1:上海
stockcode -> 证券代码;
start -> 指定的范围开始位置;
count -> 用户要请求的 K 线数目,最大值为 800
exp:api.get_index_bars(9,1, '000001', 1, 2)
'''
@update_last_ack_time
def get_security_quotes(self, all_stock, code=None):
"""
支持三种形式的参数
get_security_quotes(market, code )
get_security_quotes((market, code))
get_security_quotes([(market1, code1), (market2, code2)] )
:param all_stock (market, code) 的数组
:param code{optional} code to query
:return:
"""
if code is not None:
all_stock = [(all_stock, code)]
elif (isinstance(all_stock, list) or isinstance(all_stock, tuple))\
and len(all_stock) == 2 and type(all_stock[0]) is int:
all_stock = [all_stock]
cmd = GetSecurityQuotesCmd(self.client, lock=self.lock)
cmd.setParams(all_stock)
return cmd.call_api()
@update_last_ack_time
def get_security_count(self, market):
cmd = GetSecurityCountCmd(self.client, lock=self.lock)
cmd.setParams(market)
return cmd.call_api()
@update_last_ack_time
def get_security_list(self, market, start):
cmd = GetSecurityList(self.client, lock=self.lock)
cmd.setParams(market, start)
return cmd.call_api()
@update_last_ack_time
def get_minute_time_data(self, market, code):
cmd = GetMinuteTimeData(self.client, lock=self.lock)
cmd.setParams(market, code)
return cmd.call_api()
@update_last_ack_time
def get_history_minute_time_data(self, market, code, date):
cmd = GetHistoryMinuteTimeData(self.client, lock=self.lock)
cmd.setParams(market, code, date)
return cmd.call_api()
@update_last_ack_time
def get_transaction_data(self, market, code, start, count):
cmd = GetTransactionData(self.client, lock=self.lock)
cmd.setParams(market, code, start, count)
return cmd.call_api()
@update_last_ack_time
def get_history_transaction_data(self, market, code, start, count, date):
cmd = GetHistoryTransactionData(self.client, lock=self.lock)
cmd.setParams(market, code, start, count, date)
return cmd.call_api()
@update_last_ack_time
def get_company_info_category(self, market, code):
cmd = GetCompanyInfoCategory(self.client, lock=self.lock)
cmd.setParams(market, code)
return cmd.call_api()
@update_last_ack_time
def get_company_info_content(self, market, code, filename, start, length):
cmd = GetCompanyInfoContent(self.client, lock=self.lock)
cmd.setParams(market, code, filename, start, length)
return cmd.call_api()
@update_last_ack_time
def get_xdxr_info(self, market, code):
cmd = GetXdXrInfo(self.client, lock=self.lock)
cmd.setParams(market, code)
return cmd.call_api()
@update_last_ack_time
def get_finance_info(self, market, code):
cmd = GetFinanceInfo(self.client, lock=self.lock)
cmd.setParams(market, code)
return cmd.call_api()
@update_last_ack_time
def get_block_info_meta(self, blockfile):
cmd = GetBlockInfoMeta(self.client, lock=self.lock)
cmd.setParams(blockfile)
return cmd.call_api()
@update_last_ack_time
def get_block_info(self, blockfile, start, size):
cmd = GetBlockInfo(self.client, lock=self.lock)
cmd.setParams(blockfile, start, size)
return cmd.call_api()
def get_and_parse_block_info(self, blockfile):
return get_and_parse_block_info(self, blockfile)
@update_last_ack_time
def get_report_file(self, filename, offset):
cmd = GetReportFile(self.client, lock=self.lock)
cmd.setParams(filename, offset)
return cmd.call_api()
def get_report_file_by_size(self, filename, filesize=0, reporthook=None):
"""
Download file from proxy server
:param filename the filename to download
:param filesize the filesize to download , if you do not known the actually filesize, leave this value 0
"""
filecontent = bytearray(filesize)
current_downloaded_size = 0
get_zero_length_package_times = 0
while current_downloaded_size < filesize or filesize == 0:
response = self.get_report_file(filename, current_downloaded_size)
if response["chunksize"] > 0:
current_downloaded_size = current_downloaded_size + \
response["chunksize"]
filecontent.extend(response["chunkdata"])
if reporthook is not None:
reporthook(current_downloaded_size,filesize)
else:
get_zero_length_package_times = get_zero_length_package_times + 1
if filesize == 0:
break
elif get_zero_length_package_times > 2:
break
return filecontent
def do_heartbeat(self):
self.get_security_count(random.randint(0, 1))
def get_k_data(self, code, start_date, end_date):
# 具体详情参见 https://github.com/rainx/pytdx/issues/5
# 具体详情参见 https://github.com/rainx/pytdx/issues/21
def __select_market_code(code):
code = str(code)
if code[0] in ['5', '6', '9'] or code[:3] in ["009", "126", "110", "201", "202", "203", "204"]:
return 1
return 0
# 新版一劳永逸偷懒写法zzz
market_code = 1 if str(code)[0] == '6' else 0
# https://github.com/rainx/pytdx/issues/33
# 0 - 深圳, 1 - 上海
data = pd.concat([self.to_df(self.get_security_bars(9, __select_market_code(
code), code, (9 - i) * 800, 800)) for i in range(10)], axis=0)
data = data.assign(date=data['datetime'].apply(lambda x: str(x)[0:10])).assign(code=str(code))\
.set_index('date', drop=False, inplace=False)\
.drop(['year', 'month', 'day', 'hour', 'minute', 'datetime'], axis=1)[start_date:end_date]
return data.assign(date=data['date'].apply(lambda x: str(x)[0:10]))
if __name__ == '__main__':
import pprint
api = TdxHq_API()
if api.connect('101.227.73.20', 7709):
log.info("获取股票行情")
stocks = api.get_security_quotes([(0, "000001"), (1, "600300")])
pprint.pprint(stocks)
log.info("获取k线")
data = api.get_security_bars(9, 0, '000001', 4, 3)
pprint.pprint(data)
log.info("获取 深市 股票数量")
pprint.pprint(api.get_security_count(0))
log.info("获取股票列表")
stocks = api.get_security_list(1, 255)
pprint.pprint(stocks)
log.info("获取指数k线")
data = api.get_index_bars(9, 1, '000001', 1, 2)
pprint.pprint(data)
log.info("查询分时行情")
data = api.get_minute_time_data(TDXParams.MARKET_SH, '600300')
pprint.pprint(data)
log.info("查询历史分时行情")
data = api.get_history_minute_time_data(
TDXParams.MARKET_SH, '600300', 20161209)
pprint.pprint(data)
log.info("查询分时成交")
data = api.get_transaction_data(TDXParams.MARKET_SZ, '000001', 0, 30)
pprint.pprint(data)
log.info("查询历史分时成交")
data = api.get_history_transaction_data(
TDXParams.MARKET_SZ, '000001', 0, 10, 20170209)
pprint.pprint(data)
log.info("查询公司信息目录")
data = api.get_company_info_category(TDXParams.MARKET_SZ, '000001')
pprint.pprint(data)
log.info("读取公司信息-最新提示")
data = api.get_company_info_content(0, '000001', '000001.txt', 0, 10)
pprint.pprint(data)
log.info("读取除权除息信息")
data = api.get_xdxr_info(1, '600300')
pprint.pprint(data)
log.info("读取财务信息")
data = api.get_finance_info(0, '000001')
pprint.pprint(data)
log.info("日线级别k线获取函数")
data = api.get_k_data('000001', '2017-07-01', '2017-07-10')
pprint.pprint(data)
api.disconnect()