hikyuu 2.6.5__py3-none-win_amd64.whl → 2.6.6__py3-none-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. hikyuu/__init__.py +6 -0
  2. hikyuu/__init__.pyi +548 -545
  3. hikyuu/analysis/__init__.pyi +519 -518
  4. hikyuu/analysis/analysis.pyi +520 -519
  5. hikyuu/core.pyi +521 -520
  6. hikyuu/cpp/__init__.pyi +2 -2
  7. hikyuu/cpp/boost_date_time-mt.dll +0 -0
  8. hikyuu/cpp/boost_serialization-mt.dll +0 -0
  9. hikyuu/cpp/boost_wserialization-mt.dll +0 -0
  10. hikyuu/cpp/core310.pyd +0 -0
  11. hikyuu/cpp/core310.pyi +35 -25
  12. hikyuu/cpp/core311.pyd +0 -0
  13. hikyuu/cpp/core311.pyi +35 -25
  14. hikyuu/cpp/core312.pyd +0 -0
  15. hikyuu/cpp/core312.pyi +35 -25
  16. hikyuu/cpp/core313.pyd +0 -0
  17. hikyuu/cpp/core313.pyi +35 -25
  18. hikyuu/cpp/core39.pyd +0 -0
  19. hikyuu/cpp/core39.pyi +35 -25
  20. hikyuu/cpp/hikyuu.dll +0 -0
  21. hikyuu/cpp/hikyuu.lib +0 -0
  22. hikyuu/cpp/i18n/__init__.py +0 -0
  23. hikyuu/cpp/i18n/zh_CN.mo +0 -0
  24. hikyuu/cpp/sqlite3.dll +0 -0
  25. hikyuu/data/clickhouse_upgrade/__init__.py +1 -0
  26. hikyuu/data/clickhouse_upgrade/createdb.sql +1085 -0
  27. hikyuu/data/common_clickhouse.py +512 -0
  28. hikyuu/data/em_block_to_clickhouse.py +120 -0
  29. hikyuu/data/hku_config_template.py +58 -3
  30. hikyuu/data/pytdx_finance_to_clickhouse.py +107 -0
  31. hikyuu/data/pytdx_to_clickhouse.py +841 -0
  32. hikyuu/data/pytdx_to_mysql.py +4 -4
  33. hikyuu/data/pytdx_weight_to_clickhouse.py +191 -0
  34. hikyuu/data/tdx_to_clickhouse.py +448 -0
  35. hikyuu/data/zh_bond10_to_clickhouse.py +49 -0
  36. hikyuu/draw/drawplot/__init__.pyi +9 -9
  37. hikyuu/draw/drawplot/bokeh_draw.pyi +537 -534
  38. hikyuu/draw/drawplot/common.pyi +1 -1
  39. hikyuu/draw/drawplot/echarts_draw.pyi +539 -536
  40. hikyuu/draw/drawplot/matplotlib_draw.pyi +549 -546
  41. hikyuu/draw/elder.pyi +11 -11
  42. hikyuu/draw/kaufman.pyi +18 -18
  43. hikyuu/draw/volume.pyi +10 -10
  44. hikyuu/extend.pyi +527 -526
  45. hikyuu/fetcher/stock/zh_stock_a_pytdx.py +9 -20
  46. hikyuu/fetcher/stock/zh_stock_a_qmt.py +4 -5
  47. hikyuu/fetcher/stock/zh_stock_a_sina_qq.py +16 -60
  48. hikyuu/flat/Spot.py +96 -200
  49. hikyuu/gui/HikyuuTDX.py +132 -3
  50. hikyuu/gui/data/ImportBlockInfoTask.py +11 -0
  51. hikyuu/gui/data/ImportHistoryFinanceTask.py +15 -1
  52. hikyuu/gui/data/ImportPytdxTimeToH5Task.py +11 -1
  53. hikyuu/gui/data/ImportPytdxToH5Task.py +13 -1
  54. hikyuu/gui/data/ImportPytdxTransToH5Task.py +11 -1
  55. hikyuu/gui/data/ImportTdxToH5Task.py +13 -1
  56. hikyuu/gui/data/ImportWeightToSqliteTask.py +14 -1
  57. hikyuu/gui/data/ImportZhBond10Task.py +11 -0
  58. hikyuu/gui/data/MainWindow.py +76 -12
  59. hikyuu/gui/data/UsePytdxImportToH5Thread.py +45 -26
  60. hikyuu/gui/data/UseTdxImportToH5Thread.py +19 -1
  61. hikyuu/gui/dataserver.py +12 -4
  62. hikyuu/gui/spot_server.py +30 -40
  63. hikyuu/gui/start_qmt.py +20 -3
  64. hikyuu/hub.pyi +6 -6
  65. hikyuu/include/hikyuu/DataType.h +11 -0
  66. hikyuu/include/hikyuu/StockManager.h +8 -0
  67. hikyuu/include/hikyuu/data_driver/kdata/mysql/KRecordTable.h +1 -0
  68. hikyuu/include/hikyuu/global/GlobalSpotAgent.h +1 -1
  69. hikyuu/include/hikyuu/global/SpotRecord.h +15 -31
  70. hikyuu/include/hikyuu/global/agent/spot_generated.h +48 -232
  71. hikyuu/include/hikyuu/global/schedule/scheduler.h +1 -1
  72. hikyuu/include/hikyuu/plugin/KDataToHdf5Importer.h +3 -0
  73. hikyuu/include/hikyuu/plugin/dataserver.h +26 -1
  74. hikyuu/include/hikyuu/plugin/device.h +2 -1
  75. hikyuu/include/hikyuu/plugin/interface/DataDriverPluginInterface.h +27 -0
  76. hikyuu/include/hikyuu/plugin/interface/DataServerPluginInterface.h +2 -1
  77. hikyuu/include/hikyuu/plugin/interface/DevicePluginInterface.h +1 -1
  78. hikyuu/include/hikyuu/plugin/interface/ImportKDataToHdf5PluginInterface.h +3 -0
  79. hikyuu/include/hikyuu/plugin/interface/plugins.h +2 -0
  80. hikyuu/include/hikyuu/strategy/Strategy.h +0 -9
  81. hikyuu/include/hikyuu/utilities/config.h +1 -1
  82. hikyuu/include/hikyuu/utilities/mo/mo.h +30 -14
  83. hikyuu/include/hikyuu/utilities/os.h +6 -0
  84. hikyuu/include/hikyuu/version.h +4 -4
  85. hikyuu/plugin/backtest.dll +0 -0
  86. hikyuu/plugin/clickhousedriver.dll +0 -0
  87. hikyuu/plugin/dataserver.dll +0 -0
  88. hikyuu/plugin/device.dll +0 -0
  89. hikyuu/plugin/extind.dll +0 -0
  90. hikyuu/plugin/import2hdf5.dll +0 -0
  91. hikyuu/plugin/tmreport.dll +0 -0
  92. hikyuu/trade_manage/__init__.pyi +537 -534
  93. hikyuu/trade_manage/broker.pyi +3 -3
  94. hikyuu/trade_manage/broker_easytrader.pyi +1 -1
  95. hikyuu/trade_manage/trade.pyi +537 -534
  96. hikyuu/util/__init__.py +1 -0
  97. hikyuu/util/__init__.pyi +4 -3
  98. hikyuu/util/check.py +8 -0
  99. hikyuu/util/check.pyi +5 -1
  100. hikyuu/util/singleton.pyi +1 -1
  101. {hikyuu-2.6.5.dist-info → hikyuu-2.6.6.dist-info}/METADATA +2 -2
  102. {hikyuu-2.6.5.dist-info → hikyuu-2.6.6.dist-info}/RECORD +106 -95
  103. {hikyuu-2.6.5.dist-info → hikyuu-2.6.6.dist-info}/top_level.txt +2 -2
  104. hikyuu/include/hikyuu/global/agent/hikyuu/__init__.py +0 -1
  105. hikyuu/include/hikyuu/global/agent/hikyuu/flat/__init__.py +0 -1
  106. {hikyuu-2.6.5.dist-info → hikyuu-2.6.6.dist-info}/LICENSE +0 -0
  107. {hikyuu-2.6.5.dist-info → hikyuu-2.6.6.dist-info}/WHEEL +0 -0
  108. {hikyuu-2.6.5.dist-info → hikyuu-2.6.6.dist-info}/entry_points.txt +0 -0
