hikyuu 2.3.0__py3-none-win_amd64.whl → 2.5.0__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 (179) hide show
  1. hikyuu/__init__.py +438 -6
  2. hikyuu/__init__.pyi +791 -0
  3. hikyuu/analysis/__init__.pyi +487 -0
  4. hikyuu/analysis/analysis.pyi +517 -0
  5. hikyuu/core.pyi +482 -0
  6. hikyuu/cpp/__init__.pyi +3 -0
  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/core311.pyd +0 -0
  12. hikyuu/cpp/core312.pyd +0 -0
  13. hikyuu/cpp/core312.pyi +12867 -0
  14. hikyuu/cpp/core313.pyd +0 -0
  15. hikyuu/cpp/core38.pyd +0 -0
  16. hikyuu/cpp/core39.pyd +0 -0
  17. hikyuu/cpp/hikyuu.dll +0 -0
  18. hikyuu/cpp/hikyuu.lib +0 -0
  19. hikyuu/cpp/sqlite3.dll +0 -0
  20. hikyuu/data/common_mysql.py +24 -7
  21. hikyuu/data/common_pytdx.py +17 -1
  22. hikyuu/data/em_block_to_mysql.py +3 -2
  23. hikyuu/data/em_block_to_sqlite.py +8 -3
  24. hikyuu/data/mysql_upgrade/0025.sql +61 -0
  25. hikyuu/data/mysql_upgrade/0026.sql +9 -0
  26. hikyuu/data/sqlite_upgrade/0025.sql +63 -0
  27. hikyuu/data/sqlite_upgrade/0026.sql +10 -0
  28. hikyuu/draw/__init__.pyi +35 -0
  29. hikyuu/draw/drawplot/__init__.py +3 -0
  30. hikyuu/draw/drawplot/__init__.pyi +134 -0
  31. hikyuu/draw/drawplot/bokeh_draw.pyi +796 -0
  32. hikyuu/draw/drawplot/common.pyi +10 -0
  33. hikyuu/draw/drawplot/echarts_draw.py +219 -24
  34. hikyuu/draw/drawplot/echarts_draw.pyi +682 -0
  35. hikyuu/draw/drawplot/matplotlib_draw.py +18 -3
  36. hikyuu/draw/drawplot/matplotlib_draw.pyi +1101 -0
  37. hikyuu/draw/elder.pyi +44 -0
  38. hikyuu/draw/kaufman.pyi +38 -0
  39. hikyuu/draw/volume.pyi +31 -0
  40. hikyuu/examples/notebook/Demo/Demo2.ipynb +1 -1
  41. hikyuu/extend.py +9 -3
  42. hikyuu/extend.pyi +636 -0
  43. hikyuu/fetcher/stock/zh_block_em.py +118 -51
  44. hikyuu/gui/data/EscapetimeThread.py +4 -4
  45. hikyuu/gui/data/ImportBlockInfoTask.py +3 -2
  46. hikyuu/gui/data/ImportHistoryFinanceTask.py +2 -0
  47. hikyuu/gui/data/MainWindow.py +48 -42
  48. hikyuu/gui/importdata.py +13 -26
  49. hikyuu/hub.py +2 -4
  50. hikyuu/hub.pyi +254 -0
  51. hikyuu/include/hikyuu/DataType.h +5 -0
  52. hikyuu/include/hikyuu/Stock.h +7 -0
  53. hikyuu/include/hikyuu/indicator/Indicator.h +8 -1
  54. hikyuu/include/hikyuu/indicator/Indicator2InImp.h +65 -0
  55. hikyuu/include/hikyuu/indicator/IndicatorImp.h +4 -3
  56. hikyuu/include/hikyuu/indicator/build_in.h +12 -0
  57. hikyuu/include/hikyuu/indicator/crt/ADVANCE.h +3 -1
  58. hikyuu/include/hikyuu/indicator/crt/CONTEXT.h +2 -2
  59. hikyuu/include/hikyuu/indicator/crt/CORR.h +4 -2
  60. hikyuu/include/hikyuu/indicator/crt/COST.h +3 -0
  61. hikyuu/include/hikyuu/indicator/crt/CYCLE.h +24 -0
  62. hikyuu/include/hikyuu/indicator/crt/DECLINE.h +3 -1
  63. hikyuu/include/hikyuu/indicator/crt/DISCARD.h +27 -0
  64. hikyuu/include/hikyuu/indicator/crt/DMA.h +2 -1
  65. hikyuu/include/hikyuu/indicator/crt/HSL.h +1 -13
  66. hikyuu/include/hikyuu/indicator/crt/INBLOCK.h +31 -0
  67. hikyuu/include/hikyuu/indicator/crt/INDEX.h +60 -0
  68. hikyuu/include/hikyuu/indicator/crt/INSUM.h +5 -2
  69. hikyuu/include/hikyuu/indicator/crt/ISINF.h +28 -0
  70. hikyuu/include/hikyuu/indicator/crt/ISINFA.h +28 -0
  71. hikyuu/include/hikyuu/indicator/crt/ISNA.h +29 -0
  72. hikyuu/include/hikyuu/indicator/crt/JUMPDOWN.h +24 -0
  73. hikyuu/include/hikyuu/indicator/crt/JUMPUP.h +24 -0
  74. hikyuu/include/hikyuu/indicator/crt/LASTVALUE.h +29 -0
  75. hikyuu/include/hikyuu/indicator/crt/LIUTONGPAN.h +1 -0
  76. hikyuu/include/hikyuu/indicator/crt/REPLACE.h +29 -0
  77. hikyuu/include/hikyuu/indicator/crt/SPEARMAN.h +3 -2
  78. hikyuu/include/hikyuu/indicator/crt/WINNER.h +38 -0
  79. hikyuu/include/hikyuu/indicator/imp/IContext.h +1 -1
  80. hikyuu/include/hikyuu/indicator/imp/ICorr.h +7 -22
  81. hikyuu/include/hikyuu/indicator/imp/ICost.h +31 -0
  82. hikyuu/include/hikyuu/indicator/imp/ICycle.h +30 -0
  83. hikyuu/include/hikyuu/indicator/imp/IDiscard.h +28 -0
  84. hikyuu/include/hikyuu/indicator/imp/IDma.h +7 -24
  85. hikyuu/include/hikyuu/indicator/imp/IHsl.h +30 -0
  86. hikyuu/include/hikyuu/indicator/imp/IInBlock.h +30 -0
  87. hikyuu/include/hikyuu/indicator/imp/IIndex.h +26 -0
  88. hikyuu/include/hikyuu/indicator/imp/IIsInf.h +26 -0
  89. hikyuu/include/hikyuu/indicator/imp/IIsInfa.h +26 -0
  90. hikyuu/include/hikyuu/indicator/imp/IIsNa.h +26 -0
  91. hikyuu/include/hikyuu/indicator/imp/IJumpDown.h +24 -0
  92. hikyuu/include/hikyuu/indicator/imp/IJumpUp.h +24 -0
  93. hikyuu/include/hikyuu/indicator/imp/ILastValue.h +26 -0
  94. hikyuu/include/hikyuu/indicator/imp/IReplace.h +26 -0
  95. hikyuu/include/hikyuu/indicator/imp/ISpearman.h +6 -21
  96. hikyuu/include/hikyuu/indicator/imp/IWinner.h +26 -0
  97. hikyuu/include/hikyuu/indicator_talib/imp/TaMavp.h +6 -20
  98. hikyuu/include/hikyuu/indicator_talib/imp/ta_defines.h +14 -65
  99. hikyuu/include/hikyuu/indicator_talib/imp/ta_imp.h +54 -90
  100. hikyuu/include/hikyuu/indicator_talib/ta_crt.h +11 -9
  101. hikyuu/include/hikyuu/strategy/RunPortfolioInStrategy.h +3 -4
  102. hikyuu/include/hikyuu/strategy/Strategy.h +4 -5
  103. hikyuu/include/hikyuu/trade_manage/TradeRecord.h +5 -1
  104. hikyuu/include/hikyuu/trade_sys/allocatefunds/build_in.h +1 -0
  105. hikyuu/include/hikyuu/trade_sys/allocatefunds/crt/AF_FixedWeightList.h +22 -0
  106. hikyuu/include/hikyuu/trade_sys/allocatefunds/imp/FixedWeightListAllocateFunds.h +25 -0
  107. hikyuu/include/hikyuu/trade_sys/moneymanager/MoneyManagerBase.h +17 -4
  108. hikyuu/include/hikyuu/trade_sys/moneymanager/build_in.h +2 -0
  109. hikyuu/include/hikyuu/trade_sys/moneymanager/crt/MM_FixedCapital.h +6 -0
  110. hikyuu/include/hikyuu/trade_sys/moneymanager/crt/MM_FixedCapitalFunds.h +26 -0
  111. hikyuu/include/hikyuu/trade_sys/moneymanager/crt/MM_FixedCountTps.h +27 -0
  112. hikyuu/include/hikyuu/trade_sys/moneymanager/crt/MM_FixedRisk.h +6 -0
  113. hikyuu/include/hikyuu/trade_sys/moneymanager/crt/MM_FixedUnits.h +6 -0
  114. hikyuu/include/hikyuu/trade_sys/moneymanager/crt/MM_WilliamsFixedRisk.h +7 -0
  115. hikyuu/include/hikyuu/trade_sys/moneymanager/imp/FixedCapitalFundsMM.h +28 -0
  116. hikyuu/include/hikyuu/trade_sys/moneymanager/imp/FixedCountTpsMM.h +44 -0
  117. hikyuu/include/hikyuu/trade_sys/multifactor/build_in.h +1 -0
  118. hikyuu/include/hikyuu/trade_sys/multifactor/crt/MF_Weight.h +30 -0
  119. hikyuu/include/hikyuu/trade_sys/multifactor/imp/WeightMultiFactor.h +41 -0
  120. hikyuu/include/hikyuu/trade_sys/portfolio/Portfolio.h +38 -37
  121. hikyuu/include/hikyuu/trade_sys/portfolio/build_in.h +1 -0
  122. hikyuu/include/hikyuu/trade_sys/portfolio/crt/PF_Simple.h +25 -1
  123. hikyuu/include/hikyuu/trade_sys/portfolio/crt/PF_WithoutAF.h +50 -0
  124. hikyuu/include/hikyuu/trade_sys/portfolio/imp/SimplePortfolio.h +53 -0
  125. hikyuu/include/hikyuu/trade_sys/portfolio/imp/WithoutAFPortfolio.h +57 -0
  126. hikyuu/include/hikyuu/trade_sys/selector/imp/MultiFactorSelector.h +7 -0
  127. hikyuu/include/hikyuu/trade_sys/signal/SignalBase.h +51 -5
  128. hikyuu/include/hikyuu/trade_sys/signal/build_in.h +2 -0
  129. hikyuu/include/hikyuu/trade_sys/signal/crt/SG_Bool.h +2 -1
  130. hikyuu/include/hikyuu/trade_sys/signal/crt/SG_Logic.h +37 -0
  131. hikyuu/include/hikyuu/trade_sys/signal/crt/SG_OneSide.h +28 -0
  132. hikyuu/include/hikyuu/trade_sys/signal/imp/OneSideSignal.h +46 -0
  133. hikyuu/include/hikyuu/trade_sys/signal/imp/logic/AddSignal.h +19 -0
  134. hikyuu/include/hikyuu/trade_sys/signal/imp/logic/AddValueSignal.h +19 -0
  135. hikyuu/include/hikyuu/trade_sys/signal/imp/logic/DivSignal.h +19 -0
  136. hikyuu/include/hikyuu/trade_sys/signal/imp/logic/DivValueSignal.h +22 -0
  137. hikyuu/include/hikyuu/trade_sys/signal/imp/logic/MulSignal.h +19 -0
  138. hikyuu/include/hikyuu/trade_sys/signal/imp/logic/MulValueSignal.h +19 -0
  139. hikyuu/include/hikyuu/trade_sys/signal/imp/logic/OperatorSignal.h +68 -0
  140. hikyuu/include/hikyuu/trade_sys/signal/imp/logic/OperatorValueSignal.h +67 -0
  141. hikyuu/include/hikyuu/trade_sys/signal/imp/logic/SubSignal.h +19 -0
  142. hikyuu/include/hikyuu/trade_sys/signal/imp/logic/SubValueSignal.h +22 -0
  143. hikyuu/include/hikyuu/trade_sys/signal/imp/logic/__init__.py +1 -0
  144. hikyuu/include/hikyuu/trade_sys/stoploss/crt/ST_Indicator.h +1 -1
  145. hikyuu/include/hikyuu/trade_sys/stoploss/imp/IndicatorStoploss.h +3 -4
  146. hikyuu/include/hikyuu/utilities/FilterNode.h +2 -2
  147. hikyuu/include/hikyuu/utilities/Log.h +42 -15
  148. hikyuu/include/hikyuu/utilities/datetime/Datetime.h +1 -1
  149. hikyuu/include/hikyuu/utilities/datetime/TimeDelta.h +2 -2
  150. hikyuu/include/hikyuu/utilities/db_connect/DBCondition.h +4 -0
  151. hikyuu/include/hikyuu/utilities/db_connect/SQLResultSet.h +2 -2
  152. hikyuu/include/hikyuu/utilities/db_connect/mysql/MySQLConnect.h +5 -1
  153. hikyuu/include/hikyuu/utilities/node/NodeServer.h +4 -4
  154. hikyuu/include/hikyuu/utilities/thread/MQStealThreadPool.h +2 -2
  155. hikyuu/include/hikyuu/utilities/thread/MQThreadPool.h +2 -2
  156. hikyuu/include/hikyuu/utilities/thread/StealThreadPool.h +5 -5
  157. hikyuu/include/hikyuu/utilities/thread/ThreadPool.h +2 -2
  158. hikyuu/include/hikyuu/utilities/thread/algorithm.h +16 -10
  159. hikyuu/include/hikyuu/version.h +4 -4
  160. hikyuu/indicator/indicator.py +1 -0
  161. hikyuu/interactive.py +3 -266
  162. hikyuu/trade_manage/__init__.pyi +584 -0
  163. hikyuu/trade_manage/broker.pyi +54 -0
  164. hikyuu/trade_manage/broker_easytrader.pyi +21 -0
  165. hikyuu/trade_manage/broker_mail.pyi +55 -0
  166. hikyuu/trade_manage/trade.pyi +590 -0
  167. hikyuu/util/__init__.pyi +55 -0
  168. hikyuu/util/check.pyi +59 -0
  169. hikyuu/util/mylog.pyi +70 -0
  170. hikyuu/util/notebook.pyi +23 -0
  171. hikyuu/util/singleton.pyi +18 -0
  172. hikyuu/util/slice.pyi +8 -0
  173. {hikyuu-2.3.0.dist-info → hikyuu-2.5.0.dist-info}/METADATA +3 -2
  174. {hikyuu-2.3.0.dist-info → hikyuu-2.5.0.dist-info}/RECORD +178 -95
  175. {hikyuu-2.3.0.dist-info → hikyuu-2.5.0.dist-info}/top_level.txt +1 -0
  176. hikyuu/deprecated.py +0 -651
  177. {hikyuu-2.3.0.dist-info → hikyuu-2.5.0.dist-info}/LICENSE +0 -0
  178. {hikyuu-2.3.0.dist-info → hikyuu-2.5.0.dist-info}/WHEEL +0 -0
  179. {hikyuu-2.3.0.dist-info → hikyuu-2.5.0.dist-info}/entry_points.txt +0 -0
