Spaces:
Sleeping
Sleeping
Download scripts/parse_tdx_day_file.py from zbgool/quant-engine: direct link, hf CLI and curl.
- Browser
- Download file 5.5 kB
-
https://huggingface.co/spaces/zbgool/quant-engine/resolve/main/scripts/parse_tdx_day_file.py
- Command line
-
hf download hf://spaces/zbgool/quant-engine/scripts/parse_tdx_day_file.py
-
curl -L -o parse_tdx_day_file.py https://huggingface.co/spaces/zbgool/quant-engine/resolve/main/scripts/parse_tdx_day_file.py
5.5 kB
| import os | |
| import re | |
| import struct | |
| import pandas as pd | |
| from datetime import datetime | |
| import concurrent.futures | |
| # A股代码正则:匹配沪深两市股票,排除债券、基金、指数、B股等 | |
| # 沪市:600/601/603/605(主板)、688/689(科创板) | |
| # 深市:000/001(主板)、002/003(中小板)、300/301(创业板) | |
| A_STOCK_PATTERN = re.compile( | |
| r'^(sh(000|60[0135]|68[89]|880)|sz(399|00[0-3]|30[01]))\d{3}\.day$', re.IGNORECASE | |
| ) | |
| def is_a_stock(filename): | |
| """判断文件名是否为A股股票""" | |
| return bool(A_STOCK_PATTERN.match(filename)) | |
| def parse_tdx_day_file(filepath): | |
| """ | |
| 解析通达信本地 .day 二进制文件(核心逻辑保持不变) | |
| """ | |
| data_list = [] | |
| record_format = '<IIIIIfII' | |
| record_size = struct.calcsize(record_format) | |
| try: | |
| with open(filepath, 'rb') as f: | |
| while True: | |
| buffer = f.read(record_size) | |
| if not buffer or len(buffer) < record_size: | |
| break | |
| records = struct.unpack(record_format, buffer) | |
| row = { | |
| 'Date': pd.to_datetime(str(records[0]), format='%Y%m%d').strftime('%Y-%m-%d'), | |
| 'Open': records[1] / 100.0, | |
| 'High': records[2] / 100.0, | |
| 'Low': records[3] / 100.0, | |
| 'Close': records[4] / 100.0, | |
| 'Amount': records[5], | |
| 'Volume': records[6] | |
| } | |
| data_list.append(row) | |
| except Exception as e: | |
| return None, f"读取 {filepath} 失败: {e}" | |
| return pd.DataFrame(data_list), "success" | |
| def process_single_file(filepath, output_dir, current_date, trading_days=180): | |
| """ | |
| 处理单个文件的独立函数,专供多进程调用 | |
| """ | |
| filename = os.path.basename(filepath) | |
| stock_code = filename.replace('.day', '') # 例如: sh600000 | |
| # 4. 生成目标文件名 | |
| out_filename = f"{stock_code}_daily_{current_date}.csv" | |
| out_filepath = os.path.join(output_dir, out_filename) | |
| if os.path.exists(out_filepath): | |
| return f"已存在,跳过:{stock_code}" | |
| # 1. 解析二进制 | |
| df, status = parse_tdx_day_file(filepath) | |
| if df is None or df.empty: | |
| return f"跳过: {stock_code} (无数据或解析失败)" | |
| # 2. 截取最近 180 天 | |
| df_recent = df.tail(trading_days).copy() | |
| # 3. 规范列顺序 | |
| columns_order = ['Date', 'Open', 'Close', 'High', 'Low', 'Volume', 'Amount'] | |
| df_recent = df_recent[columns_order] | |
| # 5. 保存 CSV | |
| df_recent.to_csv(out_filepath, index=False, encoding='utf-8') | |
| return f"成功: {out_filename} ({len(df_recent)} 条)" | |
| def batch_convert_parallel(tdx_dirs, output_dir, trading_days=180): | |
| """ | |
| 多进程并行调度器 | |
| """ | |
| if not os.path.exists(output_dir): | |
| os.makedirs(output_dir) | |
| current_date = datetime.now().strftime('%Y%m%d') | |
| all_filepaths = [] | |
| # 收集所有需要处理的 .day 文件路径 | |
| for tdx_dir in tdx_dirs: | |
| if not os.path.exists(tdx_dir): | |
| print(f"警告: 目录不存在 {tdx_dir}") | |
| continue | |
| for filename in os.listdir(tdx_dir): | |
| if filename.endswith('.day') and is_a_stock(filename): | |
| all_filepaths.append(os.path.join(tdx_dir, filename)) | |
| total_files = len(all_filepaths) | |
| if total_files == 0: | |
| print("没有找到任何 .day 文件,请检查路径!") | |
| return | |
| print(f"共发现 {total_files} 个文件,准备启动多进程加速...") | |
| # 获取 CPU 核心数,留一个核心给系统,避免电脑卡死 | |
| max_workers = max(1, os.cpu_count() - 1) | |
| print(f"启用 {max_workers} 个进程进行并行转换...") | |
| # 启动进程池 | |
| success_count = 0 | |
| with concurrent.futures.ProcessPoolExecutor(max_workers=max_workers) as executor: | |
| # 将任务提交给进程池 | |
| # 列表推导式配合 executor.submit,传参给 process_single_file | |
| futures = [executor.submit(process_single_file, path, output_dir, current_date, trading_days) for path in all_filepaths] | |
| # 监控进度 | |
| for i, future in enumerate(concurrent.futures.as_completed(futures), 1): | |
| try: | |
| result_msg = future.result() | |
| if "成功" in result_msg: | |
| success_count += 1 | |
| # 每处理 500 个文件打印一次进度,避免控制台刷屏影响性能 | |
| if i % 500 == 0 or i == total_files: | |
| print(f"进度: {i}/{total_files} 已处理...") | |
| except Exception as e: | |
| print(f"任务执行异常: {e}") | |
| print(f"\n全部转换完成!成功导出 {success_count} 个 CSV 文件到 {output_dir}") | |
| if __name__ == "__main__": | |
| # 注意:在 Windows 下使用 multiprocessing,执行代码必须放在 if __name__ == "__main__": 保护块内 | |
| # === 请在这里修改你的本地路径 === | |
| TDX_SH_DIR = r"D:\\new_tdx2\\vipdoc\\sh\\lday" | |
| TDX_SZ_DIR = r"D:\\new_tdx2\\vipdoc\\sz\\lday" | |
| # 将沪深两市的目录放在一个列表里统一处理 | |
| directories_to_process = [TDX_SH_DIR, TDX_SZ_DIR] | |
| OUTPUT_DIRECTORY = r"./tdx_export_csv" | |
| # 启动并行转换 | |
| batch_convert_parallel(directories_to_process, OUTPUT_DIRECTORY, trading_days=1500) |