@@ -349,19 +349,19 @@ def import_one_stock_data(
349
349
  continue
350
350
 
351
351
  if last_krecord is not None and bar_datetime == last_datetime:
352
- if abs(last_krecord[1] - bar["open"]) / last_krecord[1] > 0.02:
352
+ if abs(last_krecord[1] - bar["open"]) / last_krecord[1] > 0.01:
353
353
  hku_error(
354
354
  f"fetch data from tdx error! {bar_datetime} {ktype} {market}{code} last_krecord open: {last_krecord[1]}, bar: {bar['open']}")
355
355
  return 0
356
- if abs(last_krecord[2] - bar["high"]) / last_krecord[2] > 0.02:
356
+ if abs(last_krecord[2] - bar["high"]) / last_krecord[2] > 0.01:
357
357
  hku_error(
358
358
  f"fetch data from tdx error! {bar_datetime} {ktype} {market}{code} last_krecord high: {last_krecord[2]}, bar: {bar['high']}")
359
359
  return 0
360
- if abs(last_krecord[3] - bar["low"]) / last_krecord[3] > 0.02:
360
+ if abs(last_krecord[3] - bar["low"]) / last_krecord[3] > 0.01:
361
361
  hku_error(
362
362
  f"fetch data from tdx error! {bar_datetime} {ktype} {market}{code} last_krecord low: {last_krecord[3]}, bar: {bar['low']}")
363
363
  return 0
364
- if abs(last_krecord[4] - bar["close"]) / last_krecord[4] > 0.02:
364
+ if abs(last_krecord[4] - bar["close"]) / last_krecord[4] > 0.01:
365
365
  hku_error(
366
366
  f"fetch data from tdx error! {bar_datetime} {ktype} {market}{code} last_krecord close: {last_krecord[4]}, bar: {bar['close']}")
367
367
  return 0
@@ -0,0 +1,191 @@
1
+ # coding:utf-8
2
+ #
3
+ # The MIT License (MIT)
4
+ #
5
+ # Copyright (c) 2010-2019 fasiondog/hikyuu
6
+ #
7
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ # of this software and associated documentation files (the "Software"), to deal
9
+ # in the Software without restriction, including without limitation the rights
10
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ # copies of the Software, and to permit persons to whom the Software is
12
+ # furnished to do so, subject to the following conditions:
13
+ #
14
+ # The above copyright notice and this permission notice shall be included in all
15
+ # copies or substantial portions of the Software.
16
+ #
17
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ # SOFTWARE.
24
+
25
+ from pytdx.hq import TDXParams
26
+ from hikyuu.util import *
27
+ from hikyuu.data.common_pytdx import to_pytdx_market
28
+
29
+
30
+ @hku_catch(trace=True)
31
+ def pytdx_import_weight_to_clickhouse(pytdx_api, connect, market):
32
+ """从 pytdx 导入权息数据"""
33
+ pytdx_market = to_pytdx_market(market)
34
+
35
+ total_count = 0
36
+ update_count = 0
37
+ stock_list = connect.query(f"select code from `hku_base`.`stock` where market='{market}' and valid=1")
38
+ stockid_list = stock_list.result_rows
39
+
40
+ for stockrecord in stockid_list:
41
+ code = stockrecord[0]
42
+
43
+ # 获取当前数据库中最后的一条权息记录的总股本和流通股本
44
+ sql = f"select date, countAsGift, countForSell, priceForSell, bonus, countOfIncreasement, totalCount, freeCount, suogu from `hku_base`.`stkweight` where market='{market}' and code='{code}' order by date desc limit 1"
45
+ tmp = connect.query(sql)
46
+ a = tmp.result_rows
47
+ last_db_weight = None
48
+ if a:
49
+ a = list(a[0])
50
+ last_db_weight = a
51
+ db_last_date = a[0]
52
+ last_total_count, last_free_count = a[6:8]
53
+ else:
54
+ last_db_weight = None
55
+ db_last_date, last_total_count, last_free_count = (0, 0, 0)
56
+
57
+ xdxr_list = pytdx_api.get_xdxr_info(pytdx_market, code)
58
+ update_last_db_weight = False
59
+ new_last_db_weight = last_db_weight
60
+ records = {}
61
+ for xdxr in xdxr_list:
62
+ try:
63
+ date = xdxr['year'] * 10000 + xdxr['month'] * 100 + xdxr['day']
64
+ if date < db_last_date:
65
+ continue
66
+ if date == db_last_date and new_last_db_weight is not None:
67
+ if xdxr['songzhuangu'] is not None:
68
+ new_last_db_weight[1] = 10000 * xdxr['songzhuangu']
69
+ update_last_db_weight = True
70
+ if xdxr['peigu'] is not None:
71
+ new_last_db_weight[2] = 10000 * xdxr['peigu']
72
+ update_last_db_weight = True
73
+ if xdxr['peigujia'] is not None:
74
+ new_last_db_weight[3] = 1000 * xdxr['peigujia']
75
+ update_last_db_weight = True
76
+ if xdxr['fenhong'] is not None:
77
+ new_last_db_weight[4] = 1000 * xdxr['fenhong']
78
+ update_last_db_weight = True
79
+ if xdxr['houzongguben'] is not None:
80
+ new_last_db_weight[6] = xdxr['houzongguben']
81
+ update_last_db_weight = True
82
+ last_total_count = new_last_db_weight[6]
83
+ if xdxr['panhouliutong'] is not None:
84
+ new_last_db_weight[7] = xdxr['panhouliutong']
85
+ update_last_db_weight = True
86
+ last_free_count = new_last_db_weight[7]
87
+ if xdxr['suogu'] is not None:
88
+ # etf 扩缩股
89
+ new_last_db_weight[8] = xdxr['suogu']
90
+ update_last_db_weight = True
91
+ continue
92
+ if date not in records:
93
+ records[date] = [
94
+ date,
95
+ 10000 * xdxr['songzhuangu'] if xdxr['songzhuangu'] is not None else 0, # countAsGift
96
+ 10000 * xdxr['peigu'] if xdxr['peigu'] is not None else 0, # countForSell
97
+ 1000 * xdxr['peigujia'] if xdxr['peigujia'] is not None else 0, # priceForSell
98
+ 1000 * xdxr['fenhong'] if xdxr['fenhong'] is not None else 0, # bonus
99
+ 0, # countOfIncreasement, pytdx 不区分送股和转增股,统一记在送股
100
+ xdxr['houzongguben'] if xdxr['houzongguben'] is not None else last_total_count, # totalCount
101
+ xdxr['panhouliutong'] if xdxr['panhouliutong'] is not None else last_free_count, # freeCount
102
+ xdxr["suogu"] if xdxr["suogu"] is not None else 0
103
+ ]
104
+ else:
105
+ if xdxr['songzhuangu'] is not None:
106
+ records[date][1] = 10000 * xdxr['songzhuangu']
107
+ if xdxr['peigu'] is not None:
108
+ records[date][2] = 10000 * xdxr['peigu']
109
+ if xdxr['peigujia'] is not None:
110
+ records[date][3] = 1000 * xdxr['peigujia']
111
+ if xdxr['fenhong'] is not None:
112
+ records[date][4] = 1000 * xdxr['fenhong']
113
+ if xdxr['houzongguben'] is not None:
114
+ records[date][6] = xdxr['houzongguben']
115
+ if xdxr['panhouliutong'] is not None:
116
+ records[date][7] = xdxr['panhouliutong']
117
+ if xdxr['suogu'] is not None:
118
+ records[date][8] = xdxr['suogu']
119
+ if xdxr['houzongguben'] is not None:
120
+ last_total_count = xdxr['houzongguben']
121
+ if xdxr['panhouliutong'] is not None:
122
+ last_free_count = xdxr['panhouliutong']
123
+ except Exception as e:
124
+ print(e)
125
+ print("{}{} xdxr: {} last_db_weigth:{}".format(market, code, xdxr, new_last_db_weight))
126
+ raise e
127
+
128
+ if update_last_db_weight and new_last_db_weight != last_db_weight:
129
+ v = new_last_db_weight
130
+ sql = f"delete from hku_base.stkweight where market='{market}' and code='{code}' and date={v[0]}"
131
+ connect.command(sql)
132
+ records[v[0]] = v
133
+ update_count += 1
134
+
135
+ if records:
136
+ insert_records = []
137
+ for v in records.values():
138
+ tmp = [market, code]
139
+ tmp.extend(v)
140
+ insert_records.append(tmp)
141
+ ic = connect.create_insert_context(table='stkweight', database='hku_base',
142
+ column_names=['market', 'code', 'date', 'countAsGift', 'countForSell',
143
+ 'priceForSell', 'bonus', 'countOfIncreasement', 'totalCount', 'freeCount', 'suogu'],
144
+ data=insert_records)
145
+ connect.insert(context=ic)
146
+ total_count += len(records)
147
+
148
+ total_count = total_count - update_count
149
+ return total_count if total_count > 0 else 0
150
+
151
+
152
+ if __name__ == '__main__':
153
+ import os
154
+ from configparser import ConfigParser
155
+ dev_config = ConfigParser()
156
+ dev_config.read(os.path.expanduser("~") + '/workspace/dev.ini')
157
+ db = 'clickhouse54-http'
158
+ user = dev_config.get(db, 'user')
159
+ password = dev_config.get(db, 'pwd')
160
+ host = dev_config.get(db, 'host')
161
+ port = dev_config.getint(db, 'port')
162
+
163
+ import clickhouse_connect
164
+ client = clickhouse_connect.get_client(
165
+ host=host, username=user, password=password)
166
+
167
+ # sql = "select date, countAsGift, countForSell, priceForSell, bonus, countOfIncreasement, totalCount, freeCount, suogu from `hku_base`.`stkweight` where market='SH' and code='000001' order by date desc limit 1"
168
+ # result = client.query(sql)
169
+ # print(result.result_rows)
170
+ # client.close()
171
+
172
+ tdx_server = '180.101.48.170'
173
+ tdx_port = 7709
174
+ quotations = ['stock', 'fund']
175
+
176
+ from pytdx.hq import TdxHq_API, TDXParams
177
+ api = TdxHq_API()
178
+ api.connect(tdx_server, tdx_port)
179
+
180
+ import time
181
+ starttime = time.time()
182
+ print("开始导入")
183
+ print("导入数量: {}".format(pytdx_import_weight_to_clickhouse(api, client, 'SH')))
184
+
185
+ api.disconnect()
186
+ client.close()
187
+
188
+ endtime = time.time()
189
+ print("\nTotal time:")
190
+ print("%.2fs" % (endtime - starttime))
191
+ print("%.2fm" % ((endtime - starttime) / 60))
@@ -0,0 +1,448 @@
1
+ # coding:utf-8
2
+ #
3
+ # The MIT License (MIT)
4
+ #
5
+ # Copyright (c) 2010-2019 fasiondog/hikyuu
6
+ #
7
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ # of this software and associated documentation files (the "Software"), to deal
9
+ # in the Software without restriction, including without limitation the rights
10
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ # copies of the Software, and to permit persons to whom the Software is
12
+ # furnished to do so, subject to the following conditions:
13
+ #
14
+ # The above copyright notice and this permission notice shall be included in all
15
+ # copies or substantial portions of the Software.
16
+ #
17
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ # SOFTWARE.
24
+
25
+ import os.path
26
+ import struct
27
+ import datetime
28
+ import math
29
+ import sys
30
+
31
+ import mysql.connector
32
+ import tables as tb
33
+
34
+ from io import SEEK_END, SEEK_SET
35
+
36
+ from hikyuu import Datetime
37
+ from hikyuu.data.common import get_stktype_list, MARKET
38
+ from hikyuu.data.common_clickhouse import (
39
+ create_database, get_codepre_list, get_table, get_lastdatetime, update_extern_data
40
+ )
41
+
42
+
43
+ def ProgressBar(cur, total):
44
+ percent = '{:.0%}'.format(cur / total)
45
+ sys.stdout.write('\r')
46
+ sys.stdout.write("[%-50s] %s" % ('=' * int(math.floor(cur * 50 / total)), percent))
47
+ sys.stdout.flush()
48
+
49
+
50
+ def tdx_import_stock_name_from_file(connect, filename, market, quotations=None):
51
+ """更新每只股票的名称、当前是否有效性、起始日期及结束日期
52
+ 如果导入的代码表中不存在对应的代码,则认为该股已失效
53
+
54
+ :param connect: mysql实例
55
+ :param filename: 代码表文件名
56
+ :param market: 'SH' | 'SZ'
57
+ :param quotations: 待导入的行情类别列表,空为导入全部 'stock' | 'fund' | 'bond' | None
58
+ """
59
+ newStockDict = {}
60
+ with open(filename, 'rb') as f:
61
+ data = f.read(50)
62
+ data = f.read(314)
63
+ while data:
64
+ a = struct.unpack('6s 17s 8s 283s', data)
65
+ stockcode = a[0].decode()
66
+ try:
67
+ stockname = a[2].decode(encoding='gbk').encode('utf8')
68
+ except:
69
+ print(stockname)
70
+ data = f.read(314)
71
+ continue
72
+ pos = stockname.find(0x00)
73
+ if pos >= 0:
74
+ stockname = stockname[:pos]
75
+ newStockDict[stockcode] = stockname.decode(encoding='utf8').strip()
76
+ data = f.read(314)
77
+
78
+ stktype_list = get_stktype_list(quotations)
79
+ sql = f"select code, name, type, valid, startDate, endDate from hku_base.stock where market='{market}' and type in {stktype_list}"
80
+ a = connect.query(sql)
81
+ a = a.result_rows
82
+ oldStockDict = {}
83
+ buf = {}
84
+ for oldstock in a:
85
+ oldcode, oldname, oldtype, oldvalid, oldstartDate, oldendDate = oldstock[0], oldstock[1], oldstock[2], int(
86
+ oldstock[3], oldstock[4], oldstock[5])
87
+ oldmarketcode = f'{market}{oldcode}'
88
+ oldStockDict[oldcode] = oldmarketcode
89
+
90
+ # 新的代码表中无此股票,则置为无效
91
+ if (oldvalid == 1) and (oldcode not in newStockDict):
92
+ connect.command(f"delete from hku_base.stock where market='{market}' and code='{oldcode}'")
93
+ buf.append((market, oldcode, oldname, oldtype, 0, today, 99999999))
94
+
95
+ # 股票名称发生变化,更新股票名称;如果原无效,则置为有效
96
+ if oldcode in newStockDict:
97
+ if oldname != newStockDict[oldcode]:
98
+ connect.command(f"delete from hku_base.stock where market='{market}' and code='{oldcode}'")
99
+ buf.append((market, oldcode, newStockDict[oldcode], oldtype,
100
+ oldtype, oldvalid, oldstartDate, oldendDate))
101
+ if oldvalid == 0:
102
+ connect.command(f"delete from hku_base.stock where market='{market}' and code='{oldcode}'")
103
+ buf.append((market, oldcode, oldname, oldtype, 1, oldstartDate, 99999999))
104
+
105
+ # 处理新出现的股票
106
+ codepre_list = get_codepre_list(connect, market, quotations)
107
+
108
+ today = datetime.date.today()
109
+ today = today.year * 10000 + today.month * 100 + today.day
110
+ count = 0
111
+ for code in newStockDict:
112
+ if code not in oldStockDict:
113
+ for codepre in codepre_list:
114
+ length = len(codepre[0])
115
+ if code[:length] == codepre[0]:
116
+ count += 1
117
+ buf.append((market, code, newStockDict[code], codepre[1], 1, today, 99999999))
118
+ break
119
+
120
+ # print('%s新增股票数:%i' % (market.upper(), count))
121
+ if len(buf) > 0:
122
+ ic = connect.create_insert_context(table='stock', database='hku_base',
123
+ column_names=['market', 'code', 'name',
124
+ 'type', 'valid', 'startDate', 'endDate'],
125
+ data=buf)
126
+ connect.insert(context=ic)
127
+ return count
128
+
129
+
130
+ def to_clickhouse_ktype(ktype):
131
+ n_ktype = ktype.upper()
132
+ if n_ktype == 'DAY':
133
+ return n_ktype
134
+ if n_ktype == '1MIN':
135
+ return 'MIN'
136
+ if n_ktype == '5MIN':
137
+ return 'MIN5'
138
+
139
+
140
+ def update_stock_info(connect, market, code):
141
+ sql = f"select toUInt32(min(date)), toUInt32(max(date)) from hku_data.day_k where market='{market}' and code='{code}'"
142
+ a = connect.query(sql)
143
+ a = a.result_rows
144
+ if a:
145
+ sql = f"select valid, startDate, endDate from hku_base.stock where market='{market}' and code='{code}'"
146
+ b = connect.query(sql)
147
+ b = b.result_rows
148
+ if b:
149
+ valid, startDate, endDate = b[0]
150
+ ticks = 1000000
151
+ now_start = Datetime.from_timestamp_utc(a[0][0]*ticks).ymd
152
+ now_end = Datetime.from_timestamp_utc(a[0][1]*ticks).ymd
153
+ if valid == 1 and now_start != startDate:
154
+ sql = f"alter table hku_base.stock update startDate={now_start}, endDate=99999999 where market='{market}' and code='{code}'"
155
+ connect.command(sql)
156
+ elif valid == 0 and now_end != endDate:
157
+ sql = f"alter table hku_base.stock update startDate={now_start}, endDate={now_end} where market='{market}' and code='{code}'"
158
+ connect.command(sql)
159
+
160
+ if ((code == "000001" and market == MARKET.SH)
161
+ or (code == "399001" and market == MARKET.SZ)
162
+ or (code == "830799" and market == MARKET.BJ)):
163
+ sql = f"alter table hku_base.market update lastDate={now_end} where market='{market}'"
164
+ connect.command(sql)
165
+
166
+
167
+ def tdx_import_day_data_from_file(connect, filename, ktype, market, stock_record):
168
+ """从通达信盘后数据导入日K线
169
+
170
+ :param connect : 数据库连接实例
171
+ :param filename: 通达信日线数据文件名
172
+ :param ktype : 'DAY' | '1MIN' | '5MIN'
173
+ :param stock_record: 股票的相关数据 (stockid, marketid, code, valid, type)
174
+ :return: 导入的记录数
175
+ """
176
+ add_record_count = 0
177
+ if not os.path.exists(filename):
178
+ return add_record_count
179
+
180
+ # market, code, name, type, valid, startDate, endDate
181
+ code, stktype = stock_record[1], stock_record[3]
182
+
183
+ table = get_table(connect, market, code, ktype)
184
+ lastdatetime = get_lastdatetime(connect, table)
185
+ if lastdatetime is not None:
186
+ lastdatetime = lastdatetime.ymd
187
+
188
+ buf = []
189
+ with open(filename, 'rb') as src_file:
190
+ data = src_file.read(32)
191
+ while data:
192
+ record = struct.unpack('iiiiifii', data)
193
+ if lastdatetime and record[0] <= lastdatetime:
194
+ data = src_file.read(32)
195
+ continue
196
+
197
+ if record[2] >= record[1] >= record[3] > 0 \
198
+ and record[2] >= record[4] >= record[3] > 0 \
199
+ and record[5] >= 0 \
200
+ and record[6] >= 0:
201
+ buf.append(
202
+ (
203
+ market, code,
204
+ record[0] * 10000, record[1] * 0.01, record[2] * 0.01, record[3] * 0.01,
205
+ record[4] * 0.01, round(record[5] * 0.001),
206
+ record[6] if stktype == 2 else round(record[6] * 0.01)
207
+ )
208
+ )
209
+ add_record_count += 1
210
+ data = src_file.read(32)
211
+
212
+ if len(buf) > 0:
213
+ ic = connect.create_insert_context(table=table[0], data=buf)
214
+ connect.insert(context=ic)
215
+ return add_record_count
216
+
217
+
218
+ def tdx_import_min_data_from_file(connect, filename, ktype, market, stock_record):
219
+ """从通达信盘后数据导入1分钟或5分钟K线
220
+
221
+ :param connect : sqlite3连接实例
222
+ :param filename: 通达信K线数据文件名
223
+ :param ktype: 'DAY' | '1MIN' | '5MIN'
224
+ :param stock_record: 股票的相关数据 (stockid, marketid, code, valid, type)
225
+ :return: 导入的记录数
226
+ """
227
+ add_record_count = 0
228
+ if not os.path.exists(filename):
229
+ return add_record_count
230
+
231
+ # market, code, name, type, valid, startDate, endDate
232
+ code, stktype = stock_record[1], stock_record[3]
233
+
234
+ table = get_table(connect, market, code, to_clickhouse_ktype(ktype))
235
+ lastdatetime = get_lastdatetime(connect, table)
236
+ if lastdatetime is not None:
237
+ lastdatetime = lastdatetime.ymdhm
238
+
239
+ buf = []
240
+ with open(filename, 'rb') as src_file:
241
+
242
+ def trans_date(yymm, hhmm):
243
+ tmp_date = yymm >> 11
244
+ remainder = yymm & 0x7ff
245
+ year = tmp_date + 2004
246
+ month = remainder // 100
247
+ day = remainder % 100
248
+ hh = hhmm // 60
249
+ mm = hhmm % 60
250
+ return year * 100000000 + month * 1000000 + day * 10000 + hh * 100 + mm
251
+
252
+ def get_date(pos):
253
+ src_file.seek(pos * 32, SEEK_SET)
254
+ data = src_file.read(4)
255
+ a = struct.unpack('HH', data)
256
+ return trans_date(a[0], a[1])
257
+
258
+ def find_pos():
259
+ src_file.seek(0, SEEK_END)
260
+ pos = src_file.tell()
261
+ total = pos // 32
262
+ if lastdatetime is None:
263
+ return total, 0
264
+
265
+ low, high = 0, total - 1
266
+ mid = high // 2
267
+ while mid <= high:
268
+ cur_date = get_date(low)
269
+ if cur_date > lastdatetime:
270
+ mid = low
271
+ break
272
+
273
+ cur_date = get_date(high)
274
+ if cur_date <= lastdatetime:
275
+ mid = high + 1
276
+ break
277
+
278
+ cur_date = get_date(mid)
279
+ if cur_date <= lastdatetime:
280
+ low = mid + 1
281
+ else:
282
+ high = mid - 1
283
+
284
+ mid = (low + high) // 2
285
+
286
+ return total, mid
287
+
288
+ file_total, pos = find_pos()
289
+ if pos < file_total:
290
+ src_file.seek(pos * 32, SEEK_SET)
291
+
292
+ data = src_file.read(32)
293
+ while data:
294
+ record = struct.unpack('HHfffffii', data)
295
+ if record[3] >= record[2] >= record[4] > 0\
296
+ and record[3] >= record[5] >= record[4] > 0\
297
+ and record[5] >= 0 \
298
+ and record[6] >= 0:
299
+ buf.append(market, code, trans_date(record[0], record[1]), round(record[2], 2),
300
+ round(record[3], 2), round(record[4], 2), round(record[5],
301
+ 2), record[6] * 0.001,
302
+ record[7] if stktype == 2 else round(record[7] * 0.01))
303
+ add_record_count += 1
304
+
305
+ data = src_file.read(32)
306
+
307
+ if len(buf) > 0:
308
+ ic = connect.create_insert_context(table=table[0], data=buf)
309
+ connect.insert(context=ic)
310
+ return add_record_count
311
+
312
+
313
+ def tdx_import_data(connect, market, ktype, quotations, src_dir, progress=ProgressBar):
314
+ """导入通达信指定盘后数据路径中的K线数据。注:只导入基础信息数据库中存在的股票。
315
+
316
+ :param connect : sqlit3链接
317
+ :param market : 'SH' | 'SZ'
318
+ :param ktype : 'DAY' | '1MIN' | '5MIN'
319
+ :param quotations: 'stock' | 'fund' | 'bond'
320
+ :param src_dir : 盘后K线数据路径,如上证5分钟线:D:\\Tdx\\vipdoc\\sh\\fzline
321
+ :param progress : 进度显示函数
322
+ :return: 导入记录数
323
+ """
324
+ add_record_count = 0
325
+ market = market.upper()
326
+
327
+ if ktype.upper() == "DAY":
328
+ suffix = ".day"
329
+ func_import_from_file = tdx_import_day_data_from_file
330
+ elif ktype.upper() == "1MIN":
331
+ suffix = ".lc1"
332
+ func_import_from_file = tdx_import_min_data_from_file
333
+ elif ktype.upper() == "5MIN":
334
+ suffix = ".lc5"
335
+ func_import_from_file = tdx_import_min_data_from_file
336
+
337
+ stktype_list = get_stktype_list(quotations)
338
+ sql = f"select market, code, name, type, valid, startDate, endDate from hku_base.stock where market='{market}' and type in {stktype_list}"
339
+ a = connect.query(sql)
340
+ a = a.result_rows
341
+
342
+ total = len(a)
343
+ for i, stock in enumerate(a):
344
+ if stock[4] == 0:
345
+ if progress:
346
+ progress(i, total)
347
+ continue
348
+
349
+ filename = src_dir + "\\" + market.lower() + stock[1] + suffix
350
+ this_count = func_import_from_file(connect, filename, ktype, market, stock)
351
+ add_record_count += this_count
352
+ if this_count > 0:
353
+ if ktype == 'DAY':
354
+ stock[1]
355
+ update_stock_info(connect, market.upper(), stock[1])
356
+ update_extern_data(connect, market.upper(), stock[1], "DAY")
357
+ elif ktype == '5MIN':
358
+ update_extern_data(connect, market.upper(), stock[1], "5MIN")
359
+ if progress:
360
+ progress(i, total)
361
+
362
+ if ktype == "DAY":
363
+ connect.command('OPTIMIZE TABLE hku_data.day_k FINAL')
364
+ return add_record_count
365
+
366
+
367
+ if __name__ == '__main__':
368
+
369
+ import time
370
+ starttime = time.time()
371
+
372
+ host = '127.0.0.1'
373
+ port = 3306
374
+ usr = 'root'
375
+ pwd = ''
376
+
377
+ src_dir = "D:\\TdxW_HuaTai"
378
+ quotations = ['stock', 'fund'] # 通达信盘后数据没有债券
379
+
380
+ connect = mysql.connector.connect(user=usr, password=pwd, host=host, port=port)
381
+ create_database(connect)
382
+
383
+ add_count = 0
384
+
385
+ print("导入股票代码表")
386
+ add_count = tdx_import_stock_name_from_file(
387
+ connect, src_dir + "\\T0002\\hq_cache\\shm.tnf", 'SH', quotations
388
+ )
389
+ add_count += tdx_import_stock_name_from_file(
390
+ connect, src_dir + "\\T0002\\hq_cache\\szm.tnf", 'SZ', quotations
391
+ )
392
+ print("新增股票数:", add_count)
393
+
394
+ print("\n导入上证日线数据")
395
+ add_count = tdx_import_data(connect, 'SH', 'DAY', quotations, src_dir + "\\vipdoc\\sh\\lday")
396
+ print("\n导入数量:", add_count)
397
+
398
+ print("\n导入深证日线数据")
399
+ add_count = tdx_import_data(connect, 'SZ', 'DAY', quotations, src_dir + "\\vipdoc\\sz\\lday")
400
+ print("\n导入数量:", add_count)
401
+ """
402
+ print("\n导入上证5分钟数据")
403
+ add_count = tdx_import_data(connect, 'SH', '5MIN', quotations, src_dir + "\\vipdoc\\sh\\fzline")
404
+ print("\n导入数量:", add_count)
405
+
406
+ print("\n导入深证5分钟数据")
407
+ add_count = tdx_import_data(connect, 'SZ', '5MIN', quotations, src_dir + "\\vipdoc\\sz\\fzline")
408
+ print("\n导入数量:", add_count)
409
+
410
+ print("\n导入上证1分钟数据")
411
+ add_count = tdx_import_data(
412
+ connect, 'SH', '1MIN', quotations, src_dir + "\\vipdoc\\sh\\minline"
413
+ )
414
+ print("\n导入数量:", add_count)
415
+
416
+ print("\n导入深证1分钟数据")
417
+ add_count = tdx_import_data(
418
+ connect, 'SZ', '1MIN', quotations, src_dir + "\\vipdoc\\sz\\minline"
419
+ )
420
+ print("\n导入数量:", add_count)
421
+ """
422
+ """
423
+ print("\n导入权息数据")
424
+ print("正在下载权息数据...")
425
+ import urllib.request
426
+ net_file = urllib.request.urlopen(
427
+ 'http://www.qianlong.com.cn/download/history/weight.rar', timeout=60
428
+ )
429
+ dest_dir = os.path.expanduser('~/.hikyuu')
430
+ dest_filename = dest_dir + '/weight.rar'
431
+ with open(dest_filename, 'wb') as file:
432
+ file.write(net_file.read())
433
+
434
+ print("下载完成,正在解压...")
435
+ os.system('unrar x -o+ -inul {} {}'.format(dest_filename, dest_dir))
436
+
437
+ print("解压完成,正在导入...")
438
+ add_count = qianlong_import_weight(connect, dest_dir + '/weight', 'SH')
439
+ add_count += qianlong_import_weight(connect, dest_dir + '/weight', 'SZ')
440
+ print("导入数量:", add_count)
441
+ connect.commit()
442
+ connect.close()
443
+ """
444
+
445
+ endtime = time.time()
446
+ print("\nTotal time:")
447
+ print("%.2fs" % (endtime - starttime))
448
+ print("%.2fm" % ((endtime - starttime) / 60))