ezKit 1.9.2__tar.gz → 1.9.4__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: ezKit
3
- Version: 1.9.2
3
+ Version: 1.9.4
4
4
  Summary: Easy Kit
5
5
  Author: septvean
6
6
  Author-email: septvean@gmail.com
@@ -100,6 +100,15 @@ def latest_data(
100
100
  ) -> list | pd.DataFrame | None:
101
101
  """股票或板块的最新数据"""
102
102
 
103
+ # 热门板块
104
+ # https://www.cls.cn/hotPlate
105
+ # 行业板块
106
+ # https://x-quote.cls.cn/web_quote/plate/plate_list?rever=1&way=change&type=industry
107
+ # 概念板块
108
+ # https://x-quote.cls.cn/web_quote/plate/plate_list?rever=1&way=change&type=concept
109
+ # 地域板块
110
+ # https://x-quote.cls.cn/web_quote/plate/plate_list?rever=1&way=change&type=area
111
+
103
112
  # ----------------------------------------------------------------------------------------------
104
113
 
105
114
  # 判断参数类型
@@ -20,7 +20,7 @@ class Database():
20
20
 
21
21
  engine = create_engine('sqlite://')
22
22
 
23
- def __init__(self, target: str, **options):
23
+ def __init__(self, target: str | None = None, **options):
24
24
  """Initiation"""
25
25
  if isinstance(target, str) and utils.isTrue(target, str):
26
26
  if utils.isTrue(options, dict):
@@ -11,7 +11,7 @@ class Mongo():
11
11
 
12
12
  client = MongoClient()
13
13
 
14
- def __init__(self, target: str | dict):
14
+ def __init__(self, target: str | dict | None = None):
15
15
  """Initiation"""
16
16
  if isinstance(target, str) and utils.isTrue(target, str):
17
17
  self.client = MongoClient(target)
@@ -16,7 +16,7 @@ class Redis:
16
16
  # 这里修改以下参数: host, port, socket_timeout, socket_connect_timeout, charset
17
17
  redis = RedisClient.Redis()
18
18
 
19
- def __init__(self, target: str | dict):
19
+ def __init__(self, target: str | dict | None = None):
20
20
  """Initiation"""
21
21
  if isinstance(target, str) and utils.isTrue(target, str):
22
22
  self.redis = RedisClient.from_url(target)