hikyuu/__init__.py CHANGED
@@ -51,26 +51,53 @@ SOFTWARE.
51
51
  import traceback
52
52
  import sys
53
53
  import pickle
54
-
55
- from .util import *
54
+ import os
56
55
 
57
56
  try:
57
+ from .util import *
58
58
  from .extend import *
59
- # from .deprecated import * # pybind getattr 会被递归,无法使用
60
59
  from .indicator import *
61
60
  from .trade_manage import *
62
61
  from .trade_sys import *
63
62
  from .analysis import *
64
63
  from .hub import *
64
+ from .draw import *
65
65
  except Exception as e:
66
66
  info = sys.exc_info()
67
- hku_fatal("{}: {}".format(info[0].__name__, info[1]))
68
- hku_fatal(traceback.format_exc())
67
+ # hku_fatal("{}: {}".format(info[0].__name__, info[1]))
68
+ # hku_fatal(traceback.format_exc())
69
+ print("{}: {}".format(info[0].__name__, info[1]))
70
+ print(traceback.format_exc())
69
71
  print("""请使用 pipdeptree -p hikyuu 检查是否存在缺失的依赖包。
70
72
  如果没有问题可以在 https://gitee.com/fasiondog/hikyuu 或 https://github.com/fasiondog/hikyuu
71
73
  上提交 issue,同时附上 "用户目录/.hikyuu" 下的 hikyuu_py.log 和 hikyuu.log 日志文件 """)
