-
Notifications
You must be signed in to change notification settings - Fork 312
Expand file tree
/
Copy pathGUI.py
More file actions
3892 lines (3310 loc) · 159 KB
/
GUI.py
File metadata and controls
3892 lines (3310 loc) · 159 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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# 该文件为GUI.py
import sys
import os
import ctypes
import subprocess
import requests
import hashlib,threading
import psutil
import pandas as pd
import numpy as np
import multiprocessing
import time
from queue import Empty
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QLabel,
QLineEdit, QTextEdit, QPushButton, QFileDialog, QMessageBox, QProgressBar,
QComboBox, QDateEdit, QTimeEdit, QGroupBox, QScrollArea, QCheckBox, QGridLayout,
QDialog,QTabWidget,QSplashScreen,QProgressDialog,QMenu, QStyle, QSplitter) # 添加QStyle和QSplitter
from PyQt5.QtCore import Qt, QThread, pyqtSignal, QDate, QTime, QRect, QTimer,QSettings,QPoint, QMutex, QUrl
from PyQt5.QtGui import QPen,QPixmap,QFont, QIcon, QPalette, QColor, QLinearGradient, QCursor, QPixmap, QPainter, QPainterPath, QDesktopServices
from khQTTools import download_and_store_data,get_and_save_stock_list, supplement_history_data
from PyQt5 import QtCore
import logging
from GUIplotLoadData import StockDataAnalyzerGUI # 添加这一行导入
#from activation_manager import ActivationCodeGenerator, MachineCode, ActivationManager
#from activation_thread import ActivationCheckThread # 添加这一行
from update_manager import UpdateManager # 将之前的UpdateManager类保存在单独的update_manager.py文件中
from version import get_version_info # 导入版本信息
from SettingsDialog import SettingsDialog
# 自定义控件类,禁用滚轮事件
class NoWheelComboBox(QComboBox):
"""禁用滚轮事件的QComboBox"""
def wheelEvent(self, event):
# 忽略滚轮事件,不调用父类的wheelEvent
event.ignore()
class NoWheelDateEdit(QDateEdit):
"""禁用滚轮事件的QDateEdit,修复中文显示问题"""
def __init__(self, parent=None):
super().__init__(parent)
self.setup_font()
def setup_font(self):
"""设置字体,解决中文显示问题"""
try:
from PyQt5.QtGui import QFont, QFontDatabase
# 尝试设置支持中文的字体
font_families = ["Microsoft YaHei", "SimHei", "SimSun", "Arial Unicode MS"]
for family in font_families:
if QFontDatabase().hasFamily(family):
font = QFont(family, 9)
font.setStyleHint(QFont.SansSerif)
self.setFont(font)
break
except Exception as e:
print(f"设置DateEdit字体时出错: {str(e)}")
def wheelEvent(self, event):
# 忽略滚轮事件,不调用父类的wheelEvent
event.ignore()
class NoWheelTimeEdit(QTimeEdit):
"""禁用滚轮事件的QTimeEdit,修复中文显示问题"""
def __init__(self, parent=None):
super().__init__(parent)
self.setup_font()
def setup_font(self):
"""设置字体,解决中文显示问题"""
try:
from PyQt5.QtGui import QFont, QFontDatabase
# 尝试设置支持中文的字体
font_families = ["Microsoft YaHei", "SimHei", "SimSun", "Arial Unicode MS"]
for family in font_families:
if QFontDatabase().hasFamily(family):
font = QFont(family, 9)
font.setStyleHint(QFont.SansSerif)
self.setFont(font)
break
except Exception as e:
print(f"设置TimeEdit字体时出错: {str(e)}")
def wheelEvent(self, event):
# 忽略滚轮事件,不调用父类的wheelEvent
event.ignore()
# 获取当前文件的上级目录
PARENT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(PARENT_DIR)
LOGS_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'logs')
# 在类的开头(__init__之前)添加图标路径的定义
#ICON_PATH = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'icons')
ICON_PATH = os.path.join(os.path.dirname(__file__), 'icons')
os.makedirs(LOGS_DIR, exist_ok=True)
# 配置日志记录
# filename: 指定日志文件的路径,将日志保存到LOGS_DIR目录下的app.log文件中
# level: 设置日志级别为DEBUG,记录所有级别的日志信息
# format: 设置日志格式,包含时间戳、日志级别和具体消息
# filemode: 设置文件模式为'w',即每次运行时覆盖之前的日志文件
logging.basicConfig(
filename=os.path.join(LOGS_DIR, 'app.log'),
level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s',
filemode='w'
)
# 同时将日志输出到控制台
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
console_handler.setFormatter(formatter)
logging.getLogger('').addHandler(console_handler)
# 保持原有的HelpDialog类不变
# 数据下载工作进程函数
def download_data_worker(params, progress_queue, result_queue, stop_event):
"""
数据下载工作进程函数
在独立进程中运行,避免GIL限制
"""
if __name__ != '__main__':
import multiprocessing
multiprocessing.current_process().name = 'DownloadWorker'
try:
import sys
import os
import time
# 延迟导入
try:
from khQTTools import download_and_store_data
except Exception as import_error:
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, current_dir)
try:
from khQTTools import download_and_store_data
except:
result_queue.put(('error', f"无法导入数据下载模块: {str(import_error)}"))
return
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# 控制更新频率
last_progress_time = 0
last_status_time = 0
update_interval = 1.0 # 1秒更新一次,减少UI压力
def progress_callback(percent):
nonlocal last_progress_time
current_time = time.time()
if current_time - last_progress_time >= update_interval or percent >= 100:
if not stop_event.is_set():
try:
progress_queue.put(('progress', percent), timeout=1)
last_progress_time = current_time
except:
pass
else:
raise InterruptedError("下载被中断")
def log_callback(message):
nonlocal last_status_time
current_time = time.time()
if current_time - last_status_time >= update_interval:
if not stop_event.is_set():
try:
progress_queue.put(('status', str(message)), timeout=1)
last_status_time = current_time
except:
pass
else:
raise InterruptedError("下载被中断")
def check_interrupt():
return stop_event.is_set()
# 执行数据下载
download_and_store_data(
local_data_path=params['local_data_path'],
stock_files=params['stock_files'],
field_list=params['field_list'],
period_type=params['period_type'],
start_date=params['start_date'],
end_date=params['end_date'],
dividend_type=params.get('dividend_type', 'none'),
time_range=params.get('time_range', 'all'),
progress_callback=progress_callback,
log_callback=log_callback,
check_interrupt=check_interrupt
)
result_queue.put(('success', '数据下载完成!'))
except Exception as e:
error_msg = f"下载过程中发生错误: {str(e)}"
result_queue.put(('error', error_msg))
logging.error(error_msg, exc_info=True)
class DownloadThread(QThread):
progress = pyqtSignal(int)
finished = pyqtSignal(bool, str)
error = pyqtSignal(str) # 添加错误信号
status_update = pyqtSignal(str) # 添加状态更新信号
def __init__(self, params, parent=None): # 添加parent参数
super().__init__(parent)
self.params = params
self.running = True
self.mutex = QMutex() # 添加互斥锁保护状态
# 多进程通信队列
self.progress_queue = multiprocessing.Queue(maxsize=50) # 减少队列大小
self.result_queue = multiprocessing.Queue()
self.stop_event = multiprocessing.Event()
self.process = None
logging.info(f"初始化下载线程,参数: {params}")
def run(self):
try:
if not self.isRunning():
return
# 参数验证
if not self.params.get('stock_files'):
raise ValueError("股票代码列表为空")
# 创建并启动子进程
self.process = multiprocessing.Process(
target=download_data_worker,
args=(self.params, self.progress_queue, self.result_queue, self.stop_event)
)
self.process.start()
# 在线程中监控进程间通信
while self.isRunning() and (self.process and self.process.is_alive()):
try:
# 检查进度和状态消息
while True:
try:
msg_type, data = self.progress_queue.get_nowait()
if msg_type == 'progress':
self.progress.emit(data)
elif msg_type == 'status':
self.status_update.emit(data)
except:
break
# 检查结果
try:
result_type, message = self.result_queue.get_nowait()
if result_type == 'success':
self.finished.emit(True, message)
else:
self.error.emit(message)
return
except:
pass
# 短暂休眠
self.msleep(200) # 减少检查频率
except Exception as e:
logging.error(f"监控下载进程时出错: {str(e)}")
break
# 检查进程是否异常退出
if self.process and not self.process.is_alive():
exit_code = self.process.exitcode
if exit_code != 0 and self.isRunning():
self.error.emit(f"下载进程异常退出,退出码: {exit_code}")
except Exception as e:
error_msg = f"启动下载进程时发生错误: {str(e)}"
logging.error(error_msg, exc_info=True)
if self.isRunning():
self.error.emit(error_msg)
self.finished.emit(False, error_msg)
def stop(self):
"""停止数据下载"""
logging.info("尝试停止下载线程")
self.mutex.lock()
self.running = False
# 停止多进程
try:
if self.stop_event:
self.stop_event.set()
if self.process and self.process.is_alive():
# 等待进程结束
self.process.join(timeout=5)
# 如果进程还没结束,强制终止
if self.process.is_alive():
self.process.terminate()
self.process.join(timeout=2)
if self.process.is_alive():
self.process.kill()
except Exception as e:
logging.error(f"停止下载进程时出错: {str(e)}")
self.mutex.unlock()
logging.info("已设置下载中断标志")
def isRunning(self):
self.mutex.lock()
result = self.running
self.mutex.unlock()
return result
def closeEvent(self, event):
"""窗口关闭时的处理"""
try:
# 停止所有定时器
if hasattr(self, 'status_timer'):
self.status_timer.stop()
if hasattr(self, 'refresh_timer'):
self.refresh_timer.stop()
# 停止下载线程
if hasattr(self, 'download_thread') and self.download_thread:
logging.info("正在停止下载线程...")
self.download_thread.stop()
self.download_thread.wait()
self.download_thread = None
logging.info("下载线程已停止")
# 停止补充数据线程
if hasattr(self, 'supplement_thread') and self.supplement_thread:
logging.info("正在停止补充数据线程...")
self.supplement_thread.stop()
self.supplement_thread.wait()
self.supplement_thread = None
logging.info("补充数据线程已停止")
# 停止清洗线程
if hasattr(self, 'cleaner_thread') and self.cleaner_thread:
logging.info("正在停止清洗线程...")
self.cleaner_thread.terminate()
self.cleaner_thread.wait()
self.cleaner_thread = None
logging.info("清洗线程已停止")
# 停止更新线程
if hasattr(self, 'update_thread') and self.update_thread:
logging.info("正在停止更新线程...")
self.update_thread.stop()
self.update_thread.wait()
self.update_thread = None
logging.info("更新线程已停止")
# 关闭可视化窗口
if hasattr(self, 'visualization_window') and self.visualization_window:
logging.info("正在关闭可视化窗口...")
self.visualization_window.close()
self.visualization_window = None
logging.info("可视化窗口已关闭")
logging.info("程序正常退出")
event.accept()
except Exception as e:
logging.error(f"程序退出时出错: {str(e)}", exc_info=True)
event.accept() # 确保程序能够退出
def supplement_data_worker(params, progress_queue, result_queue, stop_event):
"""
数据补充工作进程函数
在独立进程中运行,避免GIL限制
"""
# 多进程保护 - 防止在子进程中启动GUI
if __name__ != '__main__':
# 在子进程中,确保不会执行主程序代码
import multiprocessing
multiprocessing.current_process().name = 'GUISupplementWorker'
try:
# 在子进程中导入需要的模块
import sys
import os
# 延迟导入并捕获任何GUI相关错误
try:
from khQTTools import supplement_history_data
except Exception as import_error:
# 如果导入失败,尝试直接从当前目录导入
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, current_dir)
try:
from khQTTools import supplement_history_data
except:
result_queue.put(('error', f"无法导入数据补充模块: {str(import_error)}"))
return
import logging
import time
import re
# 配置子进程的日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# 进度和状态更新的时间控制
last_progress_time = 0
last_status_time = 0
update_interval = 0.5 # 500毫秒
# 统计信息
supplement_stats = {
'total_stocks': 0,
'success_count': 0,
'empty_data_count': 0,
'error_count': 0,
'empty_stocks': []
}
def progress_callback(percent):
nonlocal last_progress_time
current_time = time.time()
if current_time - last_progress_time >= update_interval or percent >= 100:
try:
progress_queue.put(('progress', percent), timeout=1)
last_progress_time = current_time
print(f"[GUI进程] 发送进度: {percent}%") # 调试信息
except Exception as e:
print(f"[GUI进程] 发送进度失败: {e}")
def log_callback(message):
nonlocal last_status_time
current_time = time.time()
try:
# 处理消息的统计和格式化(修复过滤逻辑)
# 检查是否是补充数据的成功消息
success_pattern = r"^补充\s+(.*?\.\S+)\s+数据成功"
success_match = re.match(success_pattern, message)
if success_match:
# 这是成功的补充消息,应该显示出来
stock_code = success_match.group(1)
supplement_stats['success_count'] += 1
# 直接转发成功消息,不修改格式
progress_queue.put(('status', message), timeout=1)
print(f"[GUI进程] 发送成功状态: {message}") # 调试信息
return
# 检查是否是错误消息
error_pattern = r"^补充\s+(.*?\.\S+)\s+数据时出错"
error_match = re.match(error_pattern, message)
if error_match:
# 这是错误消息,应该显示出来
stock_code = error_match.group(1)
supplement_stats['error_count'] += 1
# 直接转发错误消息
progress_queue.put(('status', message), timeout=1)
print(f"[GUI进程] 发送错误状态: {message}") # 调试信息
return
# 检查是否是空数据消息
empty_pattern = r"^补充\s+(.*?\.\S+)\s+数据成功,但数据为空"
empty_match = re.match(empty_pattern, message)
if empty_match:
# 这是空数据消息,应该显示出来
stock_code = empty_match.group(1)
supplement_stats['empty_data_count'] += 1
if stock_code not in supplement_stats['empty_stocks']:
supplement_stats['empty_stocks'].append(stock_code)
# 直接转发空数据消息
progress_queue.put(('status', message), timeout=1)
print(f"[GUI进程] 发送空数据状态: {message}") # 调试信息
return
# 重要消息立即发送
is_important = any(keyword in str(message) for keyword in ['开始', '完成', '失败', '错误', '中断'])
if is_important or current_time - last_status_time >= update_interval:
try:
progress_queue.put(('status', str(message)), timeout=1)
last_status_time = current_time
print(f"[GUI进程] 发送状态: {message}") # 调试信息
except Exception as e:
print(f"[GUI进程] 发送状态失败: {e}")
except Exception as e:
print(f"[GUI进程] log_callback 处理错误: {e}")
def check_interrupt():
# 检查停止事件
return stop_event.is_set()
# 执行数据补充
supplement_history_data(
stock_files=params['stock_files'],
field_list=params['field_list'],
period_type=params['period_type'],
start_date=params['start_date'],
end_date=params['end_date'],
time_range=params.get('time_range', 'all'),
dividend_type=params.get('dividend_type', 'none'),
progress_callback=progress_callback,
log_callback=log_callback,
check_interrupt=check_interrupt
)
# 构建详细的完成消息(单行汇总,避免换行)
total = supplement_stats['success_count'] + supplement_stats['empty_data_count'] + supplement_stats['error_count']
parts = ["数据补充完成!"]
parts.append(f"总股票数: {total}")
parts.append(f"成功补充: {supplement_stats['success_count']} 只股票")
if supplement_stats['empty_data_count']:
parts.append(f"空数据: {supplement_stats['empty_data_count']}")
if supplement_stats['error_count']:
parts.append(f"出错: {supplement_stats['error_count']}")
result_message = ";".join(parts)
# 发送完成信号
result_queue.put(('success', result_message.strip()))
except Exception as e:
error_msg = f"补充数据过程中发生错误: {str(e)}"
result_queue.put(('error', error_msg))
logging.error(error_msg, exc_info=True)
# 添加数据补充线程类(现在使用多进程后端)
class SupplementThread(QThread):
"""数据补充线程(现在使用多进程后端)"""
progress = pyqtSignal(int)
finished = pyqtSignal(bool, str)
error = pyqtSignal(str)
status_update = pyqtSignal(str)
def __init__(self, params, parent=None):
super().__init__(parent)
self.params = params
self.running = True
self.mutex = QMutex()
# 在主线程中创建进程间通信队列
self.progress_queue = multiprocessing.Queue(maxsize=100)
self.result_queue = multiprocessing.Queue()
self.stop_event = multiprocessing.Event()
self.process = None
def run(self):
try:
if not self.isRunning():
return
# 参数验证
if not self.params.get('stock_files'):
raise ValueError("股票代码列表为空")
# 创建并启动子进程
self.process = multiprocessing.Process(
target=supplement_data_worker,
args=(self.params, self.progress_queue, self.result_queue, self.stop_event)
)
self.process.start()
# 在线程中直接监控进程间通信
while self.isRunning() and (self.process and self.process.is_alive()):
try:
# 检查进度消息
while True:
try:
msg_type, data = self.progress_queue.get_nowait()
if msg_type == 'progress':
print(f"[GUI线程] 接收进度: {data}%") # 调试信息
self.progress.emit(data)
elif msg_type == 'status':
print(f"[GUI线程] 接收状态: {data}") # 调试信息
self.status_update.emit(data)
except Empty:
break
# 检查结果
try:
result_type, message = self.result_queue.get_nowait()
if result_type == 'success':
self.finished.emit(True, message)
else:
self.error.emit(message)
return # 完成后退出
except Empty:
pass
# 短暂休眠
self.msleep(100)
except Exception as e:
logging.error(f"监控进程时出错: {str(e)}")
break
# 检查进程是否异常退出
if self.process and not self.process.is_alive():
exit_code = self.process.exitcode
if exit_code != 0 and self.isRunning():
self.error.emit(f"数据补充进程异常退出,退出码: {exit_code}")
except Exception as e:
error_msg = f"启动数据补充进程时发生错误: {str(e)}"
logging.error(error_msg, exc_info=True)
if self.isRunning():
self.error.emit(error_msg)
self.finished.emit(False, error_msg)
def stop(self):
"""停止数据补充"""
self.mutex.lock()
self.running = False
# 停止多进程
try:
if self.stop_event:
self.stop_event.set()
if self.process and self.process.is_alive():
# 等待进程结束
self.process.join(timeout=5)
# 如果进程还没结束,强制终止
if self.process.is_alive():
self.process.terminate()
self.process.join(timeout=2)
if self.process.is_alive():
self.process.kill()
except Exception as e:
logging.error(f"停止进程时出错: {str(e)}")
self.mutex.unlock()
def isRunning(self):
self.mutex.lock()
result = self.running
self.mutex.unlock()
return result
class StockDataCleaner:
def __init__(self):
self.df = None
self.columns = []
self.row_changes = {}
self.deleted_rows = {}
self.reset()
def reset(self):
self.df = None
self.columns = []
self.row_changes = {}
self.deleted_rows = {}
def load_data(self, file_path):
self.reset()
self.df = pd.read_csv(file_path)
self.columns = self.df.columns.tolist()
return self
def clean_data(self):
if self.df is None:
raise ValueError("未加载数据。请先调用 load_data() 方法。")
self.remove_duplicates()
self.handle_missing_values()
self.correct_data_types()
self.remove_outliers()
self.handle_non_trading_hours()
self.sort_data()
return self
def remove_duplicates(self):
initial_rows = len(self.df)
# 识别时间戳列
time_columns = [col for col in self.df.columns if 'time' in col.lower() or 'date' in col.lower()]
if time_columns:
# 首先按时间戳检查重复
time_duplicates = self.df[self.df.duplicated(subset=time_columns, keep='first')]
# 对于时间戳重复的行,进一步检查其他数据是否也重复
full_duplicates = self.df[self.df.duplicated(keep='first')]
# 保存两种重复情况的统计
self.duplicate_stats = {
'time_duplicate_count': len(time_duplicates),
'full_duplicate_count': len(full_duplicates),
'time_only_duplicates': len(time_duplicates) - len(full_duplicates)
}
# 可以选择保留时间戳相同但数据不同的记录
# 这种情况可能是同一时刻的多笔交易
self.df = self.df.drop_duplicates(keep='first')
# 记录细节信息
self.deleted_rows['remove_duplicates'] = {
'time_duplicates': time_duplicates,
'full_duplicates': full_duplicates
}
# 添加警告日志
if len(time_duplicates) > len(full_duplicates):
logging.warning(
f"发现{len(time_duplicates) - len(full_duplicates)}行时间戳重复但数据不完全相同的记录,"
"这可能表示同一时刻的多笔交易"
)
else:
# 如果没有识别到时间列,按所有列查重
duplicates = self.df[self.df.duplicated()]
self.df = self.df.drop_duplicates(inplace=True)
self.deleted_rows['remove_duplicates'] = duplicates
final_rows = len(self.df)
self.row_changes['remove_duplicates'] = initial_rows - final_rows
def handle_missing_values(self):
initial_rows = len(self.df)
rows_with_missing = self.df[self.df.isnull().any(axis=1)]
price_columns = [col for col in ['open', 'high', 'low', 'close'] if col in self.columns]
if price_columns:
self.df[price_columns] = self.df[price_columns].ffill()
volume_columns = [col for col in ['volume'] if col in self.columns]
if volume_columns:
self.df[volume_columns] = self.df[volume_columns].fillna(0)
self.df.dropna(inplace=True)
final_rows = len(self.df)
self.row_changes['handle_missing_values'] = initial_rows - final_rows
self.deleted_rows['handle_missing_values'] = rows_with_missing
def correct_data_types(self):
date_columns = [col for col in self.columns if 'date' in col.lower()]
for col in date_columns:
self.df[col] = pd.to_datetime(self.df[col], errors='coerce')
numeric_columns = [col for col in ['open', 'high', 'low', 'close', 'volume'] if col in self.columns]
for col in numeric_columns:
self.df[col] = pd.to_numeric(self.df[col], errors='coerce')
def remove_outliers(self):
initial_rows = len(self.df)
outliers = pd.DataFrame()
price_columns = [col for col in ['open', 'high', 'low', 'close'] if col in self.columns]
for col in price_columns:
Q1 = self.df[col].quantile(0.25)
Q3 = self.df[col].quantile(0.75)
IQR = Q3 - Q1
lower_bound = Q1 - 5 * IQR
upper_bound = Q3 + 5 * IQR
col_outliers = self.df[(self.df[col] < lower_bound) | (self.df[col] > upper_bound)]
outliers = pd.concat([outliers, col_outliers])
self.df = self.df[(self.df[col] >= lower_bound) & (self.df[col] <= upper_bound)]
final_rows = len(self.df)
self.row_changes['remove_outliers'] = initial_rows - final_rows
self.deleted_rows['remove_outliers'] = outliers
def handle_non_trading_hours(self):
initial_rows = len(self.df)
non_trading_hours = pd.DataFrame() # 初始化变量
if 'time' in self.columns:
morning_start = pd.to_datetime('09:30:00').time()
morning_end = pd.to_datetime('11:30:00').time()
afternoon_start = pd.to_datetime('13:00:00').time()
afternoon_end = pd.to_datetime('15:00:00').time()
self.df['time'] = pd.to_datetime(self.df['time'], errors='coerce').dt.time
# 修复括号匹配问题
non_trading_hours = self.df[
~(((self.df['time'] >= morning_start) & (self.df['time'] <= morning_end)) |
((self.df['time'] >= afternoon_start) & (self.df['time'] <= afternoon_end)))
]
self.df = self.df[
((self.df['time'] >= morning_start) & (self.df['time'] <= morning_end)) |
((self.df['time'] >= afternoon_start) & (self.df['time'] <= afternoon_end))
]
final_rows = len(self.df)
self.row_changes['handle_non_trading_hours'] = initial_rows - final_rows
self.deleted_rows['handle_non_trading_hours'] = non_trading_hours
def sort_data(self):
sort_columns = [col for col in self.columns if 'date' in col.lower() or 'time' in col.lower()]
if sort_columns:
self.df.sort_values(by=sort_columns, inplace=True)
def get_cleaned_data(self):
return self.df
def save_cleaned_data(self, file_path):
self.df.to_csv(file_path, index=False)
def get_column_info(self):
return {
'all_columns': self.columns,
'date_columns': [col for col in self.columns if 'date' in col.lower()],
'time_columns': [col for col in self.columns if 'time' in col.lower()],
'price_columns': [col for col in ['open', 'high', 'low', 'close'] if col in self.columns],
'volume_columns': [col for col in ['volume'] if col in self.columns]
}
def get_data_info(self):
return {
'shape': self.df.shape,
'dtypes': self.df.dtypes.to_dict(),
'missing_values': self.df.isnull().sum().to_dict(),
'duplicates': self.df.duplicated().sum(),
'numeric_stats': self.df.describe().to_dict(),
'row_changes': self.row_changes,
'deleted_rows': self.deleted_rows
}
class CleanerThread(QThread):
progress_updated = pyqtSignal(int, int)
cleaning_completed = pyqtSignal(dict)
error_occurred = pyqtSignal(str)
def __init__(self, cleaner, folder_path, operations):
super().__init__()
self.cleaner = cleaner
self.folder_path = folder_path
self.operations = operations
def run(self):
try:
csv_files = [f for f in os.listdir(self.folder_path) if f.endswith('.csv')]
total_files = len(csv_files)
cleaning_info = {}
for file_index, file in enumerate(csv_files):
file_path = os.path.join(self.folder_path, file)
# 创建临时备份
backup_path = file_path + '.bak'
with open(file_path, 'r', encoding='utf-8') as source:
with open(backup_path, 'w', encoding='utf-8') as target:
target.write(source.read())
try:
self.cleaner.load_data(file_path)
before_info = self.cleaner.get_data_info()
total_steps = len(self.operations)
for i, operation in enumerate(self.operations):
if hasattr(self.cleaner, operation):
getattr(self.cleaner, operation)()
file_progress = int((i + 1) / total_steps * 100)
total_progress = int((file_index * 100 + file_progress) / total_files)
self.progress_updated.emit(file_progress, total_progress)
self.cleaner.save_cleaned_data(file_path)
after_info = self.cleaner.get_data_info()
cleaning_info[file] = {
'before': before_info,
'after': after_info
}
os.remove(backup_path)
except Exception as e:
if os.path.exists(backup_path):
os.replace(backup_path, file_path)
raise e
self.cleaning_completed.emit(cleaning_info)
except Exception as e:
self.error_occurred.emit(str(e))
class StockDataProcessorGUI(QMainWindow):
def __init__(self):
super().__init__()
# 检查QSettings存储位置
settings = QSettings('KHQuant', 'StockAnalyzer')
logging.info(f"QSettings存储位置: {settings.fileName()}")
logging.info(f"QSettings格式: {settings.format()}")
logging.info(f"QSettings范围: {settings.scope()}")
# 检测屏幕分辨率并设置字体大小比例
self.font_scale = self.detect_screen_resolution()
# 移除激活相关的初始化代码
self._activation_warning_shown = False
# 修改图标路径的获取方式
if getattr(sys, 'frozen', False):
# 打包后的环境,图标文件在 _internal/icons 目录下
self.ICON_PATH = os.path.join(os.path.dirname(sys.executable), '_internal', 'icons')
else:
# 开发环境
self.ICON_PATH = os.path.join(os.path.dirname(__file__), 'icons')
# 确保图标目录存在
os.makedirs(self.ICON_PATH, exist_ok=True)
# 添加调试日志
# logging.info(f"初始化图标路径: {self.ICON_PATH}")
if os.path.exists(self.ICON_PATH):
pass
#logging.info(f"图标目录内容: {os.listdir(self.ICON_PATH)}")
else:
logging.warning(f"图标目录不存在: {self.ICON_PATH}")
self.cleaner = StockDataCleaner()
self.visualization_window = None
# 初始化更新管理器(在其他初始化之前)
self.initialize_update_manager()
# 修改窗口属性设置
# self.setAttribute(Qt.WA_TranslucentBackground) # 移除
# self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowSystemMenuHint) # 移除,使用默认窗口样式
# 移除之前设置的非透明背景(冲突设置)
# self.setAttribute(Qt.WA_TranslucentBackground, False) # 禁用透明背景
# 设置窗口背景色 (这个会影响 central_widget 的背景,如果central_widget有自己的背景设置,这个可能不需要)
palette = self.palette()
palette.setColor(QPalette.Window, QColor("#2b2b2b"))
self.setPalette(palette)
# 获取版本信息
self.version_info = get_version_info()
# 在启动画面显示版本信息
if hasattr(self, 'splash'):
self.version_label.setText(f"V{self.version_info['version']}")
self.initUI()
# 下面这些属性是为无边框窗口拖动和缩放服务的,现在移除
# self.can_drag = False
# self.resizing = False
# self.resize_edge = None
# self.border_thickness = 20
# self.setMouseTracking(True) # 如果没有其他地方用到mouseMoveEvent,则此行也应移除
# 添加定时器来检查软件状态
self.status_timer = QTimer(self)
self.status_timer.timeout.connect(self.check_software_status)
self.status_timer.start(5000)
# 初始软件检查
self.check_and_open_software()
# 添加一个计时器用于延迟刷新
self.refresh_timer = QTimer(self)
self.refresh_timer.setSingleShot(True)
self.refresh_timer.timeout.connect(self.refresh_folder)
# 不再使用状态栏,改用status_label (status_label现在也没有明确位置了)
# self.statusBar().showMessage('就绪')
# 隐藏状态栏 (如果用系统标题栏,可以考虑显示状态栏)
# self.statusBar().hide()
# 获取屏幕分辨率
screen = QApplication.primaryScreen().geometry()
screen_width = screen.width()
screen_height = screen.height()
# 设置初始窗口大小(将通过showFullScreen()进入全屏)
# 在全屏模式下不需要初始resize,因为会立即进入全屏
def detect_screen_resolution(self):
"""检测屏幕分辨率并返回字体缩放比例"""
from PyQt5.QtWidgets import QApplication
screen = QApplication.desktop().screenGeometry()
width = screen.width()
height = screen.height()
# 根据屏幕宽度确定字体缩放比例
if width >= 3840: # 4K及以上分辨率
return 1.8
elif width >= 2560: # 2K分辨率