Administrator
2025-05-28 d5aa41a4647fe47e72bb21f7dff6962cfe3906be
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
"""
大单成交数据解析器
"""
import os
import re
from multiprocessing import Pool
 
import pandas as pd
 
from utils import tool
 
 
class BigOrderDealParser:
 
    @classmethod
    def str_to_float(cls, s):
        try:
            # 移除单位并转换
            return round(float(s.split("@")[0]), 2)
        except:
            return float("nan")
 
    @classmethod
    def code_format(cls, s):
        try:
            code = "{0:0>6}".format(s)
            return code
        except:
            return ''
 
 
def __pre_process_transactions_detail(args):
    def first_last(group):
        """
            获取第一条数据与最后一条
            @param group:
            @return:
            """
        return pd.Series({
            'TotalAmount': group['TradeAmount'].sum(),
            'TotalVolume': group['TradeVolume'].sum(),
            'StartTime': group['TradeTime'].iloc[0],
            'StartPrice': group['TradePrice'].iloc[0],
            'EndTime': group['TradeTime'].iloc[-1],
            'EndPrice': group['TradePrice'].iloc[-1]
        })
 
    chunk_index, chunk_data = args[0]
    csv_path = args[1]
    df = chunk_data.copy()
    index = chunk_index + 1
    children_dir = csv_path.replace(".csv", "")
    if not os.path.exists(children_dir):
        os.makedirs(children_dir)
    child_path = os.path.join(children_dir, f"{index}.csv")
    if os.path.exists(child_path):
        return
    print(f"处理Transaction第{index}批次", os.getpid())
    df["TradePrice"] = df["TradePrice"].apply(BigOrderDealParser.str_to_float)
    df["SecurityID"] = df["SecurityID"].apply(BigOrderDealParser.code_format)
    df = df[df["SecurityID"].str.startswith(("30", "00", "60"), na=False)]
    # 计算成交金额
    df['TradeAmount'] = df['TradePrice'] * df['TradeVolume']
    df = df[df["TradeAmount"] > 0]
    # 判断是否为空
    # print(df.empty)
    # 按SecurityID和BuyNo分组
    grouped = df.groupby(['SecurityID', 'BuyNo'])
    # 应用聚合函数
    chunk_result = grouped.apply(first_last)
    if not df.empty:
        chunk_result = chunk_result.reset_index()
    chunk_result.to_csv(child_path, index=False)
 
 
def pre_process_transactions(csv_path, process_count=4):
    chunk_size = 200000
    # 创建DataFrame
    chunks = pd.read_csv(csv_path, chunksize=chunk_size)
    indexed_data = list(enumerate(chunks))
    args = [(x, csv_path) for x in indexed_data]
    # 新写法
    with Pool(processes=process_count) as pool:
        pool.map(__pre_process_transactions_detail, args)
 
 
def __pre_process_ngtsticks(args):
    def first_last(group):
        return pd.Series({
            'TotalAmount': group['TradeMoney'].sum(),
            'TotalVolume': group['Volume'].sum(),
            'StartTime': group['TickTime'].iloc[0],
            'StartPrice': group['Price'].iloc[0],
            'EndTime': group['TickTime'].iloc[-1],
            'EndPrice': group['Price'].iloc[-1]
        })
 
    chunk_index, chunk_data = args[0]
    csv_path = args[1]
 
    df = chunk_data.copy()
    index = chunk_index + 1
    children_dir = csv_path.replace(".csv", "")
    if not os.path.exists(children_dir):
        os.makedirs(children_dir)
    child_path = os.path.join(children_dir, f"{index}.csv")
    if os.path.exists(child_path):
        return
    print(f"处理NGTSTick第{index}批次")
    df = df[df["TickType"] == 'T']
    df["Price"] = df["Price"].apply(BigOrderDealParser.str_to_float)
    df["SecurityID"] = df["SecurityID"].apply(BigOrderDealParser.code_format)
    df = df[df["SecurityID"].str.startswith(("30", "00", "60"), na=False)]
    # 计算成交金额
    df['TradeMoney'] = df["TradeMoney"].apply(BigOrderDealParser.str_to_float)
 
    # 按SecurityID和BuyNo分组
    grouped = df.groupby(['SecurityID', 'BuyNo'])
    # 应用聚合函数
    chunk_result = grouped.apply(first_last)
    if not df.empty:
        chunk_result = chunk_result.reset_index()
    chunk_result.to_csv(child_path, index=False)
 
 
def pre_process_ngtsticks(csv_path, process_count=4):
    chunk_size = 200000
    # 创建DataFrame
    chunks = pd.read_csv(csv_path, chunksize=chunk_size)
    indexed_data = list(enumerate(chunks))
    args = [(x, csv_path) for x in indexed_data]
    # 新写法
    with Pool(processes=process_count) as pool:
        pool.map(__pre_process_ngtsticks, args)
 
 