72
74
  raise e
73
75
 
76
+
77
+ __copyright__ = """
78
+ MIT License
79
+
80
+ Copyright (c) 2010-2017 fasiondog
81
+
82
+ Permission is hereby granted, free of charge, to any person obtaining a copy
83
+ of this software and associated documentation files (the "Software"), to deal
84
+ in the Software without restriction, including without limitation the rights
85
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
86
+ copies of the Software, and to permit persons to whom the Software is
87
+ furnished to do so, subject to the following conditions:
88
+
89
+ The above copyright notice and this permission notice shall be included in all
90
+ copies or substantial portions of the Software.
91
+
92
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
93
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
94
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
95
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
96
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
97
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
98
+ SOFTWARE.
99
+ """
100
+
74
101
  __version__ = get_version()
75
102
 
76
103
  sm = StockManager.instance()
@@ -88,16 +115,20 @@ class iodog:
88
115
 
89
116
 
90
117
  if in_interactive_session():
118
+ hku_info("runing in interactive session")
91
119
  set_python_in_interactive(True)
92
120
 
93
121
 
94
122
  # 如果是在 jupyter 环境中运行,重定向C++ stdout/stderr输出至python
95
123
  if in_ipython_frontend():
96
124
  set_python_in_jupyter(True)
97
- hku_info("hikyuu version: {}", get_version_with_build())
125
+ hku_info("running in jupyter")
98
126
  iodog.open()