@@ -0,0 +1,261 @@
1
+ """股票"""
2
+ import re
3
+ from copy import deepcopy
4
+
5
+ import akshare as ak
6
+ import numpy as np
7
+ import talib as ta
8
+ from loguru import logger
9
+ from pandas import DataFrame
10
+ from sqlalchemy.engine import Engine
11
+
12
+ from . import utils
13
+
14
+
15
+ def coderename(target: str | dict, restore: bool = False) -> str | dict | None:
16
+ """代码重命名"""
17
+
18
+ # 正向:
19
+ # coderename('000001') => 'sz000001'
20
+ # coderename({'code': '000001', 'name': '平安银行'}) => {'code': 'sz000001', 'name': '平安银行'}
21
+ # 反向:
22
+ # coderename('sz000001', restore=True) => '000001'
23
+ # coderename({'code': 'sz000001', 'name': '平安银行'}) => {'code': '000001', 'name': '平安银行'}
24
+
25
+ # 判断参数类型
26
+ match True:
27
+ case True if True not in [isinstance(target, str), isinstance(target, dict)]:
28
+ logger.error("argument type error: target")
29
+ return None
30
+ case _:
31
+ pass
32
+
33
+ # 判断参数数据
34
+ match True:
35
+ case True if True not in [utils.isTrue(target, str), utils.isTrue(target, dict)]:
36
+ logger.error("argument data error: data")
37
+ return None
38
+ case _:
39
+ pass
40
+
41
+ try:
42
+
43
+ # 初始化
44
+ code_object: dict = {}
45
+ code_name: str | dict = ""
46
+
47
+ # 判断 target 是 string 还是 dictionary
48
+ if isinstance(target, str) and utils.isTrue(target, str):
49
+ code_name = target
50
+ elif isinstance(target, dict) and utils.isTrue(target, dict):
51
+ code_object = deepcopy(target)
52
+ code_name = str(deepcopy(target["code"]))
53
+ else:
54
+ return None
55
+
56
+ # 是否还原
57
+ if utils.isTrue(restore, bool):
58
+ if len(code_name) == 8 and re.match(r"^(sz|sh)", code_name):
59
+ code_name = deepcopy(code_name[2:8])
60
+ else:
61
+ return None
62
+ else:
63
+ if code_name[0:2] == "00":
64
+ code_name = f"sz{code_name}"
65
+ elif code_name[0:2] == "60":
66
+ code_name = f"sh{code_name}"
67
+ else:
68
+ return None
69
+
70
+ # 返回结果
71
+ if utils.isTrue(target, str):
72
+ return code_name
73
+
74
+ if utils.isTrue(target, dict):
75
+ code_object["code"] = code_name
76
+ return code_object
77
+
78
+ return None
79
+
80
+ except Exception as e:
81
+ logger.exception(e)
82
+ return None
83
+
84
+
85
+ # --------------------------------------------------------------------------------------------------
86
+
87
+
88
+ def kdj_vector(df: DataFrame, cp: int = 9, sp1: int = 3, sp2: int = 3) -> DataFrame | None:
89
+ """KDJ计算器"""
90
+
91
+ # 计算周期:Calculation Period, 也可使用 Lookback Period 表示回溯周期, 指用于计算指标值的时间周期.
92
+ # 移动平均周期: Smoothing Period 或 Moving Average Period, 指对指标进行平滑处理时采用的周期.
93
+ # 同花顺默认参数: 9 3 3
94
+ # https://www.daimajiaoliu.com/daima/4ed4ffa26100400
95
+ # 说明: KDJ 指标的中文名称又叫随机指标, 融合了动量观念、强弱指标和移动平均线的一些优点, 能够比较迅速、快捷、直观地研判行情, 被广泛用于股市的中短期趋势分析.
96
+ # 有采用 ewm 使用 com=2 的, 但是如果使用 com=2 在默认值的情况下KDJ值是正确的.
97
+ # 但是非默认值, 比如调整参数, 尝试慢速 KDJ 时就不对了, 最终采用 alpha = 1/m 的情况, 对比同花顺数据, 是正确的.
98
+
99
+ # 判断参数类型
100
+ match True:
101
+ case True if not isinstance(df, DataFrame):
102
+ logger.error("argument type error: df")
103
+ return None
104
+ case _:
105
+ pass
106
+
107
+ try:
108
+ low_list = df['low'].rolling(cp).min()
109
+ high_list = df['high'].rolling(cp).max()
110
+ rsv = (df['close'] - low_list) / (high_list - low_list) * 100
111
+ df['K'] = rsv.ewm(alpha=1 / sp1, adjust=False).mean()
112
+ df['D'] = df['K'].ewm(alpha=1 / sp2, adjust=False).mean()
113
+ df['J'] = (3 * df['K']) - (2 * df['D'])
114
+ return df
115
+ except Exception as e:
116
+ logger.exception(e)
117
+ return None
118
+
119
+
120
+ # --------------------------------------------------------------------------------------------------
121
+
122
+
123
+ def data_vector(
124
+ df: DataFrame,
125
+ macd_options: tuple[int, int, int] = (12, 26, 9),
126
+ kdj_options: tuple[int, int, int] = (9, 3, 3)
127
+ ) -> DataFrame | None:
128
+ """数据运算"""
129
+
130
+ try:
131
+
132
+ # 数据为空
133
+ if isinstance(df, DataFrame) and df.empty:
134
+ return None
135
+
136
+ # ------------------------------------------------------------------------------------------
137
+
138
+ # 计算均线: 3,7日均线
139
+ # pylint: disable=E1101
140
+ # df['SMA03'] = ta.SMA(df['close'], timeperiod=3) # type: ignore
141
+ # df['SMA07'] = ta.SMA(df['close'], timeperiod=7) # type: ignore
142
+
143
+ # 3,7日均线金叉: 0 无, 1 金叉, 2 死叉
144
+ # df['SMA37_X'] = 0
145
+ # sma37_position = df['SMA03'] > df['SMA07']
146
+ # df.loc[sma37_position[(sma37_position is True) & (sma37_position.shift() is False)].index, 'SMA37_X'] = 1 # type: ignore
147
+ # df.loc[sma37_position[(sma37_position is False) & (sma37_position.shift() is True)].index, 'SMA37_X'] = 2 # type: ignore
148
+
149
+ # 计算均线: 20,25日均线
150
+ # df['SMA20'] = ta.SMA(df['close'], timeperiod=20) # type: ignore
151
+ # df['SMA25'] = ta.SMA(df['close'], timeperiod=25) # type: ignore
152
+
153
+ # 20,25日均线金叉: 0 无, 1 金叉, 2 死叉
154
+ # df['SMA225_X'] = 0
155
+ # sma225_position = df['SMA20'] > df['SMA25']
156
+ # df.loc[sma225_position[(sma225_position is True) & (sma225_position.shift() is False)].index, 'SMA225_X'] = 1 # type: ignore
157
+ # df.loc[sma225_position[(sma225_position is False) & (sma225_position.shift() is True)].index, 'SMA225_X'] = 2 # type: ignore
158
+
159
+ # ------------------------------------------------------------------------------------------
160
+
161
+ # 计算 MACD: 默认参数 12 26 9
162
+ macd_dif, macd_dea, macd_bar = ta.MACD(df['close'].values, fastperiod=macd_options[0], slowperiod=macd_options[1], signalperiod=macd_options[2]) # type: ignore
163
+ macd_dif[np.isnan(macd_dif)], macd_dea[np.isnan(macd_dea)], macd_bar[np.isnan(macd_bar)] = 0, 0, 0
164
+
165
+ # https://www.bilibili.com/read/cv10185856
166
+ df['MACD'] = 2 * (macd_dif - macd_dea)
167
+ df['MACD_DIF'] = macd_dif
168
+ df['MACD_DEA'] = macd_dea
169
+
170
+ # MACD 金叉死叉: 0 无, 1 金叉, 2 死叉
171
+ df['MACD_X'] = 0
172
+ macd_position = df['MACD_DIF'] > df['MACD_DEA']
173
+ df.loc[macd_position[(macd_position is True) & (macd_position.shift() is False)].index, 'MACD_X'] = 1 # type: ignore
174
+ df.loc[macd_position[(macd_position is False) & (macd_position.shift() is True)].index, 'MACD_X'] = 2 # type: ignore
175
+
176
+ # ------------------------------------------------------------------------------------------
177
+
178
+ # 计算 KDJ: : 默认参数 9 3 3
179
+ kdj_data = kdj_vector(df, kdj_options[0], kdj_options[1], kdj_options[2])
180
+
181
+ if kdj_data is not None:
182
+
183
+ # KDJ 数据
184
+ df['K'] = kdj_data['K'].values
185
+ df['D'] = kdj_data['D'].values
186
+ df['J'] = kdj_data['J'].values
187
+
188
+ # KDJ 金叉死叉: 0 无, 1 金叉, 2 死叉
189
+ df['KDJ_X'] = 0
190
+ kdj_position = df['J'] > df['D']
191
+ df.loc[kdj_position[(kdj_position is True) & (kdj_position.shift() is False)].index, 'KDJ_X'] = 1 # type: ignore
192
+ df.loc[kdj_position[(kdj_position is False) & (kdj_position.shift() is True)].index, 'KDJ_X'] = 2 # type: ignore
193
+
194
+ # ------------------------------------------------------------------------------------------
195
+
196
+ return df
197
+
198
+ except Exception as e:
199
+ logger.exception(e)
200
+ return None
201
+
202
+
203
+ # --------------------------------------------------------------------------------------------------
204
+
205
+
206
+ def get_code_name_from_akshare() -> DataFrame | None:
207
+ """获取股票代码和名称"""
208
+ info = "获取股票代码和名称"
209
+ try:
210
+ logger.info(f"{info} ......")
211
+ df: DataFrame = ak.stock_info_a_code_name()
212
+ if df.empty:
213
+ logger.error(f"{info} [失败]")
214
+ return None
215
+ # 排除 ST、证券和银行
216
+ # https://towardsdatascience.com/8-ways-to-filter-pandas-dataframes-d34ba585c1b8
217
+ df = df[df.code.str.contains("^00|^60") & ~df.name.str.contains("ST|证券|银行")]
218
+ logger.success(f"{info} [成功]")
219
+ return df
220
+ except Exception as e:
221
+ logger.error(f"{info} [失败]")
222
+ logger.exception(e)
223
+ return None
224
+
225
+
226
+ # --------------------------------------------------------------------------------------------------
227
+
228
+
229
+ def get_stock_data_from_akshare(code: str) -> DataFrame | None:
230
+ """从 akshare 获取数据"""
231
+ info = f"获取股票所有数据: {code}"
232
+ try:
233
+ logger.info(f"{info} ......")
234
+ df: DataFrame = ak.stock_zh_a_daily(symbol=code, adjust="qfq")
235
+ df = df.round({'turnover': 4})
236
+ logger.success(f"{info} [成功]")
237
+ return df[['date', 'open', 'close', 'high', 'low', 'volume', 'turnover']].copy()
238
+ except Exception as e:
239
+ logger.error(f"{info} [失败]")
240
+ logger.exception(e)
241
+ return None
242
+
243
+
244
+ # --------------------------------------------------------------------------------------------------
245
+
246
+
247
+ def save_data_to_database(engine: Engine, code: str) -> bool:
248
+ """保存股票数据到数据库"""
249
+ info: str = "保存股票数据到数据库"
250
+ try:
251
+ logger.info(f"{info} ......")
252
+ df: DataFrame | None = get_stock_data_from_akshare(code)
253
+ if df is None:
254
+ return False
255
+ df.to_sql(name=code, con=engine, if_exists="replace", index=False)
256
+ logger.success(f"{info} [成功]")
257
+ return True
258
+ except Exception as e:
259
+ logger.success(f"{info} [失败]")
260
+ logger.exception(e)
261
+ return False
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: ezKit
3
- Version: 1.9.2
3
+ Version: 1.9.4
4
4
  Summary: Easy Kit