def __concat_pre_datas(dir_path):
    """
    拼接数据
    @param dir_path:
    @return:
    """
    combined_path = os.path.join(dir_path, 'combined.csv')
    if os.path.exists(combined_path):
        print("合并的目标文件已存在")
        return
    file_list = os.listdir(dir_path)
    file_list.sort(key=lambda x: int(re.findall(r'\d+', x)[0]))
    df_list = []
    for file in file_list:
        df = pd.read_csv(os.path.join(dir_path, file))
        if df.empty:
            continue
        df["SecurityID"] = df["SecurityID"].apply(BigOrderDealParser.code_format)
        df_list.append(df)
    print("准备合并的文件数量:", len(df_list))
 
    combined_df = pd.concat(df_list, ignore_index=True)
 
    print("合并完成,准备写入文件!")
    # 保存结果
    combined_df.to_csv(combined_path, index=False)
    print("写入文件完成!")
 
 
def concat_pre_transactions(dir_path):
    __concat_pre_datas(dir_path)
 
 
def concat_pre_ngtsticks(dir_path):
    __concat_pre_datas(dir_path)
 
 
def process_combined_transaction(dir_path):
    """
    处理拼接起来的数据
    @param dir_path:
    @return:
    """
    combined_path = os.path.join(dir_path, 'combined.csv')
    if not os.path.exists(combined_path):
        print("拼接数据不存在")
        return
    df = pd.read_csv(combined_path)
    df_copy = df.copy()
    grouped = df_copy.groupby(["SecurityID"])
    # 应用聚合函数
    chunk_result = grouped.apply(pd.Series({}))
    # chunk_result["SecurityID"] = chunk_result["SecurityID"].apply(BigOrderDealParser.code_format)
    print(chunk_result.to_string(
        index=False,  # 不显示索引
        justify='left',  # 左对齐
        float_format='%.3f'  # 浮点数格式
    ))
 
 
__combined_df_cache = {}
 
 
def extract_big_order_of_all(dir_path):
    combined_path = os.path.join(dir_path, 'combined.csv')
    if not os.path.exists(combined_path):
        print("拼接数据不存在")
        return
    codes = extract_big_order_codes(dir_path)
    print("总代码数量:", len(codes))
    for code in codes:
        extract_big_order_of_code(dir_path, code)
 
 
def extract_big_order_of_code(dir_path, code):
    """
    提取代码的大单
    @param dir_path: 数据目录
    @param code: 为空表示导出全部
    @return:
    """
 
    def first_last(group):
        """
            获取第一条数据与最后一条
            @param group:
            @return:
            """
        return pd.Series({
            'SecurityID': group['SecurityID'].iloc[0],
            'BuyNo': group['BuyNo'].iloc[0],
            'TotalVolume': group['TotalVolume'].sum(),
            'TotalAmount': group['TotalAmount'].sum(),
            'EndTime': group['EndTime'].iloc[-1],
            'EndPrice': group['EndPrice'].iloc[-1],
            'StartTime': group['StartTime'].iloc[0],
            'StartPrice': group['StartPrice'].iloc[0]
        })
 
    combined_path = os.path.join(dir_path, 'combined.csv')
    if not os.path.exists(combined_path):
        print("拼接数据不存在")
        return
    output_path = os.path.join(dir_path, f"big_buy_{code}.csv")
    if os.path.exists(output_path):
        print("路径已存在:", output_path)
        return
    df = __combined_df_cache.get(combined_path)
    if not df:
        df = pd.read_csv(combined_path)
        __combined_df_cache[combined_path] = df
    df_copy = df.copy()
    if code:
        df_copy = df_copy[df_copy["SecurityID"] == int(code)]
    if df_copy.empty:
        print("目标代码对应成交数据为空")
        return
    df_copy["SecurityID"] = df_copy["SecurityID"].apply(BigOrderDealParser.code_format)
    # 按SecurityID和BuyNo分组
    grouped = df_copy.groupby(['SecurityID', 'BuyNo'])
    grouped_result = grouped.apply(first_last)
    grouped_result = grouped_result[grouped_result["TotalAmount"] > 500000]
    # print(grouped_result)
    # 遍历内容
    grouped_result.to_csv(output_path, index=False)
    print(f"保存成功,路径:{output_path}")
 
 
def extract_big_order_codes(dir_path):
    """
    导出大单代码
    @param dir_path: 数据目录
    @param code:
    @return:
    """
    combined_path = os.path.join(dir_path, 'combined.csv')
    if not os.path.exists(combined_path):
        print("拼接数据不存在")
        return
    df = pd.read_csv(combined_path)
    df_copy = df.copy()
    if df_copy.empty:
        print("目标代码对应成交数据为空")
        return
    df_copy["SecurityID"] = df_copy["SecurityID"].apply(BigOrderDealParser.code_format)
    # 按SecurityID和BuyNo分组
    grouped = df_copy.groupby(['SecurityID'])
    return set(grouped.groups.keys())
 
 
if __name__ == "__main__":
    # pre_process_transactions("E:/测试数据/Transaction_Test.csv")
    # pre_process_ngtsticks("E:/测试数据/NGTSTick_Test.csv")
    # concat_pre_transactions("E:/测试数据/Transaction_Test")
    # extract_big_order_codes("E:/测试数据/Transaction_Test")
    extract_big_order_of_code("E:/测试数据/Transaction_Test")