99
127
 
100
128
 
129
+ use_draw_engine('matplotlib')
130
+
131
+
101
132
  def hku_save(var, filename):
102
133
  """
103
134
  序列化,将hikyuu内建类型的变量(如Stock、TradeManager等)保存在指定的文件中,格式为XML。
@@ -121,6 +152,242 @@ def hku_load(filename):
121
152
  return out
122
153
 
123
154
 
155
+ def set_global_context(stk, query):
156
+ """
157
+ 设置全局的 K 线上下文
158
+
159
+ :param Stock stk: 指定的全局Stock
160
+ :param Query query: 指定的查询条件
161
+ """
162
+ global K, O, C, H, L, A, V
163
+ K = stk.get_kdata(query)
164
+ O.set_context(K)
165
+ C.set_context(K)
166
+ H.set_context(K)
167
+ L.set_context(K)
168
+ A.set_context(K)
169
+ V.set_context(K)
170
+
171
+
172
+ def get_global_context():
173
+ """
174
+ 获取当前的全局 K 线上下文
175
+
176
+ :rtype: KData
177
+ """
178
+ return C.getContext()
179
+
180
+
181
+ # 预定义block变量的只有load_hikyuu后,才会生效
182
+ blocka = None # 全部A股
183
+ zsbk_a = None # 指数板块A股
184
+ blocksh = None # 全部沪市
185
+ zsbk_sh = None # 指数板块上证
186
+ blocksz = None
187
+ zsbk_sz = None
188
+ blockbj = None
189
+ zsbk_bj = None
190
+ blockg = None
191
+ zsbk_cyb = None
192
+ blockstart = None
193
+ blockzxb = None
194
+ zsbk_zxb = None
195
+ zsbk_sh50 = None
196
+ zsbk_sh180 = None
197
+ zsbk_hs300 = None
198
+ zsbk_zz100 = None
199
+
200
+
201
+ def load_hikyuu(**kwargs):
202
+ """
203
+ 初始化加载 hikyuu 数据库,并初始化全局变量。
204
+
205
+ 示例:
206
+
207
+ # 仅预加载 sh000001 日线数据,关闭行情接收
208
+ options = {
209
+ "stock_list": ["sh000001"],
210
+ "ktype_list": ["day"],
211
+ "load_history_finance": False,
212
+ "load_weight": False,
213
+ "start_spot": False,
214
+ "spot_worker_num": 1,
215
+ }
216
+ load_hikyuu(**options)
217
+
218
+ 参数:
219
+ config_file (str): 配置文件路径,默认为 ~/.hikyuu/hikyuu.ini
220
+
221
+ stock_list (list): 指定加载的股票列表,默认为全部A股('all'), 如:['sh000001', 'sz399001']
222
+ ktype_list (list): 指定加载的K线类型列表,默认按配置文件设置加载. 如: ['day', 'week', 'month']
223
+ 支持的K线类型有:
224
+ 'day', 'week', 'month', 'quarter', 'halfyear', 'year', 'min', 'min5',
225
+ 'min15', 'min30', 'min60', 'hour2'
226
+ load_history_finance (boolean): 预加载历史财务数至内存,默认为 True
227
+ load_weight (boolean): 加载权息数据,默认为 True
228
+
229
+ start_spot (boolean): 启动行情接收,默认为 True
230
+ spot_worker_num (int): 行情接收数据处理线程数,默认为 1
231
+ """
232
+ if 'config_file' in kwargs:
233
+ config_file = kwargs['config_file']
234
+ if not os.path.exists(config_file):
235
+ hku_fatal("配置文件不存在: {}".format(config_file))
236
+ return
237
+ else:
238
+ from .data.hku_config_template import generate_default_config
239
+ config_file = os.path.expanduser('~') + "/.hikyuu/hikyuu.ini"
240
+ if not os.path.exists(config_file):
241
+ # 创建默认配置
242
+ hku_info("创建默认配置文件")
243
+ generate_default_config()
244
+
245
+ import configparser
246
+ ini = configparser.ConfigParser()
247
+ ini.read(config_file, encoding='utf-8')
248
+ hku_param = Parameter()
249
+ hku_param["tmpdir"] = ini.get('hikyuu', 'tmpdir')
250
+ hku_param["datadir"] = ini.get('hikyuu', 'datadir')
251
+ if ini.has_option('hikyuu', 'quotation_server'):
252
+ hku_param["quotation_server"] = ini['hikyuu']['quotation_server']
253
+
254
+ base_param = Parameter()
255
+ base_info_config = ini.options('baseinfo')
256
+ for p in base_info_config:
257
+ base_param[p] = ini.get('baseinfo', p)
258
+
259
+ block_param = Parameter()
260
+ block_config = ini.options('block')
261
+ for p in block_config:
262
+ block_param[p] = ini.get('block', p)
263
+
264
+ preload_param = Parameter()
265
+ preload_config = ini.options('preload')
266
+ for p in preload_config:
267
+ if p in ('day', 'week', 'month', 'quarter', 'halfyear', 'year', 'min', 'min5', 'min15', 'min30', 'min60', 'hour2'):
268
+ preload_param[p] = ini.getboolean('preload', p)
269
+ else:
270
+ preload_param[p] = ini.getint('preload', p)
271
+
272
+ kdata_param = Parameter()
273
+ kdata_config = ini.options('kdata')
274
+ for p in kdata_config:
275
+ if p == "convert":
276
+ kdata_param[p] = ini.getboolean('kdata', p)
277
+ continue
278
+ kdata_param[p] = ini.get('kdata', p)
279
+
280
+ context = StrategyContext(["all"])
281
+ # 兼容原有通过环境变量设置加载选项的方式(优先级低)
282
+ if 'HKU_STOCK_LIST' in os.environ:
283
+ context.stock_list = os.environ['HKU_STOCK_LIST'].split(";")
284
+ if 'HKU_KTYPE_LIST' in os.environ:
285
+ context.ktype_list = os.environ['HKU_KTYPE_LIST'].split(";")
286
+ if 'HKU_LOAD_HISTORY_FINANCE' in os.environ:
287
+ load_str = os.environ['HKU_LOAD_HISTORY_FINANCE'].upper()
288
+ load_finance = load_str in ("1", "TRUE")
289
+ hku_param.set("load_history_finance", load_finance)
290
+ if 'HKU_LOAD_STOCK_WEIGHT' in os.environ:
291
+ load_str = os.environ['HKU_LOAD_STOCK_WEIGHT'].upper()
292
+ load_stk_weight = load_str in ("1", "TRUE")
293
+ hku_param.set("load_stock_weight", load_stk_weight)
294
+
295
+ # 优先使用传入参数作为加载上下文
296
+ if 'stock_list' in kwargs:
297
+ context.stock_list = kwargs['stock_list']
298
+ if 'ktype_list' in os.environ:
299
+ context.ktype_list = kwargs['ktype_list']
300
+ if 'load_history_finance' in kwargs:
301
+ hku_param.set("load_history_finance", kwargs['load_history_finance'])
302
+ if 'load_weight' in kwargs:
303
+ hku_param.set("load_stock_weight", kwargs['load_weight'])
304
+
305
+ sm.init(base_param, block_param, kdata_param, preload_param, hku_param, context)
306
+
307
+ start_spot = False
308
+ if 'HKU_START_SPOT' in os.environ:
309
+ spot_str = os.environ['HKU_START_SPOT'].upper()
310
+ start_spot = spot_str in ('1', 'TRUE')
311
+ spot_worker_num = 1
312
+ if 'HKU_SPOT_WORKER_NUM' in os.environ:
313
+ spot_worker_num = int(os.environ['HKU_SPOT_WORKER_NUM'])
314
+
315
+ if 'start_spot' in kwargs:
316
+ start_spot = kwargs['start_spot']
317
+ if 'spot_worker_num' in kwargs:
318
+ spot_worker_num = kwargs['spot_worker_num']
319
+
320
+ # 启动行情接收代理
321
+ if start_spot:
322
+ start_spot_agent(False, spot_worker_num)
323
+
324
+ global blocka
325
+ global zsbk_a
326
+ global blocksh
327
+ global zsbk_sh
328
+ global blocksz
329
+ global zsbk_sz
330
+ global blockbj
331
+ global zsbk_bj
332
+ global blockg
333
+ global zsbk_cyb
334
+ global blockstart
335
+ global blockzxb
336
+ global zsbk_zxb
337
+ global zsbk_sh50
338
+ global zsbk_sh180
339
+ global zsbk_hs300
340
+ global zsbk_zz100
341
+
342
+ blocka = Block("A", "ALL")
343
+ for s in sm:
344
+ if s.type in (constant.STOCKTYPE_A, constant.STOCKTYPE_A_BJ):
345
+ blocka.add(s)
346
+ zsbk_a = blocka
347
+
348
+ blocksh = Block("A", "SH")
349
+ for s in blocka:
350
+ if s.market == "SH":
351
+ blocksh.add(s)
352
+ zsbk_sh = blocksh
353
+
354
+ blocksz = Block("A", "SZ")
355
+ for s in blocka:
356
+ if s.market == "SZ":
357
+ blocksz.add(s)
358
+ zsbk_sz = blocksz
359
+
360
+ blockbj = Block("A", "BJ")
361
+ for s in blocka:
362
+ if s.market == "BJ":
363
+ blockbj.add(s)
364
+ zsbk_bj = blockbj
365
+
366
+ blockg = Block("G", "创业板")
367
+ for s in sm:
368
+ if s.type == constant.STOCKTYPE_GEM:
369
+ blockg.add(s)
370
+ zsbk_cyb = blockg
371
+
372
+ blockstart = Block("START", "科创板")
373
+ for s in sm:
374
+ if s.type == constant.STOCKTYPE_START:
375
+ blockstart.add(s)
376
+
377
+ blockzxb = Block("A", "中小板")
378
+ for s in blocksz:
379
+ if s.code[:3] == "002":
380
+ blockzxb.add(s)
381
+ zsbk_zxb = blockzxb
382
+
383
+ zsbk_sh50 = sm.get_block("指数板块", "上证50")
384
+ zsbk_sh180 = sm.get_block("指数板块", "上证180")
385
+ zsbk_hs300 = sm.get_block("指数板块", "沪深300")
386
+ zsbk_zz100 = sm.get_block("指数板块", "中证100")
387
+
388
+ set_global_context(sm['sh000001'], Query(-150))
389
+
390
+
124
391
  # ==============================================================================
125
392
  #
126
393
  # 设置关键类型简称
@@ -135,3 +402,168 @@ V = VOL()
135
402
  D = Datetime
136
403
  K = None
137
404
  Q = Query
405
+
406
+ # ==============================================================================
407
+ #
408
+ # 粗略的选股函数
409
+ #
410
+ # ==============================================================================
411
+
412
+
413
+ def select(cond, start=Datetime(201801010000), end=Datetime.now(), print_out=True):
414
+ """
415
+ 示例:
416
+ #选出涨停股
417
+ C = CLOSE()
418
+ x = select(C / REF(C, 1) - 1 >= 0.0995)
419
+
420
+ :param Indicator cond: 条件指标
421
+ :param Datetime start: 起始日期
422
+ :param Datetime end: 结束日期
423
+ :param bool print_out: 打印选中的股票
424
+ :rtype: 选中的股票列表
425
+ """
426
+ q = Query(start, end)
427
+ d = sm.get_trading_calendar(q, 'SH')
428
+ if len(d) == 0:
429
+ return
430
+
431
+ result = []
432
+ for s in blocka:
433
+ if not s.valid:
434
+ continue
435
+
436
+ k = s.get_kdata(q)
437
+ if len(k) == 0 or k[-1].datetime != d[-1]:
438
+ continue
439
+
440
+ cond.set_context(k)
441
+ if len(cond) > 0 and not isnan(cond[-1]) and cond[-1] > 0:
442
+ result.append(s)
443
+ if print_out:
444
+ print(d[-1], s)
445
+
446
+ return result
447
+
448
+
449
+ def select2(inds, start=Datetime(201801010000), end=Datetime.now(), stks=None):
450
+ """导出最后时刻指定证券的所有指定指标值
451
+
452
+ 如:
453
+ select2([CLOSE(), VOLUME()], stks=blocka)
454
+
455
+ 返回一个DataFrame, 列名是指标名称, 行是证券代码和证券名称:
456
+
457
+ 证券代码 证券名称 CLOSE VOLUME
458
+ SH600000 浦发银行 14.09 1000
459
+ SH600001 中国平安 13.09 2000
460
+ SZ000001 平安银行 13.09 3000
461
+ ...
462
+
463
+ :param Indicator inds: 指标列表
464
+ :param Datetime start: 起始日期
465
+ :param Datetime end: 结束日期(不包括该日期)
466
+ :param list stks: 指定的证券列表
467
+ :rtype: pandas.DataFrame
468
+ """
469
+ q = Query(start, end)
470
+ d = sm.get_trading_calendar(q, 'SH')
471
+ if len(d) == 0:
472
+ return
473
+
474
+ if stks is None:
475
+ stks = sm
476
+
477
+ ind_cols = {'证券代码': [], '证券名称': []}
478
+ for ind in inds:
479
+ ind_cols[ind.name] = []
480
+
481
+ for s in stks:
482
+ if not s.valid:
483
+ continue
484
+
485
+ k = s.get_kdata(q)
486
+ if len(k) == 0 or k[-1].datetime != d[-1]:
487
+ continue
488
+
489
+ ind_cols['证券代码'].append(s.market_code)
490
+ ind_cols['证券名称'].append(s.name)
491
+ for ind in inds:
492
+ x = ind(k)
493
+ ind_cols[ind.name].append(x[-1])
494
+
495
+ df = pd.DataFrame(ind_cols)
496
+ return df
497
+
498
+
499
+ # ==============================================================================
500
+ #
501
+ # 增加临时的实时数据更新函数 realtime_update
502
+ #
503
+ # ==============================================================================
504
+
505
+
506
+ def realtime_update_inner(source='qq', stk_list=None):
507
+ if stk_list is None:
508
+ if source == 'qmt':
509
+ stk_list = [s for s in sm if s.valid and s.type in (
510
+ constant.STOCKTYPE_A, constant.STOCKTYPE_INDEX, constant.STOCKTYPE_ETF,
511
+ constant.STOCKTYPE_GEM, constant.STOCKTYPE_START, constant.STOCKTYPE_A_BJ)]
512
+ else:
513
+ stk_list = [
514
+ stk.market_code.lower() for stk in sm if stk.valid and stk.type in
515
+ (constant.STOCKTYPE_A, constant.STOCKTYPE_INDEX, constant.STOCKTYPE_GEM,
516
+ constant.STOCKTYPE_START, constant.STOCKTYPE_A_BJ)
517
+ ]
518
+
519
+ if source == 'qq':
520
+ from hikyuu.fetcher.stock.zh_stock_a_sina_qq import get_spot
521
+ stk_list = [s.market_code.lower() for s in stk_list]
522
+ records = get_spot(stk_list, 'qq')
523
+ elif source == 'qmt':
524
+ from hikyuu.fetcher.stock.zh_stock_a_qmt import get_spot
525
+ records = get_spot(stk_list)
526
+ else:
527
+ hku_error(f'Not support website source: {source}!')
528
+ return
529
+
530
+ for r in records:
531
+ stk = sm[f'{r["market"]}{r["code"]}']
532
+ if stk.is_null():
533
+ continue
534
+ k = KRecord()
535
+ k.datetime = Datetime(r['datetime']).start_of_day()
536
+ k.open = r['open']
537
+ k.high = r['high']
538
+ k.low = r['low']
539
+ k.close = r['close']
540
+ k.volume = r['volume']
541
+ k.amount = r['amount']
542
+ stk.realtime_update(k)
543
+
544
+
545
+ def realtime_update_wrap():
546
+ pre_update_time = None
547
+
548
+ def realtime_update_closure(source='qq', delta=60, stk_list=None):
549
+ """
550
+ 更新实时日线数据
551
+ :param str source: 数据源 ('qq' | 'qmt')
552
+ :param int delta: 最小更新间隔时间, 防止更新过于频繁
553
+ :param sequence stk_list: 待更新的stock列表, 如为 None 则更新全部
554
+ """
555
+ from datetime import timedelta, datetime
556
+ nonlocal pre_update_time
557
+ now_update_time = datetime.now()
558
+ if (source == 'qmt') or (pre_update_time is None) or (now_update_time - pre_update_time) > timedelta(0, delta, 0):
559
+ realtime_update_inner(source, stk_list)
560
+ pre_update_time = datetime.now()
561
+ print(f"更新完毕!更新时间: {pre_update_time}")
562
+ else:
563
+ print(f"更新间隔小于 {str(delta)} 秒,未更新")
564
+ print(f"上次更新时间: {pre_update_time}")
565
+
566
+ return realtime_update_closure
567
+
568
+
569
+ realtime_update = realtime_update_wrap()