Spaces:
Sleeping

File size: 5,496 Bytes
c68f3b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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)