5
5
  Author: septvean
6
6
  Author-email: septvean@gmail.com
@@ -3,7 +3,7 @@ from setuptools import find_packages, setup
3
3
 
4
4
  setup(
5
5
  name='ezKit',
6
- version='1.9.2',
6
+ version='1.9.4',
7
7
  author='septvean',
8
8
  author_email='septvean@gmail.com',
9
9
  description='Easy Kit',
@@ -1,113 +0,0 @@
1
- """股票"""
2
- import re
3
- from copy import deepcopy
4
-
5
- from loguru import logger
6
- from pandas import DataFrame
7
-
8
- from . import utils
9
-
10
-
11
- def coderename(target: str | dict, restore: bool = False) -> str | dict | None:
12
- """代码重命名"""
13
-
14
- # 正向:
15
- # coderename('000001') => 'sz000001'
16
- # coderename({'code': '000001', 'name': '平安银行'}) => {'code': 'sz000001', 'name': '平安银行'}
17
- # 反向:
18
- # coderename('sz000001', restore=True) => '000001'
19
- # coderename({'code': 'sz000001', 'name': '平安银行'}) => {'code': '000001', 'name': '平安银行'}
20
-
21
- # 判断参数类型
22
- match True:
23
- case True if True not in [isinstance(target, str), isinstance(target, dict)]:
24
- logger.error("argument type error: target")
25
- return None
26
- case _:
27
- pass
28
-
29
- # 判断参数数据
30
- match True:
31
- case True if True not in [utils.isTrue(target, str), utils.isTrue(target, dict)]:
32
- logger.error("argument data error: data")
33
- return None
34
- case _:
35
- pass
36
-
37
- try:
38
-
39
- # 初始化
40
- code_object: dict = {}
41
- code_name: str | dict = ""
42
-
43
- # 判断 target 是 string 还是 dictionary
44
- if isinstance(target, str) and utils.isTrue(target, str):
45
- code_name = target
46
- elif isinstance(target, dict) and utils.isTrue(target, dict):
47
- code_object = deepcopy(target)
48
- code_name = str(deepcopy(target["code"]))
49
- else:
50
- return None
51
-
52
- # 是否还原
53
- if utils.isTrue(restore, bool):
54
- if len(code_name) == 8 and re.match(r"^(sz|sh)", code_name):
55
- code_name = deepcopy(code_name[2:8])
56
- else:
57
- return None
58
- else:
59
- if code_name[0:2] == "00":
60
- code_name = f"sz{code_name}"
61
- elif code_name[0:2] == "60":
62
- code_name = f"sh{code_name}"
63
- else:
64
- return None
65
-
66
- # 返回结果
67
- if utils.isTrue(target, str):
68
- return code_name
69
-
70
- if utils.isTrue(target, dict):
71
- code_object["code"] = code_name
72
- return code_object
73
-
74
- return None
75
-
76
- except Exception as e:
77
- logger.exception(e)
78
- return None
79
-
80
-
81
- # --------------------------------------------------------------------------------------------------
82
-
83
-
84
- def kdj_vector(df: DataFrame, cp: int = 9, sp1: int = 3, sp2: int = 3) -> DataFrame | None:
85
- """KDJ计算器"""
86
-
87
- # 计算周期:Calculation Period, 也可使用 Lookback Period 表示回溯周期, 指用于计算指标值的时间周期.
88
- # 移动平均周期: Smoothing Period 或 Moving Average Period, 指对指标进行平滑处理时采用的周期.
89
- # 同花顺默认参数: 9 3 3
90
- # https://www.daimajiaoliu.com/daima/4ed4ffa26100400
91
- # 说明: KDJ 指标的中文名称又叫随机指标, 融合了动量观念、强弱指标和移动平均线的一些优点, 能够比较迅速、快捷、直观地研判行情, 被广泛用于股市的中短期趋势分析.
92
- # 有采用 ewm 使用 com=2 的, 但是如果使用 com=2 在默认值的情况下KDJ值是正确的.
93
- # 但是非默认值, 比如调整参数, 尝试慢速 KDJ 时就不对了, 最终采用 alpha = 1/m 的情况, 对比同花顺数据, 是正确的.
94
-
95
- # 判断参数类型
96
- match True:
97
- case True if not isinstance(df, DataFrame):
98
- logger.error("argument type error: df")
99
- return None
100
- case _:
101
- pass
102
-
103
- try:
104
- low_list = df['low'].rolling(cp).min()
105
- high_list = df['high'].rolling(cp).max()
106
- rsv = (df['close'] - low_list) / (high_list - low_list) * 100
107
- df['K'] = rsv.ewm(alpha=1 / sp1, adjust=False).mean()
108
- df['D'] = df['K'].ewm(alpha=1 / sp2, adjust=False).mean()
109
- df['J'] = (3 * df['K']) - (2 * df['D'])
110
- return df
111
- except Exception as e:
112
- logger.exception(e)
113
- return None
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes