File size: 51,987 Bytes
1721429
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
# coding: UTF-8
import configparser
import os
import psutil
import scipy.io as scio
import numpy as np
import pandas as pd
import sys
from backtest_framework.print_type import PrintType as p
import copy
import warnings
from sklearn.linear_model import LinearRegression
import scipy.stats as st
from wby_utils.path.Path import get_all_dirs

warnings.filterwarnings("ignore")


class DataApi:
    def getConfig(self):
        """

        赋值路径用函数

        :param:

        :return:

        """
        try:
            self.config = configparser.ConfigParser()
            self.config.read(self.configPath, encoding="utf-8")
        except Exception as e:
            p.error_print(sys._getframe().f_code.co_filename, sys._getframe().f_code.co_name, "配置文件读取失败!")
        else:
            self.local_db_path = self.config['data_path']['local_db']
            self.dataPathList.append(self.config['data_path']['base_data_path'])
            self.factorNpzPath = self.config['data_path']['derivative_factor_npz_path']  # 因子路径
            self.dataPathList.append(self.factorNpzPath)
            self.result_path = self.config['data_path']['result_path']  # 结果路径
            self.dataPathList.append(self.result_path)

    def getLpp(self):
        """

        获取回测下标用函数

        :return: int,回测下标

        """
        return self.lpp

    def setLpp(self, lpp):
        """

        设置回测下标用函数

        :return:

        """
        self.lpp = lpp

    def version(process_name):
        """

        展示版本用函数

        :param process_name: 运行程序类名,char类型

        :return:

        """
        crossbar = "==============================================="
        version = "==" + process_name + " for Python3, Version: 0.0.1=="

        p.version_print(sys._getframe().f_code.co_filename, sys._getframe().f_code.co_name, crossbar)
        p.version_print(sys._getframe().f_code.co_filename, sys._getframe().f_code.co_name, version)
        p.version_print(sys._getframe().f_code.co_filename, sys._getframe().f_code.co_name, crossbar)

    def loadDerivativeFactorToGlobal(self, factorName, shapeType, typeLen):
        """

            从指定目录读取因子数据用函数

            :param factorName:因子名

            :param shapeType:char类型,‘tensor’表示三维矩阵型因子,’matrix‘表示矩阵型因子,’vector‘表示列表型因子

            :param typeLen:typeLen在当type为’vector‘的时候的列数,‘tensor’二维和三维的长度

            :return:

        """
        if factorName in self.globalSave.keys():
            p.disp_print(sys._getframe().f_code.co_filename,
                         sys._getframe().f_code.co_name, "请求的因子已被导入!")
            return

        tradeDate = self.getAllData("trade_date_int")

        filePath_npz = self.factorNpzPath + factorName + ".npz"
        filePath_mat = self.factorNpzPath + factorName + ".mat"
        try:
            try:
                data = np.load(filePath_npz)
                single_key = data.files[0]
                factorData = data[single_key]
            except:
                factorData = scio.loadmat(filePath_mat)[factorName]
            site = np.max([1, np.shape(factorData)[0] - self.factorGeneratorTradeDateCount - 1])

            self.startDate = str(tradeDate[site][0])
            self.endDate = str(tradeDate[-1][0])
            if shapeType == "matrix":
                factorData = self.myFactorReshape(factorData)
            elif shapeType == 'vector':
                factor = np.nan * np.zeros((len(tradeDate), factorData.shape[1]))
                factor[:factorData.shape[0], :factorData.shape[1]] = factorData
                factorData = factor
            elif shapeType == 'tensor':
                factor = np.nan * np.zeros((len(tradeDate), factorData.shape[1], factorData.shape[2]))
                factor[:factorData.shape[0], :factorData.shape[1], :factorData.shape[2]] = factorData
                factorData = factor
        except:
            self.startDate = str(tradeDate[0][0])
            self.endDate = str(tradeDate[-1][0])
            if shapeType == 'matrix':
                factorData = self.myFactorReshape()
            elif shapeType == 'vector':
                factorData = np.nan * np.zeros((len(tradeDate), typeLen))
            elif shapeType == 'tensor':
                if len(typeLen) == 1:
                    p.error_print(sys._getframe().f_code.co_filename,
                                  sys._getframe().f_code.co_name, "typeLen参数不能为标量!")
                factorData = np.nan * np.zeros((len(tradeDate), typeLen[0], typeLen[1]))
        self.globalSave[factorName] = factorData
        p.disp_print(sys._getframe().f_code.co_filename,
                     sys._getframe().f_code.co_name, "导入" + factorName + "文件!")

    def setGlobal(self, globalName, globalValue):
        """

        存储全局变量用函数

        :param globalName: char类型,全局变量名

        :param globalValue: 任意类型,全局变量值

        :return:

        """
        self.globalSave[globalName] = globalValue

    def getGlobal(self, globalName):
        """

        获取全局变量用函数

        :param globalName: char类型,全局变量名

        :return: 任意类型, 全局变量值

        """

        try:
            return self.globalSave[globalName]
        except:

            p.warning_print(sys._getframe().f_code.co_filename, sys._getframe().f_code.co_name,
                            f"请求的全局变量不存在!{globalName}")
            return None

    def getAllData(self, key):
        """

        获取数据文件用函数

        :param key: char类型,数据名称

        :return: 数据文件,np.array格式

        """
        if key not in self.allData:
            npzFile = key + '.npz'
            matFile = key + '.mat'
            for dataPath in self.dataPathList:
                if npzFile in os.listdir(dataPath):
                    data = np.load(dataPath + "\\\\" + npzFile, allow_pickle=True)
                    single_key = data.files[0]
                    value = data[single_key]
                    self.allData[key] = value

                    p.disp_print(sys._getframe().f_code.co_filename,
                                 sys._getframe().f_code.co_name,
                                 "因子文件" + key + "成功导入!")
                    return self.allData[key]
                elif matFile in os.listdir(dataPath):
                    value = scio.loadmat(dataPath + matFile)[key]
                    self.allData[key] = value

                    p.disp_print(sys._getframe().f_code.co_filename,
                                 sys._getframe().f_code.co_name,
                                 "因子文件" + key + "成功导入!")
                    return self.allData[key]

            p.error_print(sys._getframe().f_code.co_filename,
                          sys._getframe().f_code.co_name,

                          "因子文件导入失败!找不到因子文件" + key + ",请更新因子!" + dataPath)
        return self.allData[key]

    def getDataPackage(self, key):
        """

        获取数据文件用函数

        :param key: char类型,数据名称

        :return: 数据文件,np.array格式

        """
        if key not in self.allData:
            npzFile = key + '.npz'
            matFile = key + '.mat'
            for dataPath in self.dataPathList:
                if npzFile in os.listdir(dataPath):
                    data = np.load(dataPath + "\\\\" + npzFile, allow_pickle=True)
                    self.allData[key] = data

                    p.disp_print(sys._getframe().f_code.co_filename,
                                 sys._getframe().f_code.co_name,
                                 "数据包" + key + "成功导入!")
                    return self.allData[key]
                elif matFile in os.listdir(dataPath):
                    value = scio.loadmat(dataPath + matFile)[key]
                    self.allData[key] = value

                    p.disp_print(sys._getframe().f_code.co_filename,
                                 sys._getframe().f_code.co_name,
                                 "数据包" + key + "成功导入!")
                    return self.allData[key]

            p.error_print(sys._getframe().f_code.co_filename,
                          sys._getframe().f_code.co_name,
                          "数据包导入失败!找不到数据包" + key + ",请更新数据包!")
        return self.allData[key]

    def getFieldTickData(self, code, tradeDate):
        """

        获取tick交易数据用函数

        :param code: char类型,股票代码

        :param tradeDate:int类型,交易日期

        :return: np.array类型,tick交易数据

        """

        trade_date = self.getAllData('trade_date_int')
        tradeDateSite = np.where(trade_date == int(tradeDate))[0][0]

        if not tradeDateSite:
            p.error_print(sys._getframe().f_code.co_filename,
                          sys._getframe().f_code.co_name, "请求的日期为非交易日!")

        elif tradeDateSite > self.getLpp():
            p.error_print(sys._getframe().f_code.co_filename,
                          sys._getframe().f_code.co_name, "禁止提取未来数据!")

        else:
            quotePath = self.local_db_path + 'quote_data\\stock\\xt_tick_data\\' + str(tradeDate) + '\\'

            dataFile = f"{quotePath}{code}.npz"
            ret = np.load(dataFile, allow_pickle=True)

        return ret

    def getFieldMinuteData(self, fieldName, tradeDate):
        """

        获取日内交易数据用函数

        :param fieldName: char类型,日内交易数据名称

        :param tradeDate: int类型,交易日期

        :return: np.array类型,日内交易数据

        """

        trade_date = self.getAllData('trade_date_int')
        tradeDateSite = np.where(trade_date == int(tradeDate))[0][0]

        if not tradeDateSite:
            p.error_print(sys._getframe().f_code.co_filename,
                          sys._getframe().f_code.co_name, "请求的日期为非交易日!")

        elif tradeDateSite > self.getLpp():
            p.error_print(sys._getframe().f_code.co_filename,
                          sys._getframe().f_code.co_name, "禁止提取未来数据!")

        else:

            if fieldName[-2:] == '1m':
                quotePath = self.local_db_path + 'quote_data\\stock\\minute_data\\1m\\'
            elif fieldName[-2:] == '5m' and not fieldName[-3:] == '15m':
                quotePath = self.local_db_path + 'quote_data\\stock\\minute_data\\5m\\'
            elif fieldName[-3:] == '10m':
                quotePath = self.local_db_path + 'quote_data\\stock\\minute_data\\10m\\'
            elif fieldName[-3:] == '15m':
                quotePath = self.local_db_path + 'quote_data\\stock\\minute_data\\15m\\'
            elif fieldName[-3:] == '30m':
                quotePath = self.local_db_path + 'quote_data\\stock\\minute_data\\30m\\'
            elif fieldName[-3:] == '60m':
                quotePath = self.local_db_path + 'quote_data\\stock\\minute_data\\60m\\'
            else:
                p.error_print(sys._getframe().f_code.co_filename,
                              sys._getframe().f_code.co_name,
                              "请求的因子文件为非日内行情数据!")

            dataFile = f"{quotePath}{fieldName}_{tradeDate}.npz"
            data = np.load(dataFile, allow_pickle=True)
            single_key = data.files[0]
            value = data[single_key]
            ret = self.quoteCorrection(value)

        return ret

    def getStartTradeDate(self, startTradeDate, change):
        """

        设置开始交易日期标签用函数

        :param startTradeDate: int类型,开始交易日期

        :return: startDateFlag数值,int类型

        """
        tradeDate = self.getAllData('trade_date_int')

        if startTradeDate and startTradeDate != np.inf:

            date = int(startTradeDate)

            ret = 0
            minDistant = np.inf
            for i in list(range(0, len(tradeDate))):
                if tradeDate[i] - date < minDistant and tradeDate[i] - date >= 0:
                    minDistant = tradeDate[i] - date
                    ret = i

        else:

            ret = 0
        if change == True:
            self.startDateFlag = ret

        return ret

    def getEndTradeDate(self, endTradeDate=""):
        """

        设置结束交易日期标签用函数

        :param endTradeDate: int类型,结束交易日期

        :return: endDateFlag数值,int类型

        """
        tradeDate = self.getAllData('trade_date_int')

        if endTradeDate and endTradeDate != np.inf:

            date = int(endTradeDate)

            ret = 0
            minDistant = np.inf
            for i in list(range(0, len(tradeDate))):
                if date - tradeDate[i] < minDistant and date - tradeDate[
                    i] >= 0:
                    minDistant = date - tradeDate[i]
                    ret = i

        else:

            ret = len(tradeDate)

        self.endDateFlag = ret

        return ret

    def myFactorReshape(self, inputData):
        """

        规范数据形状用函数

        :param inputData: np.array类型,输入的数据

        :return: np.array类型,重塑形状之后的数据

        """
        tradeDate = self.getAllData("trade_date_int")
        stock_list = self.getAllData("stock_code")
        if not inputData is None:
            if inputData.shape[1] < len(stock_list):
                ret = np.hstack((inputData, np.nan * np.zeros(
                    (inputData.shape[0],
                     len(stock_list) - inputData.shape[1]))))
            else:
                ret = inputData
            if inputData.shape[0] < len(tradeDate):
                ret = np.vstack((ret, np.nan * np.zeros(
                    (len(tradeDate) - ret.shape[0], ret.shape[1]))))
        else:
            ret = np.nan * np.zeros([len(tradeDate), len(stock_list)])

        return ret

    def myWinsorizeCalc(self, inputValue, sigma, calcType):
        """

        去极值用函数

        :param inputValue: np.array类型,输入的数据

        :param sigma: int类型,控制宽度参数

        :param calcType: char类型,“std”、“median”、“Briner”,代表去极值方法

        :return: np.array类型,去极值后的数据

        """
        inputValue_ = copy.deepcopy(inputValue)
        if calcType == 'std' or calcType == 'median':
            if calcType == 'std':
                meanValue = np.nanmean(inputValue_)
                stdValue = np.nanstd(inputValue_)
            elif calcType == 'median':
                meanValue = np.nanmedian(inputValue_)
                stdValue = np.nanmedian(np.abs(inputValue_ - meanValue))

            upperThreshold = meanValue + stdValue * sigma
            lowerThreshold = meanValue - stdValue * sigma

            while len(np.where(inputValue_ > upperThreshold)[1]) > 0 or len(
                    np.where(inputValue_ < lowerThreshold)[1]) > 0:

                inputValue_[0, np.where(
                    inputValue_ > upperThreshold)[1]] = upperThreshold
                inputValue_[0, np.where(
                    inputValue_ < lowerThreshold)[1]] = lowerThreshold

                if calcType == 'std':
                    meanValue = np.nanmean(inputValue_)
                    stdValue = np.nanstd(inputValue_)
                elif calcType == 'median':
                    meanValue = np.nanmedian(inputValue_)
                    stdValue = np.nanmedian(np.abs(inputValue_ - meanValue))

                upperThreshold = meanValue + stdValue * sigma
                lowerThreshold = meanValue - stdValue * sigma

        elif calcType == 'Briner':
            inputValue_ = self.myStandardizeCalc(inputValue_)
            s_plus = max(0, min(1, 0.5 / np.nanmax(inputValue_ - sigma)))
            s_minus = max(0, min(1, -0.5 / np.nanmin(inputValue_ + sigma)))
            inputValue_[0, np.where(
                inputValue_ > sigma)[1]] = sigma * (1 - s_plus) + inputValue_[
                0, np.where(inputValue_ > sigma)[1]] * s_plus
            inputValue_[0, np.where(
                inputValue_ < -sigma)[1]] = -sigma * (1 - s_minus) + inputValue_[
                0, np.where(inputValue_ < -sigma)[1]] * s_minus

        else:
            meanValue = np.nan
            stdValue = np.nan
            p.warning_print(sys._getframe().f_code.co_filename,
                            sys._getframe().f_code.co_name, "标准化类型的入参有误!")

        return inputValue_

    def myStandardizeCalc(self, inputValue, calcType, filter):
        """

        标准化用函数

        :param inputValue: np.array类型,输入的数据

        :param calcType: char类型,“zscore”或“0-1”,代表标准化方法

        :return: np.array类型,标准化后的数据

        """
        if calcType == 'zscore':
            return (inputValue -
                    np.nanmean(inputValue)) / np.nanstd(inputValue)
        elif calcType == '0-1':
            return (inputValue - np.nanmin(inputValue)) / (
                    np.nanmax(inputValue) - np.nanmin(inputValue))
        elif calcType == 'ppf':
            ppf = st.norm.ppf(1 - np.sum(~np.isnan(inputValue)) / np.sum(~np.isnan(filter)))
            return ppf + (np.nanmax(inputValue) - ppf) / (np.nanmax(inputValue) - np.nanmin(inputValue)) * (
                    inputValue - np.nanmin(inputValue))

    def myNanFillAsData(self, inputValue, data):
        """

        缺失值填充用函数

        :param inputValue: np.array类型,输入的数据

        :param data: float类型,填充缺失值用参数

        :return: np.array类型,填充缺失值后的数据

        """
        stockTradeDayCount = self.getFieldData('stockTradeDayCount', 1)
        inTheMarket = np.nan * np.zeros([1, np.shape(stockTradeDayCount)[1]])
        inTheMarket[0, np.where(stockTradeDayCount > 0)[1]] = 1
        for i in range(np.shape(inTheMarket)[1]):
            if np.isnan(inTheMarket[0, i]) == False and np.isnan(
                    inputValue[0, i]):
                inputValue[0, i] = data

        return inputValue * inTheMarket

    def myIndustryFlag(zx):
        """

        生成各股行业one-hot矩阵用函数

        :param zx: np.array类型,中信行业数据

        :return: np.array类型,各股行业one-hot矩阵

        """
        ret = np.zeros([int(np.nanmax(zx)), int(np.shape(zx)[1])])

        for i in list(range(int(np.nanmax(zx)))):
            ret[i, np.where(zx == i + 1)[1]] = 1

        return ret

    def removeAllData(self, key, usedMemoProcess, usedMemoPercent):
        """

        从内存移除数据用函数

        :param key: list类型,包含数据名称的列表

        :param usedMemoProcess: float类型,python进程占用内存GB上限

        :param usedMemoPercent: float类型,计算机内存占用百分比上限

        :return:

        """
        if not usedMemoProcess and not usedMemoPercent:
            for i in range(len(key)):
                self.allData.pop(key[i])

                p.disp_print(sys._getframe().f_code.co_filename,
                             sys._getframe().f_code.co_name,
                             "请求的因子/数据包" + key[i] + "删除完毕!")
        else:

            mem_Process = round(
                psutil.Process(os.getpid()).memory_info().rss / 1024 / 1024 /
                1024, 2)
            memPercent = round(psutil.virtual_memory().percent / 100, 2)

            if (usedMemoProcess and mem_Process > usedMemoProcess) or (
                    usedMemoPercent and memPercent > usedMemoPercent):

                for i in range(len(key)):
                    self.allData.pop(key[i])

                    p.disp_print(sys._getframe().f_code.co_filename,
                                 sys._getframe().f_code.co_name,
                                 "请求的因子/数据包" + key[i] + "删除完毕!")

    def getStockName(self):
        """

        获取股票名称用函数

        :param 

        :return: np.array类型,股票名称列表

        """
        return self.getAllData("stockName")

    def getStockCode(self):
        """

        获取股票数字代码用函数

        :param 

        :return: np.array类型,股票数字代码列表

        """
        stock_list = self.getStockList()
        return np.array(list(map(lambda x: int(x[:6]), stock_list)))

    def getStockList(self):
        """

        获取股票代码用函数

        :param 

        :return: np.array类型,股票代码列表

        """
        return self.getAllData("stock_code")

    def getTradeDateList(self, varargin):
        """

        返回交易日历,不传入参数返回历史所有的交易日历,传入参数返回固定交易日数的交易日历

        :param days: 返回固定交易日期数

        :return: List

        """
        ret = self.getAllData("trade_date_int")

        if varargin:
            return ret[self.getLpp() - varargin + 1:self.getLpp() + 1, :]
        else:
            return ret[:self.getLpp() + 1, :]

    def isLastDate(self):
        """

        判断是否为最后一个回测截面,如果是,返回True,否则返回False

        :return: bool

        """
        return self.lpp == self.endDateFlag

    def getStockIndexQuotes(self, indexCode, varargin):  # TODO
        """

        获取股票指数行情数据

        :param indexCode:指数代码

        :param varargin:可选参数,截取的日期行数

        :return:

        """
        lpp = self.lpp
        nowDate = self.getNowDate()
        indexQuotes = self.getAllData("stockIndexQuotes")[()][indexCode]
        site = np.where(indexQuotes[:, 0] == nowDate)[0][0]
        if varargin:
            return indexQuotes[lpp - varargin + 1:lpp + 1]
        else:
            return indexQuotes[:lpp + 1]

    def getStockIndexDailyQuotes(self, indexCode, tradeDate):
        """

        获取股票指数日内行情数据

        :param indexCode:指数代码

        :param tradeDate:行情日期

        :return:

        """
        return self.getAllData("stockIndexDailyQuotes")[()][indexCode][tradeDate]

    def getFieldData(self, fieldName, varargin):
        """

        获取因子矩阵用函数

        :param fieldName:因子名

        :param varargin: 返回的因子行数

        :return:

        """
        lpp = self.lpp
        if varargin:
            return self.getAllData(fieldName)[lpp - varargin + 1:lpp + 1]
        else:
            return self.getAllData(fieldName)[:lpp + 1]

    def getFieldDataByIndex(self, fieldName, index):
        """

        获取因子矩阵用函数

        :param fieldName:因子名

        :param index: 回测下标

        :return:

        """
        return self.getAllData(fieldName)[index].reshape(1, -1)

    def saveGlobal(self, globalName):
        """

        存储因子到指定文件夹目录

        :param globalName:请求存储的因子名

        :return:

        """

        factorData = self.getGlobal(globalName)

        if sum(factorData[-1] == 0) + sum(np.isnan(
                factorData[-1])) == factorData.shape[1]:
            p.warning_print(sys._getframe().f_code.co_filename,
                            sys._getframe().f_code.co_name,
                            "衍生因子 " + globalName + " 异常,结果未保存!")

        else:
            np.savez_compressed(self.factorNpzPath + globalName + '.npz', factorData)
            if self.saveFactorResultAsMat == True:
                scio.savemat(self.factorNpzPath + globalName + '.mat', {globalName: factorData})

            p.disp_print(sys._getframe().f_code.co_filename,
                         sys._getframe().f_code.co_name,
                         "衍生因子 " + globalName + " 保存完成!")

    def saveGlobalUnconditionally(self, globalName):
        """

        无条件存储因子到指定文件夹目录

        :param globalName:请求存储的因子名

        :return:

        """

        factorData = self.getGlobal(globalName)

        np.savez_compressed(self.factorNpzPath + globalName + '.npz', factorData)
        if self.saveFactorResultAsMat == True:
            scio.savemat(self.factorNpzPath + globalName + '.mat', {globalName: factorData})

        p.disp_print(sys._getframe().f_code.co_filename,
                     sys._getframe().f_code.co_name,
                     "衍生因子 " + globalName + " 保存完成!")

    def getBarCount(self):
        """

        返回bar计数

        :return:

        """
        return self.barCount

    def getNowDate(self, type):
        """

        返回回测当日下标的日期

        :return:

        """
        if type == 'int':
            return self.getAllData("trade_date_int")[self.lpp][0]
        elif type == 'datetime':
            return self.getAllData("trade_date_datetime")[self.lpp][0]
        else:
            p.error_print(sys._getframe().f_code.co_filename,
                          sys._getframe().f_code.co_name,
                          "type类型有误!")

    def getYesterdayDate(self, type):
        """

        返回回测前一日下标的日期

        :return:

        """
        if type == 'int':
            return self.getAllData("trade_date_int")[self.lpp - 1][0]
        elif type == 'datetime':
            return self.getAllData("trade_date_datetime")[self.lpp - 1][0]
        else:
            p.error_print(sys._getframe().f_code.co_filename,
                          sys._getframe().f_code.co_name,
                          "type类型有误!")

    def getNextDate(self, type):
        """

        返回回测下一日下标的日期

        :return:

        """
        if type == 'int':
            tradeDate = self.getAllData("trade_date_int")
            tradeDateHistory = self.getAllData("calendar_date_int")
        elif type == 'datetime':
            tradeDate = self.getAllData("trade_date_datetime")
            tradeDateHistory = self.getAllData("calendar_date_datetime")
        else:
            p.error_print(sys._getframe().f_code.co_filename,
                          sys._getframe().f_code.co_name,
                          "type类型有误!")
        index = np.where(tradeDateHistory == tradeDate[self.lpp])[0][0]
        return tradeDateHistory[index + 1][0]

    def getHalfTimeWeight(halflife, window):
        '''

        得到半衰期权重,WLS回归用

        :param halflife: 半衰期时长,int类型

        :param window: 观察期窗口,int类型

        :return: 半衰期标准化后的权重,np.array类型,一行

        '''

        sigma = 0.5 ** (1 / halflife)
        weight = np.empty([1, window])
        for i in range(window):
            weight[0, i] = sigma ** (window - i)
        weight = weight / np.sum(weight)
        return weight.reshape(1, -1)  # 转化为1Darray 方便

    def myFiltering(self, inputValue):
        """

        将非交易日的因子值设置为np.nan用函数,同时将inf转化为nan

        :param inputValue: np.array类型,输入的数据

        :param data: float类型,填充缺失值用参数

        :return: np.array类型,填充缺失值后的数据

        """
        stockTradeDayCount = self.getFieldData('stock_on_list_duration', 1)
        stockTradeDayCount = stockTradeDayCount.astype(np.float32)
        stockTradeDayCount[stockTradeDayCount > 0] = 1
        stockTradeDayCount[stockTradeDayCount == 0] = np.nan
        ret = inputValue * stockTradeDayCount
        ret[np.isinf(ret)] = np.nan
        return ret

    def myRank(self, data, type):
        """

        将因子截面数据做排名返回

        :param data: np.array类型,因子截面数据的输入值

        :param type: char类型,降序(descend)、升序(ascend)

        :return: np.array类型,data的排名返回值

        """
        if type == '降序' or type == 'descend':
            rev = -1
        elif type == '升序' or type == 'ascend':
            rev = 1
        data_ = copy.deepcopy(data)
        data_ = np.array(data_)
        Site = np.where(~np.isnan(data_))
        data_[Site] = np.argsort(data_[Site] * rev)
        data_[Site] = np.argsort(data_[Site])

        return data_.reshape(1, -1)

    def mySort(self, data, type):
        """

        将因子排序下标返回

        :param data: np.array类型,因子截面数据的输入值

        :param type: char类型,降序(descend)、升序(ascend)

        :return: np.array类型,data的排名下标返回值

        """
        if type == '降序' or type == 'descend':
            rev = -1
        elif type == '升序' or type == 'ascend':
            rev = 1
        data_ = copy.deepcopy(data)
        Site = np.where(~np.isnan(data_))
        data_ = np.array(data_)
        data_[Site] = np.argsort(data_[Site] * rev)

        return data_.reshape(1, -1)

    def quoteCorrection(self, inputvalue):
        '''

        纠正getFieldDailyData获得数据列数错误用函数

        :param inputValue: np.array类型,输入的数据

        :return: np.array类型,列数正确的函数

        '''
        column_num = len(self.getAllData('stock_code'))
        value_num = inputvalue.shape[1]
        if column_num > value_num:
            ret = np.hstack(
                (inputvalue, np.nan *
                 np.zeros([inputvalue.shape[0], column_num - value_num])))
        elif column_num <= value_num:
            ret = inputvalue[:, :column_num]
        return ret

    def regForNeutralizeFactor(self, factor, list1):
        '''

        中性化因子用函数

        :param factor: 被中性化的因子,二维数组(1,)

        :param list: 包含中性化因子数组的列表,列表内部数据格式:二维数组(1,)

        :return: ndarray类型,回归后的残差,二维数组(1,)

        '''
        factor = factor.T
        neutralizeList = np.zeros((factor.shape[0], len(list1))) * np.nan
        result = np.zeros((1, factor.shape[0])) * np.nan
        for i in range(len(list1)):
            neutralizeList[:, i] = list1[i][0, :]
        y = factor
        x = neutralizeList
        for i in range(x.shape[1]):
            if i == 0:
                y_not_empty = np.where(~np.isnan(y))[0].tolist()
                x_not_empty = np.where(~np.isnan(x[:, i]))[0].tolist()
                not_empty = list(set(x_not_empty).intersection(set(y_not_empty)))
            else:
                y_not_empty = not_empty
                x_not_empty = np.where(~np.isnan(x[:, i]))[0].tolist()
                not_empty = list(set(x_not_empty).intersection(set(y_not_empty)))

        y = y[not_empty]
        x = x[not_empty]
        m = LinearRegression()
        m.fit(x, y)
        residual = y - m.predict(x)
        for i in range(len(not_empty)):
            result[0, not_empty[i]] = residual[i, 0]
        return result

    def myNeutralizeCalc(self, y, x):
        '''

        :param x:

        :param y:

        :return:

        '''
        fit_data = np.vstack((x, y))
        site = np.where(~np.isnan(np.sum(fit_data, axis=0)))[0]
        x_ = x[:, site]
        y_ = y[:, site]
        resid = np.nan * np.zeros(y.shape).reshape(1, -1)
        if x_.size and y_.size:
            m = LinearRegression()
            m.fit(x_.T, y_.T)
            resid[0, site] = (y_.T - m.predict(x_.T)).reshape(1, -1)
        return resid

    def getReportPeriodsList(self, modified):
        '''

        获取最新报告期列表用函数

        :param modified: bool类型,确定是否需要扩展

        :return: np.array类型,报告期数组

        '''
        report_periods_list = self.getFieldData('reportPeriodsList')
        report_periods_list = report_periods_list[~np.isnan(report_periods_list
                                                            )]
        report_periods_list = np.array(list(set(report_periods_list.tolist())))
        report_periods_list = np.flipud(np.sort(report_periods_list))

        if modified == False:
            return report_periods_list
        else:
            if report_periods_list[0] % 10000 == 1231:
                report_periods_list = np.insert(report_periods_list, 0,
                                                report_periods_list[0] + 9100)
            elif report_periods_list[0] % 10000 == 930:
                report_periods_list = np.insert(report_periods_list, 0,
                                                report_periods_list[0] + 301)
            elif report_periods_list[0] % 10000 == 630:
                report_periods_list = np.insert(report_periods_list, 0,
                                                report_periods_list[0] + 300)
            elif report_periods_list[0] % 10000 == 331:
                report_periods_list = np.insert(report_periods_list, 0,
                                                report_periods_list[0] + 299)
            return report_periods_list

    def getFinancialAllData(self, key):
        """

        导入数据包用函数

        :param key: char类型,数据包名

        :return: tuple类型,包含数据包数据值和数据名称的元组

        """
        if key in self.allData:
            return self.allData[key]

        npzFile = key + '.npz'

        for dataPath in self.dataPathList:
            if npzFile in os.listdir(dataPath):
                dataFile = dataPath + "\\\\" + npzFile
                break

        try:
            data = np.load(dataFile, allow_pickle=True)
        except:
            p.error_print(sys._getframe().f_code.co_filename,
                          sys._getframe().f_code.co_name,
                          "数据包导入失败!找不到数据包" + key + ",请更新数据包!")
        else:
            value = data['value']
            fieldName = data['fieldname']
            v = (value, fieldName)
            self.allData[key] = v
            return self.allData[key]

    def getFinancialFieldData(self, tableName, fieldName, reportDate):
        """

        获取金融数据

        :param tableName: char类型,数据包名称

        :param fieldName: char/list/tuple类型,数据包中具体数据名称

        :param reportDate: int类型,报告期

        :return: np.array类型,具体的金融数据

        """
        nextDate = self.getNextDate()
        tableData = self.getFinancialAllData(tableName)
        fieldData = tableData[0]
        fieldNameList = tableData[1]

        if isinstance(fieldName, str):
            try:
                site = np.where(fieldNameList == fieldName)[0][0]
            except:
                p.error_print(
                    sys._getframe().f_code.co_filename,
                    sys._getframe().f_code.co_name,
                    "在" + tableName + "数据包里找不到对应的" + fieldName + "字段!")

            else:
                fieldData = fieldData[:, [0, 1, 2, site]]

                stockCode = self.getStockCode()
                IA_ret = np.ones([1, len(stockCode)])

                fieldData = fieldData[np.where(
                    fieldData[:, 1] <= nextDate)[0], :]
                ret = np.nan * np.zeros([1, len(stockCode)])

                fieldData = fieldData[np.where(
                    fieldData[:, 2] == reportDate)[0], :]

                if fieldData.size == 0:
                    return ret
                else:
                    for i in range(len(stockCode)):
                        dataTemp = fieldData[np.where(
                            fieldData[:, 0] == stockCode[i])[0]]
                        if dataTemp.size == 0:
                            IA_ret[0, i] = np.nan
                            continue
                        if np.shape(dataTemp)[0] > 1:
                            dataTemp = dataTemp[np.argsort(dataTemp[:, 1])]
                        ret[0, i] = dataTemp[-1, -1]
                if tableName != 'ASHARE_PROFITNOTICE':
                    ret[np.where(np.isnan(ret))] = 0
                    ret = ret * IA_ret

        elif isinstance(fieldName, (np.ndarray, list, tuple)):
            try:
                site = list(
                    map(lambda x: np.where(fieldNameList == x)[0][0],
                        fieldName))
            except:
                var_str = fieldName[0]
                for i in list(range(1, len(fieldName))):
                    var_str += ',' + fieldName[i]
                p.error_print(sys._getframe().f_code.co_filename,
                              sys._getframe().f_code.co_name,
                              "在" + tableName + "数据包里找不到对应的" + var_str + "字段!")
            else:
                tmp = [0, 1, 2]
                tmp.extend(site)
                fieldData = fieldData[:, tmp]

                stockCode = self.getStockCode()
                IA_ret = np.ones([1, len(stockCode)])

                fieldData = fieldData[np.where(
                    fieldData[:, 1] <= nextDate)[0], :]

                ret = np.nan * np.zeros([len(site), len(stockCode)])

                fieldData = fieldData[np.where(
                    fieldData[:, 2] == reportDate)[0], :]

                if fieldData.size == 0:
                    return ret
                else:
                    for i in list(range(len(stockCode))):
                        dataTemp = fieldData[np.where(
                            fieldData[:, 0] == stockCode[i])[0]]
                        if dataTemp.size == 0:
                            IA_ret[0, i] = np.nan
                            continue
                        if np.shape(dataTemp)[0] > 1:
                            dataTemp = dataTemp[np.argsort(dataTemp[:, 1])]
                        for j in list(range(3, np.shape(dataTemp)[1])):
                            ret[j - 3, i] = dataTemp[-1, j]
                if tableName != 'ASHARE_PROFITNOTICE':
                    ret[np.where(np.isnan(ret))] = 0
                    ret = ret * IA_ret
        return ret

    def getFinancialFieldDataMatrix(self, tablename, fieldname,

                                    report_periods_list, datalen):
        '''

        获取财务数据矩阵用函数

        :param tablename: char类型,表名

        :param fieldname: char类型,字段名

        :param report_periods_list: 1darray数组,报告期列表

        :param datalen: int类型,数据行数

        :return: np.array类型,财务数据矩阵

        '''
        ret = np.nan * np.zeros((int(datalen), len(self.getStockList())))
        for i in range(datalen):
            try:
                ret[i] = self.getFinancialFieldData(tablename, fieldname,
                                                    report_periods_list[i])
            except:
                p.error_print(sys._getframe().f_code.co_filename,
                              sys._getframe().f_code.co_name,
                              "数据包导入失败!找不到数据包" + tablename + ",请更新数据包!")
        return ret

    def getFinancialFieldDataMatrixModified(self, value, tablename, fieldname,

                                            report_periods_list):
        '''

        注意:此函数对value进行操作,返回的是value的修正值,内存占用不变

        获取财务数据修正矩阵用函数

        :param tablename: char类型,修正表名

        :param fieldname: char类型,具体修正字段名

        :param report_periods_list: 1darray数组,报告期列表

        :return: np.array类型,财务数据矩阵

        '''
        datalen = min(3, value.shape[0])
        if fieldname != 'NET_PROFIT_EXCL_MIN_INT_INC':
            ret = np.nan * np.zeros((datalen, len(self.getStockList())))
            for i in range(datalen):
                try:
                    ret[i] = self.getFinancialFieldData(tablename, fieldname,
                                                        report_periods_list[i])
                except:
                    p.error_print(sys._getframe().f_code.co_filename,
                                  sys._getframe().f_code.co_name,
                                  "逐行报告期数据提取失败!")
            value[:datalen][np.where(np.isnan(
                value[:datalen]))] = ret[np.where(np.isnan(value[:datalen]))]
            return value
        else:
            ret_1 = np.nan * np.zeros((datalen, len(self.getStockList())))
            for i in range(datalen):
                try:
                    ret_1[i] = self.getFinancialFieldData(tablename, fieldname,
                                                          report_periods_list[i])
                except:
                    p.error_print(sys._getframe().f_code.co_filename,
                                  sys._getframe().f_code.co_name,
                                  "逐行报告期数据提取失败!")
            ret_2 = np.nan * np.zeros((datalen, len(self.getStockList())))
            for i in range(datalen):
                try:
                    upDown = self.getFinancialFieldData('ASHARE_PROFITNOTICE', [
                        'S_PROFITNOTICE_NETPROFITMIN',
                        'S_PROFITNOTICE_NETPROFITMAX'
                    ], report_periods_list[i]) * 10000
                    ret_2[i] = np.nanmean(upDown, axis=0)
                except:
                    p.error_print(sys._getframe().f_code.co_filename,
                                  sys._getframe().f_code.co_name,
                                  "字段为净利润,业绩预告逐行报告期数据提取失败!")
            value[:datalen][np.where(np.isnan(
                value[:datalen]))] = ret_1[np.where(np.isnan(value[:datalen]))]
            value[:datalen][np.where(np.isnan(
                value[:datalen]))] = ret_2[np.where(np.isnan(value[:datalen]))]
            return value

    def getFinancialFieldDataMatrixModified_gta(self, value, tablename, fieldname,

                                                report_periods_list):
        '''

        函数

        注意:此函数对value进行操作,返回的是value的修正值,内存占用不变

        获取财务数据修正矩阵用函数

        :param tablename: char类型,修正表名

        :param fieldname: char类型,具体修正字段名

        :param report_periods_list: 1darray数组,报告期列表

        :return: np.array类型,财务数据矩阵

        '''

        dic_fieldname = {'B0011': 'GROSSREVENUE', 'B0013': 'OPERATEPROFIT', 'B001': 'TOTALPROFIT', 'A001': 'ASSET'
            , 'A0031': 'EQUITYPARENT', 'A003': 'EQUITY', 'B0024': 'PROFITPARENT', 'B001101': 'GROSSREVENUE',
                         'B002': 'PROFIT'}
        fieldname = dic_fieldname[fieldname]
        datalen = min(3, value.shape[0])
        if fieldname != 'PROFITPARENT' and 'PROFIT':
            ret = np.nan * np.zeros((datalen, len(self.getStockList())))
            for i in range(datalen):
                try:
                    ret[i] = self.getFinancialFieldData(tablename, fieldname,
                                                        report_periods_list[i])
                except:
                    p.error_print(sys._getframe().f_code.co_filename,
                                  sys._getframe().f_code.co_name,
                                  "逐行报告期数据提取失败!")
            value[:datalen][np.where(np.isnan(
                value[:datalen]))] = ret[np.where(np.isnan(value[:datalen]))]
            return value
        elif fieldname == 'PROFITPARENT':  # 归母净利润
            ret_1 = np.nan * np.zeros((datalen, len(self.getStockList())))
            for i in range(datalen):
                try:
                    ret_1[i] = self.getFinancialFieldData(tablename, fieldname,
                                                          report_periods_list[i])
                except:
                    p.error_print(sys._getframe().f_code.co_filename,
                                  sys._getframe().f_code.co_name,
                                  "逐行报告期数据提取失败!")
            ret_2 = np.nan * np.zeros((datalen, len(self.getStockList())))
            for i in range(datalen):
                try:
                    upDown = self.getFinancialFieldData('STK_FIN_FORECFIN', [
                        'PROFITPARENTFLOOR',
                        'PROFITPARENTCEILING'
                    ], report_periods_list[i])
                    ret_2[i] = np.nanmean(upDown, axis=0)
                except:
                    p.error_print(sys._getframe().f_code.co_filename,
                                  sys._getframe().f_code.co_name,
                                  "字段为归母净利润,业绩预告逐行报告期数据提取失败!")
            value[:datalen][np.where(np.isnan(
                value[:datalen]))] = ret_1[np.where(np.isnan(value[:datalen]))]
            value[:datalen][np.where(np.isnan(
                value[:datalen]))] = ret_2[np.where(np.isnan(value[:datalen]))]
            return value
        elif fieldname == 'PROFIT':  # 净利润
            ret_1 = np.nan * np.zeros((datalen, len(self.getStockList())))
            for i in range(datalen):
                try:
                    ret_1[i] = self.getFinancialFieldData(tablename, fieldname,
                                                          report_periods_list[i])
                except:
                    p.error_print(sys._getframe().f_code.co_filename,
                                  sys._getframe().f_code.co_name,
                                  "逐行报告期数据提取失败!")
            ret_2 = np.nan * np.zeros((datalen, len(self.getStockList())))
            for i in range(datalen):
                try:
                    upDown = self.getFinancialFieldData('STK_FIN_FORECFIN', [
                        'PROFITFLOOR',
                        'PROFITCEILING'
                    ], report_periods_list[i])
                    ret_2[i] = np.nanmean(upDown, axis=0)
                except:
                    p.error_print(sys._getframe().f_code.co_filename,
                                  sys._getframe().f_code.co_name,
                                  "字段为净利润,业绩预告逐行报告期数据提取失败!")
            value[:datalen][np.where(np.isnan(
                value[:datalen]))] = ret_1[np.where(np.isnan(value[:datalen]))]
            value[:datalen][np.where(np.isnan(
                value[:datalen]))] = ret_2[np.where(np.isnan(value[:datalen]))]
            return value

    def getFinancialFieldDataMatrix_Q(self, value, report_periods_list):
        '''

        获取财务单季度数据矩阵用函数

        :param value: ndarray类型,getFieldDataMatrix获得的财务数据矩阵

        :param report_periods_list: 1darray数组,报告期列表

        :return: np.array类型,财务单季度数据矩阵

        '''
        datalen = value.shape[0]
        ret = np.nan * np.zeros((datalen - 1, len(self.getStockList())))
        for i in range(datalen - 1):
            try:
                if report_periods_list[i] % 10000 == 331:
                    ret[i] = value[i]
                else:
                    ret[i] = value[i] - value[i + 1]
            except:
                p.error_print(sys._getframe().f_code.co_filename,
                              sys._getframe().f_code.co_name,
                              "财务数据单季度计算失败!")
        return ret

    def getFinancialFieldDataMatrix_TTM(self, value, n):
        '''

        获取财务TTM数据矩阵用函数

        :param value: ndarray类型,getFieldDataMatrix_Q获得的财务单季度数据矩阵

        :param n: int类型,期数,默认为4

        :return: np.array类型,财务TTM数据矩阵

        '''
        datalen = value.shape[0]
        ret = np.nan * np.zeros((datalen - (n - 1), len(self.getStockList())))

        for i in range(datalen - (n - 1)):
            try:
                ret[i] = np.sum(value[i:(i + n), :], axis=0)
            except:
                p.error_print(sys._getframe().f_code.co_filename,
                              sys._getframe().f_code.co_name,
                              "财务数据TTM计算失败!")
        return ret

    def getFirstNonnan(arr, axis, invalid_val):
        '''

        获得矩阵每行或者每列第一个非空值所在位置用函数

        :param arr: ndarray类型

        :param axis: 0/1 0为每列提取,1为每行提取

        :param invalid_val: int/float,若行/列全空返回的数字

        :return: 1darray数组

        '''
        mask = ~np.isnan(arr)
        return np.where(mask.any(axis=axis), mask.argmax(axis=axis), invalid_val)

    def getNewestData(arr):
        '''

        获取矩阵每一列第一个非空值用函数

        :param arr: ndarray类型

        :return: ndarray类型,一行矩阵

        '''
        ret = np.nan * np.zeros((1, arr.shape[1]))
        for i in range(arr.shape[0]):
            ret[0, np.where(np.isnan(ret[0]))[0]] = arr[i][np.where(np.isnan(ret[0]))[0]]
        return ret

    def getGrowthData(self, factor_list, dataLen, type):
        '''

        计算growth因子用函数

        :param factor_list: ndarray类型,growth因子基础值矩阵

        :param dataLen: int类型,默认为1,前后两期的间隔

        :param type: char类型,默认为rate,计算的growth因子种类

        :return: ndarray类型,一行矩阵

        '''
        factor_list = np.flipud(factor_list)
        if type == 'rate':
            growth = (factor_list[dataLen:] - factor_list[:-dataLen]) / np.abs(factor_list[:-dataLen])
        elif type == 'value':
            growth = factor_list[dataLen:] - factor_list[:-dataLen]
            growth = growth.astype('float')
        else:
            p.warning_print(sys._getframe().f_code.co_filename,
                            sys._getframe().f_code.co_name, "传入的type类型有误")
            return None

        growth[np.where(growth == np.inf)] = np.nan
        growth[np.where(growth == -np.inf)] = np.nan
        growth = np.flipud(growth)
        growth = self.getNewestData(growth)
        return growth