-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_modules.py
More file actions
404 lines (355 loc) · 18.9 KB
/
Copy pathgenerate_modules.py
File metadata and controls
404 lines (355 loc) · 18.9 KB
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Tushare模块生成器
基于分析结果生成最重要的缺失API模块
"""
import os
import json
import re
# 基于分析结果定义最重要的缺失API模块
PRIORITY_APIS = {
"stock_market": {
"stk_limit": {
"api_name": "stk_limit",
"description": "获取全市场每日涨跌停价格",
"interface_description": "接口:stk_limit描述:获取全市场(包含A/B股和基金)每日涨跌停价格,包括涨停价格,跌停价格等,每个交易日8点40左右更新当日股票涨跌停价格。限量:单次最多提取5800条记录,可循环调取,总量不限制积分:用户积2000积分可调取,单位分钟有流控,积分越高流量越大",
"url": "https://tushare.pro/document/2?doc_id=183",
"request_params": [
{"name": "ts_code", "type": "string", "required": False, "description": "TS股票代码"},
{"name": "trade_date", "type": "string", "required": False, "description": "交易日期"},
{"name": "start_date", "type": "string", "required": False, "description": "开始日期"},
{"name": "end_date", "type": "string", "required": False, "description": "结束日期"}
],
"response_fields": [
{"name": "ts_code", "type": "string", "description": "TS股票代码"},
{"name": "trade_date", "type": "string", "description": "交易日期"},
{"name": "up_limit", "type": "number", "description": "涨停价"},
{"name": "down_limit", "type": "number", "description": "跌停价"}
]
},
"suspend_d": {
"api_name": "suspend_d",
"description": "获取股票每日停复牌信息",
"interface_description": "接口:suspend_d更新时间:不定期描述:按日期方式获取股票每日停复牌信息",
"url": "https://tushare.pro/document/2?doc_id=214",
"request_params": [
{"name": "ts_code", "type": "string", "required": False, "description": "TS股票代码"},
{"name": "suspend_date", "type": "string", "required": False, "description": "停牌日期"},
{"name": "resume_date", "type": "string", "required": False, "description": "复牌日期"}
],
"response_fields": [
{"name": "ts_code", "type": "string", "description": "TS股票代码"},
{"name": "suspend_date", "type": "string", "description": "停牌日期"},
{"name": "resume_date", "type": "string", "description": "复牌日期"},
{"name": "ann_date", "type": "string", "description": "公告日期"},
{"name": "suspend_reason", "type": "string", "description": "停牌原因"},
{"name": "reason_type", "type": "string", "description": "停牌原因类别"}
]
}
},
"stock_special": {
"top_list": {
"api_name": "top_list",
"description": "获取龙虎榜每日明细",
"interface_description": "接口:top_list描述:龙虎榜每日交易明细数据历史: 2005年至今限量:单次请求返回最大10000行数据,可通过参数循环获取全部历史积分:用户需要至少2000积分才可以调取",
"url": "https://tushare.pro/document/2?doc_id=106",
"request_params": [
{"name": "ts_code", "type": "string", "required": False, "description": "TS股票代码"},
{"name": "trade_date", "type": "string", "required": False, "description": "交易日期"},
{"name": "start_date", "type": "string", "required": False, "description": "开始日期"},
{"name": "end_date", "type": "string", "required": False, "description": "结束日期"}
],
"response_fields": [
{"name": "ts_code", "type": "string", "description": "TS股票代码"},
{"name": "trade_date", "type": "string", "description": "交易日期"},
{"name": "name", "type": "string", "description": "名称"},
{"name": "close", "type": "number", "description": "收盘价"},
{"name": "pct_chg", "type": "number", "description": "涨跌幅"},
{"name": "turnover_rate", "type": "number", "description": "换手率"},
{"name": "amount", "type": "number", "description": "总成交额"},
{"name": "l_sell", "type": "number", "description": "龙虎榜卖出额"},
{"name": "l_buy", "type": "number", "description": "龙虎榜买入额"},
{"name": "l_amount", "type": "number", "description": "龙虎榜成交额"},
{"name": "net_amount", "type": "number", "description": "龙虎榜净买入额"},
{"name": "net_rate", "type": "number", "description": "龙虎榜净买额占比"},
{"name": "amount_rate", "type": "number", "description": "龙虎榜成交额占比"},
{"name": "float_values", "type": "number", "description": "当日流通市值"}
]
},
"top_inst": {
"api_name": "top_inst",
"description": "获取龙虎榜机构明细",
"interface_description": "接口:top_inst描述:龙虎榜机构成交明细限量:单次请求最大返回10000行数据,可根据参数循环获取全部历史积分:用户需要至少2000积分才可以调取",
"url": "https://tushare.pro/document/2?doc_id=107",
"request_params": [
{"name": "ts_code", "type": "string", "required": False, "description": "TS股票代码"},
{"name": "trade_date", "type": "string", "required": False, "description": "交易日期"},
{"name": "start_date", "type": "string", "required": False, "description": "开始日期"},
{"name": "end_date", "type": "string", "required": False, "description": "结束日期"}
],
"response_fields": [
{"name": "ts_code", "type": "string", "description": "TS股票代码"},
{"name": "trade_date", "type": "string", "description": "交易日期"},
{"name": "exalter", "type": "string", "description": "营业部名称"},
{"name": "buy", "type": "number", "description": "买入额(万)"},
{"name": "buy_rate", "type": "number", "description": "买入占总成交比例"},
{"name": "sell", "type": "number", "description": "卖出额(万)"},
{"name": "sell_rate", "type": "number", "description": "卖出占总成交比例"},
{"name": "net_buy", "type": "number", "description": "净成交额(万)"}
]
}
},
"stock_financial": {
"fina_audit": {
"api_name": "fina_audit",
"description": "获取财务审计意见",
"interface_description": "接口:fina_audit描述:获取上市公司定期财务审计意见数据权限:用户需要至少500积分才可以调取",
"url": "https://tushare.pro/document/2?doc_id=80",
"request_params": [
{"name": "ts_code", "type": "string", "required": False, "description": "TS股票代码"},
{"name": "ann_date", "type": "string", "required": False, "description": "公告日期"},
{"name": "start_date", "type": "string", "required": False, "description": "公告开始日期"},
{"name": "end_date", "type": "string", "required": False, "description": "公告结束日期"},
{"name": "period", "type": "string", "required": False, "description": "报告期"}
],
"response_fields": [
{"name": "ts_code", "type": "string", "description": "TS股票代码"},
{"name": "ann_date", "type": "string", "description": "公告日期"},
{"name": "end_date", "type": "string", "description": "报告期"},
{"name": "audit_result", "type": "string", "description": "审计结果"},
{"name": "audit_fees", "type": "number", "description": "审计总费用(万元)"},
{"name": "audit_agency", "type": "string", "description": "会计事务所"},
{"name": "audit_sign", "type": "string", "description": "签字会计师"}
]
},
"dividend": {
"api_name": "dividend",
"description": "获取分红送股数据",
"interface_description": "接口:dividend描述:分红送股数据权限:用户需要至少2000积分才可以调取",
"url": "https://tushare.pro/document/2?doc_id=103",
"request_params": [
{"name": "ts_code", "type": "string", "required": False, "description": "TS股票代码"},
{"name": "ann_date", "type": "string", "required": False, "description": "公告日期"},
{"name": "record_date", "type": "string", "required": False, "description": "股权登记日"},
{"name": "ex_date", "type": "string", "required": False, "description": "除权除息日"}
],
"response_fields": [
{"name": "ts_code", "type": "string", "description": "TS股票代码"},
{"name": "end_date", "type": "string", "description": "分红年度"},
{"name": "ann_date", "type": "string", "description": "预案公告日"},
{"name": "div_proc", "type": "string", "description": "实施进度"},
{"name": "stk_div", "type": "number", "description": "每股送转"},
{"name": "stk_bo_rate", "type": "number", "description": "每股送股比例"},
{"name": "stk_co_rate", "type": "number", "description": "每股转增比例"},
{"name": "cash_div", "type": "number", "description": "每股分红(税后)"},
{"name": "cash_div_tax", "type": "number", "description": "每股分红(税前)"},
{"name": "record_date", "type": "string", "description": "股权登记日"},
{"name": "ex_date", "type": "string", "description": "除权除息日"},
{"name": "pay_date", "type": "string", "description": "派息日"}
]
}
},
"stock_reference": {
"margin": {
"api_name": "margin",
"description": "获取融资融券每日交易汇总数据",
"interface_description": "接口:margin描述:获取融资融券每日交易汇总数据限量:单次请求最大返回4000行数据,可根据日期循环权限:2000积分可获得本接口权限",
"url": "https://tushare.pro/document/2?doc_id=58",
"request_params": [
{"name": "trade_date", "type": "string", "required": False, "description": "交易日期"},
{"name": "exchange_id", "type": "string", "required": False, "description": "交易所代码"}
],
"response_fields": [
{"name": "trade_date", "type": "string", "description": "交易日期"},
{"name": "exchange_id", "type": "string", "description": "交易所代码"},
{"name": "rzye", "type": "number", "description": "融资余额(元)"},
{"name": "rzmre", "type": "number", "description": "融资买入额(元)"},
{"name": "rzche", "type": "number", "description": "融资偿还额(元)"},
{"name": "rqye", "type": "number", "description": "融券余额(元)"},
{"name": "rqmcl", "type": "number", "description": "融券卖出量(股)"},
{"name": "rzrqye", "type": "number", "description": "融资融券余额(元)"}
]
}
}
}
def to_camel_case(snake_str):
"""将snake_case转换为camelCase"""
components = snake_str.split('_')
return components[0] + ''.join(x.capitalize() for x in components[1:])
def to_pascal_case(snake_str):
"""将snake_case转换为PascalCase"""
return ''.join(x.capitalize() for x in snake_str.split('_'))
def generate_interface_file(api_name, api_config):
"""生成接口文件"""
# 生成请求参数接口
request_interface = f"""/**
* {api_config['interface_description']}
* {api_config['url']}
*/
/**
* {api_config['description']}请求参数
*/
export interface {to_pascal_case(api_name)}RequestParams {{"""
for param in api_config['request_params']:
request_interface += f"""
/** {param['description']} */
{param['name']}?: {param['type']};"""
request_interface += """
}
/**
* """ + api_config['description'] + """返回参数
*/
export interface """ + to_pascal_case(api_name) + """Response {"""
for field in api_config['response_fields']:
request_interface += f"""
/** {field['description']} */
{field['name']}: {field['type']};"""
request_interface += """
}"""
return request_interface
def generate_const_file(api_name, api_config):
"""生成常量文件"""
const_content = f"""import {{ isValidDate, isValidTsCode }} from '../../../../base/validate';
import {{ RequestParamSpec }} from '../../../../interface/requestType';
/**
* {api_config['interface_description']}
* {api_config['url']}
*/
/**
* {api_config['description']}返回参数规范
*/
export const {to_camel_case(api_name)}RequestParamsSpecs: RequestParamSpec[] = ["""
for param in api_config['request_params']:
validator = ""
if 'date' in param['name'] or param['name'] == 'period':
validator = ",\n validator: isValidDate"
elif param['name'] == 'ts_code':
validator = ",\n validator: isValidTsCode"
const_content += f"""
{{
name: '{param['name']}',
type: '{param['type']}',
required: {str(param['required']).lower()},
description: '{param['description']}'{validator}
}},"""
const_content += """
]
/**
* """ + api_config['description'] + """返回参数规范
*/
export const """ + to_camel_case(api_name) + """ResponseSpecs: RequestParamSpec[] = ["""
for field in api_config['response_fields']:
validator = ""
if 'date' in field['name'] or field['name'] == 'period':
validator = ",\n validator: isValidDate"
elif field['name'] == 'ts_code':
validator = ",\n validator: isValidTsCode"
const_content += f"""
{{
name: '{field['name']}',
type: '{field['type']}',
required: false,
description: '{field['description']}'{validator}
}},"""
const_content += """
]"""
return const_content
def generate_api_file(api_name, api_config):
"""生成API文件"""
pascal_name = to_pascal_case(api_name)
camel_name = to_camel_case(api_name)
# 生成必填条件检查逻辑
required_fields = [p['name'] for p in api_config['request_params'] if p['required']]
condition_description = ",".join([p['description'] for p in api_config['request_params']])
api_content = f"""import {{ {pascal_name}RequestParams, {pascal_name}Response }} from './{camel_name}Interface';
import {{ getHttpClient }} from '../../../../base/http';
import {{ validateParams }} from '../../../../base/validate';
import {{ {camel_name}ResponseSpecs, {camel_name}RequestParamsSpecs }} from './{camel_name}Const';
const apiName = '{api_config['api_name']}';
/**
* {api_config['description']}
* @param params 请求参数
* @returns Promise<{pascal_name}ResponseData[]>
*/
export async function get{pascal_name}Api(token: string, params: {pascal_name}RequestParams): Promise<{pascal_name}Response[]> {{
// 验证参数
validateParams<{pascal_name}RequestParams>(params, {camel_name}RequestParamsSpecs);
// 确保至少提供了一个查询条件
if (!params || (Object.values(params).every(it => !it))) {{
throw new Error('至少需要提供一个查询条件:{condition_description}');
}}
// 发送请求
const httpClient = getHttpClient(token);
const fields = {camel_name}ResponseSpecs.map((it) => it.name).join(',');
const numFields = {camel_name}ResponseSpecs.filter((it) => it.type === 'number').map((it) => it.name);
const response = await httpClient.post<{{
fields: string[];
items: any[][];
}}>(apiName, params, fields);
// 转换响应数据格式
return response.items.map((item) => {{
const data: any = {{}};
response.fields.forEach((field, index) => {{
// 数值类型转换
if (numFields.includes(field)) {{
data[field] = parseFloat(item[index]);
}} else {{
data[field] = item[index];
}}
}});
return data as {pascal_name}Response;
}});
}}
"""
return api_content
def generate_index_file(api_name):
"""生成index文件"""
camel_name = to_camel_case(api_name)
return f"""// {camel_name} API
export * from './{camel_name}Api';
export * from './{camel_name}Const';
export * from './{camel_name}Interface';
"""
def generate_module(category, api_name, api_config):
"""生成完整的模块"""
camel_name = to_camel_case(api_name)
# 确定模块路径
if category == "stock_market":
base_path = "/Users/mac/work/github/zhao-core/tushare/packages/tushare-core/src/api/stock/market"
elif category == "stock_special":
base_path = "/Users/mac/work/github/zhao-core/tushare/packages/tushare-core/src/api/stock/special"
elif category == "stock_finance":
base_path = "/Users/mac/work/github/zhao-core/tushare/packages/tushare-core/src/api/stock/financial"
else:
base_path = "/Users/mac/work/github/zhao-core/tushare/packages/tushare-core/src/api/stock/reference"
module_path = os.path.join(base_path, camel_name)
# 创建模块目录
os.makedirs(module_path, exist_ok=True)
# 生成文件
files = {
f"{camel_name}Interface.ts": generate_interface_file(api_name, api_config),
f"{camel_name}Const.ts": generate_const_file(api_name, api_config),
f"{camel_name}Api.ts": generate_api_file(api_name, api_config),
"index.ts": generate_index_file(api_name)
}
for filename, content in files.items():
file_path = os.path.join(module_path, filename)
with open(file_path, 'w', encoding='utf-8') as f:
f.write(content)
print(f"Generated: {file_path}")
def main():
print("=== Tushare模块生成器 ===\n")
for category, apis in PRIORITY_APIS.items():
print(f"生成 {category} 类别的模块:")
for api_name, api_config in apis.items():
print(f" 生成 {api_name} 模块...")
try:
generate_module(category, api_name, api_config)
print(f" ✓ {api_name} 模块生成成功")
except Exception as e:
print(f" ✗ {api_name} 模块生成失败: {e}")
print()
print("模块生成完成!")
if __name__ == "__main__":
main()