forked from phonegapX/alphasickle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
raw_data_fetch.py
1197 lines (1125 loc) · 78 KB
/
raw_data_fetch.py
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
# -*- coding: utf-8 -*-
"""
阿尔法收割者
Project: alphasickle
Author: Moses
E-mail: [email protected]
"""
import os
import numpy as np
import pandas as pd
import tushare as ts
import pymysql
from retrying import retry
from functools import wraps
from factor_generate import FactorGenerater
try:
basestring
except NameError:
basestring = str
#打印能完整显示
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
pd.set_option('display.width', 50000)
pd.set_option('max_colwidth', 1000)
class RawDataFetcher(FactorGenerater):
def _get_month_end(self, date):
import calendar
import pandas.tseries.offsets as toffsets
_, days = calendar.monthrange(date.year, date.month)
if date.day == days:
return date
else:
return date + toffsets.MonthEnd(n=1)
@retry(stop_max_attempt_number=500, wait_random_min=1000, wait_random_max=2000)
def ensure_data(self, func, save_dir, start_dt='20010101', end_dt='20201231'):
""" 确保按交易日获取数据
"""
tmp_dir = os.path.join(self.root, save_dir)
dl = [pd.to_datetime(name.split(".")[0]) for name in os.listdir(tmp_dir)]
dl = sorted(dl)
s = pd.to_datetime(start_dt)
e = pd.to_datetime(end_dt)
tdays = pd.Series(self.tradedays, index=self.tradedays)
tdays = tdays[(tdays>=s)&(tdays<=e)]
tdays = tdays.index.tolist()
for tday in tdays:
if tday in dl: continue
t = tday.strftime("%Y%m%d")
datdf = func(t)
path = os.path.join(tmp_dir, t+".csv")
datdf.to_csv(path, encoding='gbk')
print(t+".csv write ok !!!!!")
@retry(stop_max_attempt_number=500, wait_random_min=1000, wait_random_max=2000)
def ensure_data_by_q(self, func, save_dir, start_dt='20010101', end_dt='20201231'):
""" 确保按季度获取数据
"""
tmp_dir = os.path.join(self.root, save_dir)
dl = [pd.to_datetime(name.split(".")[0]) for name in os.listdir(tmp_dir)]
dl = sorted(dl)
if len(dl) > 3:
dl = dl[0:len(dl)-3] #已经存在的最后三个季度数据重新下载
s = pd.to_datetime(start_dt)
e = pd.to_datetime(end_dt)
qdates = pd.date_range(start=s, end=e, freq='Q')
qdates = qdates.tolist()
for tday in qdates:
if tday in dl: continue
t = tday.strftime("%Y%m%d")
datdf = func(period=t)
path = os.path.join(tmp_dir, t+".csv")
datdf.to_csv(path, encoding='gbk')
print(t+".csv write ok !!!!!")
def create_indicator(self, raw_data_dir, raw_data_field, indicator_name):
''' 主要用于通过日频数据创建日频指标
'''
tmp_dir = os.path.join(self.root, raw_data_dir)
tdays = [pd.to_datetime(f.split(".")[0]) for f in os.listdir(tmp_dir)]
tdays = sorted(tdays)
all_stocks_info = self.meta
df = pd.DataFrame(index=all_stocks_info.index, columns=tdays)
for f in os.listdir(tmp_dir):
tday = pd.to_datetime(f.split(".")[0])
dat = pd.read_csv(os.path.join(tmp_dir, f), index_col=['ts_code'], engine='python', encoding='gbk')
df[tday] = dat[raw_data_field]
print(tday)
df = df.dropna(how='all') #删掉全为空的一行
diff = df.index.difference(all_stocks_info.index) #删除没在股票基础列表中多余的股票行
df = df.drop(labels=diff)
self.close_file(df, indicator_name)
def create_indicator_m_by_d(self, raw_data_dir, raw_data_field, indicator_name, start_dt='20010101', end_dt='20201231'):
''' 通过日频数据创建月频指标
'''
tmp_dir = os.path.join(self.root, raw_data_dir)
s = pd.to_datetime(start_dt)
e = pd.to_datetime(end_dt)
new_tdays = self._get_trade_days(s, e, "M")
new_caldays = [self._get_month_end(tdate) for tdate in new_tdays]
all_stocks_info = self.meta
df = pd.DataFrame(index=all_stocks_info.index, columns=new_caldays)
for tday in new_tdays:
name = tday.strftime("%Y%m%d")
dat = pd.read_csv(os.path.join(tmp_dir, name+".csv"), index_col=['ts_code'], engine='python', encoding='gbk')
caldate = self.month_map[tday]
df[caldate] = dat[raw_data_field]
print(caldate)
df = df.dropna(how='all') #删掉全为空的一行
self.close_file(df, indicator_name)
def create_indicator_m_by_d_ex(self, raw_data_dir, raw_data_field, indicator_name, start_dt='20010101', end_dt='20201231'):
''' 通过日频数据创建月频指标
'''
self.create_indicator(raw_data_dir, raw_data_field, indicator_name)
datdf = getattr(self, indicator_name, None)
datdf = self.preprocess(datdf)
self.close_file(datdf, indicator_name)
#
s = pd.to_datetime(start_dt)
e = pd.to_datetime(end_dt)
new_tdays = self._get_trade_days(s, e, "M")
new_caldays = [self._get_month_end(tdate) for tdate in new_tdays]
all_stocks_info = self.meta
df = pd.DataFrame(index=all_stocks_info.index, columns=new_caldays)
for tday in new_tdays:
caldate = self.month_map[tday]
df[caldate] = datdf[tday]
print(caldate)
df = df.dropna(how='all') #删掉全为空的一行
self.close_file(df, indicator_name+'_m')
def create_indicator_m_by_q(self, raw_data_dir, raw_data_field, indicator_name, start_dt='20010101', end_dt='20201231'):
''' 通过季频数据创建月频指标,主要用于财报数据处理
'''
s = pd.to_datetime(start_dt) #统计周期开始
e = pd.to_datetime(end_dt) #统计周期结束
qdays = pd.date_range(start=s, end=e, freq="Q") #每个季度最后一天
mdays = pd.date_range(start=s, end=e, freq="M") #每个月最后一天
all_stocks_info = self.meta
tmp_dir = os.path.join(self.root, raw_data_dir) #财务指标表
panel = {}
for d in qdays: #每季度最后一天
name = d.strftime("%Y%m%d")
dat = pd.read_csv(os.path.join(tmp_dir, name+".csv"), index_col=['ts_code'], engine='python', encoding='gbk', parse_dates=['ann_date','end_date'])
diff = dat.index.difference(all_stocks_info.index) #删除没在股票基础列表中多余的股票行
dat = dat.drop(labels=diff)
dat = dat[~dat.index.duplicated(keep='last')] #财务数据中同一只股票可能会有重复的记录,删除多余重复的
del dat['Unnamed: 0']
panel[d] = dat
print(d)
datpanel = pd.Panel(panel)
datpanel = datpanel.to_frame().stack().unstack(level=(0,1)) #貌似某些情况下会有BUG,有索引但是没数据
#开始计算结果指标(月频),在每个时间截面逐个处理每只股票
df = pd.DataFrame(index=all_stocks_info.index, columns=mdays)
for d in df.columns: #每月最后一天
for stock in df.index: #每只股票
try:
datdf = datpanel[stock]
datdf = datdf.loc[datdf['ann_date']<d] #站在当前时间节点,每只股票所能看到的最近一期财务指标数据(不同股票财报发布时间不一定相同)
df.at[stock, d] = datdf.iloc[-1].at[raw_data_field] #取已经发布最近一期财报数据指定字段进行赋值
#print(stock)
except:
pass
print(d)
df = df.dropna(how='all') #删掉全为空的一行
self.close_file(df, indicator_name)
def create_indicator_m_by_q_ex(self, raw_data_dir, raw_data_field, indicator_name, start_dt='20010101', end_dt='20201231'):
''' 通过季频数据创建月频指标,主要用于财报数据处理
'''
s = pd.to_datetime(start_dt) #统计周期开始
e = pd.to_datetime(end_dt) #统计周期结束
qdays = pd.date_range(start=s, end=e, freq="Q") #每个季度最后一天
mdays = pd.date_range(start=s, end=e, freq="M") #每个月最后一天
all_stocks_info = self.meta
tmp_dir = os.path.join(self.root, raw_data_dir) #财务指标表
panel = {}
for d in qdays: #每季度最后一天
name = d.strftime("%Y%m%d")
dat = pd.read_csv(os.path.join(tmp_dir, name+".csv"), index_col=['ts_code'], engine='python', encoding='gbk', parse_dates=['ann_date','end_date'])
diff = dat.index.difference(all_stocks_info.index) #删除没在股票基础列表中多余的股票行
dat = dat.drop(labels=diff)
dat = dat[~dat.index.duplicated(keep='last')] #财务数据中同一只股票可能会有重复的记录,删除多余重复的
del dat['Unnamed: 0']
panel[d] = dat
print(d)
datpanel = pd.Panel(panel)
datpanel = datpanel.swapaxes(0, 1)
#开始计算结果指标(月频),在每个时间截面逐个处理每只股票
df = pd.DataFrame(index=all_stocks_info.index, columns=mdays)
for d in df.columns: #每月最后一天
for stock in df.index: #每只股票
try:
datdf = datpanel.loc[stock]
datdf = datdf.loc[datdf['ann_date']<d] #站在当前时间节点,每只股票所能看到的最近一期财务指标数据(不同股票财报发布时间不一定相同)
df.at[stock, d] = datdf.iloc[-1].at[raw_data_field] #取已经发布最近一期财报数据指定字段进行赋值
#print(stock)
except:
pass
print(d)
df = df.dropna(how='all') #删掉全为空的一行
self.close_file(df, indicator_name)
def _align_element(self, df1, df2):
''' 对齐股票和时间
'''
row_index = sorted(df1.index.intersection(df2.index))
col_index = sorted(df1.columns.intersection(df2.columns))
return df1.loc[row_index, col_index], df2.loc[row_index, col_index]
def create_daily_quote_indicators(self):
'''
'''
#-------------------------------------------------------------
#创建一些行情指标
self.create_indicator("__temp_daily__", "S_DQ_ADJFACTOR", "adjfactor")
adjfactor = self.preprocess(self.adjfactor)
self.close_file(adjfactor, 'adjfactor')
self.create_indicator("__temp_daily__", "amount", "amt")
amt = self.amt / 10 #默认每单位千元,转换为每单位万元
amt = self.preprocess(amt, suspend_days_process=True, val=0)
self.close_file(amt, 'amt')
self.create_indicator("__temp_daily__", "close", "close")
close = self.preprocess(self.close)
self.close_file(close, 'close')
close, adjfactor = self._align_element(self.close, self.adjfactor)
hfq_close = close * adjfactor
self.close_file(hfq_close, 'hfq_close') #后复权收盘价
self.create_indicator("__temp_daily__", "pct_chg", "pct_chg")
pct_chg = self.preprocess(self.pct_chg, suspend_days_process=True, val=0)
self.close_file(pct_chg, 'pct_chg')
#-------------------------------------------------------------
#将三大指数的数据给补上
pct_chg = self.pct_chg
close = self.close
hfq_close = self.hfq_close
benchmarks = ['000001.SH', '000300.SH', '000905.SH'] #上证综指,沪深300,中证500
tmp_dir = os.path.join(self.root, "__temp_index_daily__")
for name in benchmarks:
dat = pd.read_csv(os.path.join(tmp_dir, name+".csv"), index_col=[2], engine='python', encoding='gbk', parse_dates=['trade_date'])
pct_chg.loc[name] = dat['pct_chg'][pct_chg.columns]
close.loc[name] = dat['close'][close.columns]
hfq_close.loc[name] = dat['close'][hfq_close.columns]
#更新数据
pct_chg = pct_chg / 100
self.close_file(pct_chg, 'pct_chg')
self.close_file(close, 'close')
self.close_file(hfq_close, 'hfq_close')
#-------------------------------------------------------------
#生成周期为1,3,6,12月收益率
s = pd.to_datetime('20010101') #统计周期开始
e = pd.to_datetime('20201231') #统计周期结束
tdays_be_month = self.trade_days_begin_end_of_month
tdays_be_month = tdays_be_month[(tdays_be_month>=s)&(tdays_be_month<=e)].dropna(how='all')
months_end = tdays_be_month.index
hfq_close = self.hfq_close
#***pct_chg_M
pct_chg_M = pd.DataFrame()
for m_end_date in months_end:
m_start_date = tdays_be_month.loc[m_end_date].values[0]
pct_chg_M[self.month_map.loc[m_end_date]] = hfq_close[m_end_date] / hfq_close[m_start_date] - 1
self.close_file(pct_chg_M, 'pct_chg_M')
#pct_chg_Nm
for period in (1,3,6,12):
pct_chg_Nm = pd.DataFrame()
if period != 1:
for m_end_date in months_end[::-1]:
try:
start_date_before_n_period = tdays_be_month.loc[self._get_date(m_end_date, -period+1, months_end)].values[0]
s = hfq_close[m_end_date] / hfq_close[start_date_before_n_period] - 1
pct_chg_Nm[self.month_map[m_end_date]] = s
except KeyError:
print(m_end_date)
break
else:
pct_chg_Nm = getattr(self, f'pct_chg_M', None)
self.close_file(pct_chg_Nm, f"pctchg_{period}M")
print(f'pct_chg_{period}M updated.')
def create_daily_basic_indicators(self):
'''
'''
self.create_indicator("__temp_daily_basic__", "turnover_rate", "turn")
turn = self.turn / 100
turn = self.preprocess(turn, suspend_days_process=True)
self.close_file(turn, "turn")
self.create_indicator("__temp_daily_basic__", "total_mv", "mkt_cap_ard")
mkt_cap_ard = self.preprocess(self.mkt_cap_ard)
self.close_file(mkt_cap_ard, "mkt_cap_ard")
def preprocess(self, datdf, suspend_days_process=False, val=np.nan):
''' 数据预处理
'''
datdf = datdf.copy()
datdf = datdf.fillna(method='ffill', axis=1).fillna(method='bfill', axis=1)
row_index, col_index = datdf.index, datdf.columns
liststatus = self.listday_matrix.loc[row_index, col_index]
cond = (liststatus==1)
datdf = datdf.where(cond) #将不是上市日的数值替换为nan
if suspend_days_process:
tradestatus = self.trade_status.loc[row_index, col_index]
cond = (liststatus==1) & (tradestatus==0)
datdf = datdf.where(~cond, val) #将上市但停牌的数值设为指定值
return datdf
class TushareFetcher(RawDataFetcher):
def __init__(self):
self.pro = ts.pro_api('x')
super().__init__(using_fetch=True)
def fetch_meta_data(self):
""" 股票基础信息
"""
df_list = []
df = self.pro.stock_basic(exchange='', fields='ts_code,name,list_date,delist_date')
df_list.append(df)
df = self.pro.stock_basic(exchange='', fields='ts_code,name,list_date,delist_date', list_status='D')
df_list.append(df)
df = self.pro.stock_basic(exchange='', fields='ts_code,name,list_date,delist_date', list_status='P')
df_list.append(df)
df = pd.concat(df_list)
df = df.rename(columns={"list_date":"ipo_date"})
df = df.rename(columns={'name':'sec_name'})
df = df.rename(columns={"ts_code":"code"})
df.drop_duplicates(subset=['code'], keep='first', inplace=True)
df.sort_values(by=['ipo_date'], inplace=True)
#print(pd.to_datetime(df['ipo_date']))
#df.reset_index(drop=True, inplace=True)
df.set_index(['code'], inplace=True)
self.close_file(df, 'meta')
def fetch_trade_day(self):
""" 交易日列表
"""
df = self.pro.trade_cal(is_open='1')
df = df[['cal_date','is_open']]
df = df.rename(columns={"cal_date":"tradedays"})
df.set_index(['tradedays'], inplace=True)
self.close_file(df, 'tradedays')
def fetch_month_map(self):
""" 每月最后一个交易日和每月最后一个日历日的映射表
"""
tdays = self.tradedays
s_dates = pd.Series(tdays, index=tdays)
func_last = lambda ser: ser.iat[-1]
new_dates = s_dates.resample('M').apply(func_last)
month_map = new_dates.to_frame(name='trade_date')
month_map.index.name = 'calendar_date'
month_map.reset_index(inplace=True)
month_map.set_index(['trade_date'], inplace=True)
self.close_file(month_map, 'month_map')
#------------------------------------------------------------------------------------
#日数据
def daily(self, t):
return self.pro.daily(trade_date=t)
def suspend_d(self, t):
return self.pro.suspend_d(trade_date=t)
def limit_list(self, t):
return self.pro.limit_list(trade_date=t)
def adj_factor(self, t):
return self.pro.adj_factor(trade_date=t)
def daily_basic(self, t):
return self.pro.daily_basic(trade_date=t)
def moneyflow(self, t):
return self.pro.moneyflow(trade_date=t)
#------------------------------------------------------------------------------------
def segment_op(limit, _max):
""" 分段获取数据
"""
def segment_op_(f):
#
@wraps(f)
def wrapper(*args, **kwargs):
dfs = []
for i in range(0, _max, limit):
kwargs['offset'] = i
df = f(*args, **kwargs)
if len(df) < limit:
if len(df) > 0:
dfs.append(df)
break
df = df.iloc[0:limit]
dfs.append(df)
df = pd.concat(dfs, ignore_index=True)
return df
#
return wrapper
#
return segment_op_
#------------------------------------------------------------------------------------
#季度数据
@segment_op(limit=5000, _max=100000)
def fina_indicator(self, *args, **kwargs):
fields = '''ts_code,
ann_date,
end_date,
eps,
dt_eps,
total_revenue_ps,
revenue_ps,
capital_rese_ps,
surplus_rese_ps,
undist_profit_ps,
extra_item,
profit_dedt,
gross_margin,
current_ratio,
quick_ratio,
cash_ratio,
invturn_days,
arturn_days,
inv_turn,
ar_turn,
ca_turn,
fa_turn,
assets_turn,
op_income,
valuechange_income,
interst_income,
daa,
ebit,
ebitda,
fcff,
fcfe,
current_exint,
noncurrent_exint,
interestdebt,
netdebt,
tangible_asset,
working_capital,
networking_capital,
invest_capital,
retained_earnings,
diluted2_eps,
bps,
ocfps,
retainedps,
cfps,
ebit_ps,
fcff_ps,
fcfe_ps,
netprofit_margin,
grossprofit_margin,
cogs_of_sales,
expense_of_sales,
profit_to_gr,
saleexp_to_gr,
adminexp_of_gr,
finaexp_of_gr,
impai_ttm,
gc_of_gr,
op_of_gr,
ebit_of_gr,
roe,
roe_waa,
roe_dt,
roa,
npta,
roic,
roe_yearly,
roa2_yearly,
roe_avg,
opincome_of_ebt,
investincome_of_ebt,
n_op_profit_of_ebt,
tax_to_ebt,
dtprofit_to_profit,
salescash_to_or,
ocf_to_or,
ocf_to_opincome,
capitalized_to_da,
debt_to_assets,
assets_to_eqt,
dp_assets_to_eqt,
ca_to_assets,
nca_to_assets,
tbassets_to_totalassets,
int_to_talcap,
eqt_to_talcapital,
currentdebt_to_debt,
longdeb_to_debt,
ocf_to_shortdebt,
debt_to_eqt,
eqt_to_debt,
eqt_to_interestdebt,
tangibleasset_to_debt,
tangasset_to_intdebt,
tangibleasset_to_netdebt,
ocf_to_debt,
ocf_to_interestdebt,
ocf_to_netdebt,
ebit_to_interest,
longdebt_to_workingcapital,
ebitda_to_debt,
turn_days,
roa_yearly,
roa_dp,
fixed_assets,
profit_prefin_exp,
non_op_profit,
op_to_ebt,
nop_to_ebt,
ocf_to_profit,
cash_to_liqdebt,
cash_to_liqdebt_withinterest,
op_to_liqdebt,
op_to_debt,
roic_yearly,
total_fa_trun,
profit_to_op,
q_opincome,
q_investincome,
q_dtprofit,
q_eps,
q_netprofit_margin,
q_gsprofit_margin,
q_exp_to_sales,
q_profit_to_gr,
q_saleexp_to_gr,
q_adminexp_to_gr,
q_finaexp_to_gr,
q_impair_to_gr_ttm,
q_gc_to_gr,
q_op_to_gr,
q_roe,
q_dt_roe,
q_npta,
q_opincome_to_ebt,
q_investincome_to_ebt,
q_dtprofit_to_profit,
q_salescash_to_or,
q_ocf_to_sales,
q_ocf_to_or,
basic_eps_yoy,
dt_eps_yoy,
cfps_yoy,
op_yoy,
ebt_yoy,
netprofit_yoy,
dt_netprofit_yoy,
ocf_yoy,
roe_yoy,
bps_yoy,
assets_yoy,
eqt_yoy,
tr_yoy,
or_yoy,
q_gr_yoy,
q_gr_qoq,
q_sales_yoy,
q_sales_qoq,
q_op_yoy,
q_op_qoq,
q_profit_yoy,
q_profit_qoq,
q_netprofit_yoy,
q_netprofit_qoq,
equity_yoy,
rd_exp,
update_flag'''
kwargs['fields'] = fields
return self.pro.fina_indicator_vip(*args, **kwargs)
@segment_op(limit=5000, _max=100000)
def income(self, *args, **kwargs):
return self.pro.income_vip(*args, **kwargs)
@segment_op(limit=5000, _max=100000)
def balancesheet(self, *args, **kwargs):
return self.pro.balancesheet_vip(*args, **kwargs)
@segment_op(limit=5000, _max=100000)
def cashflow(self, *args, **kwargs):
return self.pro.cashflow_vip(*args, **kwargs)
#------------------------------------------------------------------------------------
#指数日行情
def index_daily(self):
index_list = ['000001.SH', '000300.SH', '000905.SH']
tmp_dir = os.path.join(self.root, "__temp_index_daily__")
for i in index_list:
df = self.pro.index_daily(ts_code=i)
path = os.path.join(tmp_dir, i+".csv")
df.to_csv(path, encoding='gbk')
print(i+".csv write ok !!!!!")
#------------------------------------------------------------------------------------
'''
通过上面的函数,会从tushare把原始数据下载并保存到本地raw_data目录中
raw_data/src目录: 股票基础列表,成交日列表
raw_data/__temp_adj_factor__目录: 复权因子表(日频数据)
raw_data/__temp_daily__目录: 每日行情表(日频数据)
raw_data/__temp_daily_basic__目录: 每日指标表(日频数据)
raw_data/__temp_limit_list__目录: 每日涨跌停表(日频数据)
raw_data/__temp_moneyflow__目录: 每日个股资金流向表(日频数据)
raw_data/__temp_suspend_d__目录: 每日停复牌表(日频数据)
raw_data/__temp_index_daily__目录: 每日指数行情(日频数据)
raw_data/__temp_balancesheet__目录: 资产负债表(季频数据)
raw_data/__temp_cashflow__目录: 现金流量表(季频数据)
raw_data/__temp_fina_indicator__目录: 财务指标表(季频数据)
raw_data/__temp_income__目录: 利润表(季频数据)
下面开始的函数主要就是通过上面这些原始数据生成一些月频基础指标,主要有三种形式:
1. 通过 <日频数据> 生成 <月频指标>
2. 通过 <季频数据> 生成 <月频指标>
3. 通过 <日频数据>和<季频数据> 混合生成 <月频指标>
'''
def create_listday_matrix(self):
''' 股票上市存续周期日矩阵
'''
all_stocks_info = self.meta
trade_days = self.tradedays
def if_listed(series):
nonlocal all_stocks_info
code = series.name
ipo_date = all_stocks_info.at[code, 'ipo_date']
delist_date = all_stocks_info.at[code, 'delist_date']
daterange = series.index
if delist_date is pd.NaT:
res = np.where(daterange >= ipo_date, 1, 0)
else:
res = np.where(daterange < ipo_date, 0, np.where(daterange <= delist_date, 1, 0))
return pd.Series(res, index=series.index)
listday_dat = pd.DataFrame(index=all_stocks_info.index, columns=trade_days)
listday_dat = listday_dat.apply(if_listed, axis=1)
self.close_file(listday_dat, 'listday_matrix')
def create_month_tdays_begin_end(self, latest_month_end_tradeday=None):
''' 每月第一个和最后一个交易日映射
'''
tdays = self.tradedays
months_start = tdays[0:1] + list(after_d for before_d, after_d in zip(tdays[:-1], tdays[1:]) if before_d.month != after_d.month)
months_end = list(before_d for before_d, after_d in zip(tdays[:-1], tdays[1:]) if before_d.month != after_d.month) + tdays[-1:]
if latest_month_end_tradeday is None:
latest_month_end_tradeday = self.month_map.index[-1]
if months_end[-1] > latest_month_end_tradeday:
months_start, months_end = months_start[:-1], months_end[:-1]
trade_days_be_month = pd.DataFrame(months_end, index=months_start, columns=['month_end'])
trade_days_be_month.index.name = 'month_start'
self.close_file(trade_days_be_month, 'trade_days_begin_end_of_month')
def create_trade_status(self):
''' 股票停复牌状态
'''
tmp_dir = os.path.join(self.root, "__temp_suspend_d__")
tdays = [pd.to_datetime(f.split(".")[0]) for f in os.listdir(tmp_dir)]
tdays = sorted(tdays)
all_stocks_info = self.meta
df = pd.DataFrame(index=all_stocks_info.index, columns=tdays)
df.loc[:, :] = 1 #默认都是正常状态
for f in os.listdir(tmp_dir):
tday = pd.to_datetime(f.split(".")[0])
dat = pd.read_csv(os.path.join(tmp_dir, f), index_col=[1], engine='python', encoding='gbk')
df.loc[dat.index, tday] = 0 #停牌的设置为0
print(tday)
self.close_file(df, "trade_status")
def create_maxupordown(self):
''' 股票涨跌停状态
'''
tmp_dir = os.path.join(self.root, "__temp_limit_list__")
tdays = [pd.to_datetime(f.split(".")[0]) for f in os.listdir(tmp_dir)]
tdays = sorted(tdays)
all_stocks_info = self.meta
df = pd.DataFrame(index=all_stocks_info.index, columns=tdays)
df.loc[:, :] = 0 #默认都没有涨跌停
for f in os.listdir(tmp_dir):
tday = pd.to_datetime(f.split(".")[0])
dat = pd.read_csv(os.path.join(tmp_dir, f), index_col='ts_code', engine='python', encoding='gbk')
#==================================================
#有些股票已经名字和证劵代码,需要修改
index = dat.index.to_series()
index = index.replace("000022.SZ", "001872.SZ")
index = index.replace("601313.SH", "601360.SH")
index = index.replace("000043.SZ", "001914.SZ")
#==================================================
df.loc[index, tday] = 1 #涨跌停的设置为1
print(tday)
self.close_file(df, "maxupordown")
def create_turn_d(self):
''' 日换手率
'''
self.create_indicator("__temp_daily_basic__", "turnover_rate", "turn")
turn = self.turn / 100
turn = self.preprocess(turn, suspend_days_process=True)
self.close_file(turn, "turn")
def create_mkt_cap_float_m(self):
''' 通过日频数据创建月频指标(可统一为单个函数)
'''
tmp_dir = os.path.join(self.root, "__temp_daily_basic__")
s = pd.to_datetime('20090101')
e = pd.to_datetime('20191231')
new_tdays = self._get_trade_days(s, e, "M")
new_caldays = [self._get_month_end(tdate) for tdate in new_tdays]
all_stocks_info = self.meta
df = pd.DataFrame(index=all_stocks_info.index, columns=new_caldays)
for tday in new_tdays:
name = tday.strftime("%Y%m%d")
dat = pd.read_csv(os.path.join(tmp_dir, name+".csv"), index_col=[1], engine='python', encoding='gbk')
caldate = self.month_map[tday]
df[caldate] = dat["circ_mv"]
print(caldate)
df = df.dropna(how='all') #删掉全为空的一行
self.close_file(df, "mkt_cap_float_m")
def create_pe_ttm_m(self):
''' 通过日频数据创建月频指标(可统一为单个函数)
'''
tmp_dir = os.path.join(self.root, "__temp_daily_basic__")
s = pd.to_datetime('20090101')
e = pd.to_datetime('20191231')
new_tdays = self._get_trade_days(s, e, "M")
new_caldays = [self._get_month_end(tdate) for tdate in new_tdays]
all_stocks_info = self.meta
df = pd.DataFrame(index=all_stocks_info.index, columns=new_caldays)
for tday in new_tdays:
name = tday.strftime("%Y%m%d")
dat = pd.read_csv(os.path.join(tmp_dir, name+".csv"), index_col=[1], engine='python', encoding='gbk')
caldate = self.month_map[tday]
df[caldate] = dat["pe_ttm"]
print(caldate)
df = df.dropna(how='all') #删掉全为空的一行
self.close_file(df, "pe_ttm_m")
def create_val_pe_deducted_ttm_m(self):
''' 通过日频数据创建月频指标(可统一为单个函数)
'''
tmp_dir = os.path.join(self.root, "__temp_daily_basic__")
s = pd.to_datetime('20090101')
e = pd.to_datetime('20191231')
new_tdays = self._get_trade_days(s, e, "M")
new_caldays = [self._get_month_end(tdate) for tdate in new_tdays]
all_stocks_info = self.meta
df = pd.DataFrame(index=all_stocks_info.index, columns=new_caldays)
for tday in new_tdays:
name = tday.strftime("%Y%m%d")
dat = pd.read_csv(os.path.join(tmp_dir, name+".csv"), index_col=[1], engine='python', encoding='gbk')
caldate = self.month_map[tday]
df[caldate] = dat["pe"] #临时先用pe替代
print(caldate)
df = df.dropna(how='all') #删掉全为空的一行
self.close_file(df, "val_pe_deducted_ttm_m")
def create_pb_lf_m(self):
''' 通过日频数据创建月频指标(可统一为单个函数)
'''
tmp_dir = os.path.join(self.root, "__temp_daily_basic__")
s = pd.to_datetime('20090101')
e = pd.to_datetime('20191231')
new_tdays = self._get_trade_days(s, e, "M")
new_caldays = [self._get_month_end(tdate) for tdate in new_tdays]
all_stocks_info = self.meta
df = pd.DataFrame(index=all_stocks_info.index, columns=new_caldays)
for tday in new_tdays:
name = tday.strftime("%Y%m%d")
dat = pd.read_csv(os.path.join(tmp_dir, name+".csv"), index_col=[1], engine='python', encoding='gbk')
caldate = self.month_map[tday]
df[caldate] = dat["pb"]
print(caldate)
df = df.dropna(how='all') #删掉全为空的一行
self.close_file(df, "pb_lf_m")
def create_ps_ttm_m(self):
''' 通过日频数据创建月频指标(可统一为单个函数)
'''
tmp_dir = os.path.join(self.root, "__temp_daily_basic__")
s = pd.to_datetime('20090101')
e = pd.to_datetime('20191231')
new_tdays = self._get_trade_days(s, e, "M")
new_caldays = [self._get_month_end(tdate) for tdate in new_tdays]
all_stocks_info = self.meta
df = pd.DataFrame(index=all_stocks_info.index, columns=new_caldays)
for tday in new_tdays:
name = tday.strftime("%Y%m%d")
dat = pd.read_csv(os.path.join(tmp_dir, name+".csv"), index_col=[1], engine='python', encoding='gbk')
caldate = self.month_map[tday]
df[caldate] = dat["ps_ttm"]
print(caldate)
df = df.dropna(how='all') #删掉全为空的一行
self.close_file(df, "ps_ttm_m")
def create_pcf_ncf_ttm_m(self):
s = pd.to_datetime('20090101') #统计周期开始
e = pd.to_datetime('20191231') #统计周期结束
new_tdays = self._get_trade_days(s, e, "M") #每月最后一个交易日
new_caldays = [self._get_month_end(tdate) for tdate in new_tdays] #每月最后一天(每月最后一个日历日)
all_stocks_info = self.meta
#-------------------------------------------------------
#总市值指标(月频)
df_total_mv = pd.DataFrame(index=all_stocks_info.index, columns=new_caldays) #总市值指标(月频)
tmp_dir = os.path.join(self.root, "__temp_daily_basic__") #每日指标表
for tday in new_tdays:
name = tday.strftime("%Y%m%d")
dat = pd.read_csv(os.path.join(tmp_dir, name+".csv"), index_col=[1], engine='python', encoding='gbk')
caldate = self.month_map[tday]
df_total_mv[caldate] = dat["total_mv"]
print(caldate)
#df_total_mv = df_total_mv.dropna(how='all') #删掉全为空的一行
print(df_total_mv) #总市值指标ok
#-------------------------------------------------------
#现金增加额指标(季频)
tmp_dir = os.path.join(self.root, "__temp_cashflow__") #现金流量表
qdays = pd.date_range(start=s, end=e, freq="Q") #每个季度最后一天
df_cfps = pd.DataFrame(index=all_stocks_info.index, columns=qdays) #现金增加额指标(季频)
df_ann_date = pd.DataFrame(index=all_stocks_info.index, columns=qdays) #财报发布日期(季频)
for qday in qdays:
name = qday.strftime("%Y%m%d")
dat = pd.read_csv(os.path.join(tmp_dir, name+".csv"), index_col=[1], engine='python', encoding='gbk', parse_dates=['ann_date'])
diff = dat.index.difference(df_cfps.index) #删除没在股票基础列表中多余的股票行
dat = dat.loc[~dat.index.isin(diff)] #方法1
#dat = dat.drop(labels=diff) #方法2
#
#x = dat.index.to_series()
#print(x)
#x = x.groupby(['ts_code'])
#print(x)
#print(x.count())
#print(x.count()>1)
#print(dat[x.count()>1])
#
#x = dat.index
#print(x.duplicated())
#print(dat[x.duplicated()])
dat = dat[~dat.index.duplicated(keep='last')] #财务数据中同一只股票可能会有重复的记录,删除多余重复的
df_cfps[qday] = dat["n_incr_cash_cash_equ"] #现金及现金等价物净增加额
df_ann_date[qday] = dat["ann_date"] #财报发布日期
print(qday)
print(df_cfps) #现金增加额指标ok
#df_cfps = df_cfps.dropna(how='all') #删掉全为空的一行
#-------------------------------------------------------
#现金增加额指标可能有空值,利用线性插值补全(这步可以不做)
df_cfps_t = df_cfps.T #把时间变成索引,股票变成列名
def _w(ser):
if pd.isnull(ser[3]): #一年内如果第四季度(年报)指标值为空,那么整年四个季度都设置为空
ser.iloc[:] = np.nan
elif any(pd.isnull(ser)): #1~3季度如果存在空值,就利用线性插值补全
if pd.isnull(ser[0]): #第一季度必须保证有值,才能进行插值
ser[0] = ser[3]/4 #第一季度如果为空,就用全年的均值进行填充
ser = ser.interpolate()
df_cfps_t.loc[ser.index, ser.name] = ser #回填
df_cfps_t.resample('A').apply(_w) #按年分组处理
df_cfps = df_cfps_t.T #变回来:股票为索引,日期为列名
#-------------------------------------------------------
#计算结果指标(月频)
df_result = pd.DataFrame(index=all_stocks_info.index, columns=new_caldays)
'''
算法:
(1)最新报告期是年报,则TTM=年报;
(2)最新报告期不是年报,则TTM=本期+(上年年报-上年同期),如果本期、上年年报、上年同期存在空值,则不计算,返回空值;
(3)最新报告期通过财报发布时间进行判断,防止前视偏差。
'''
#按时间和股票逐个开始计算
for calday in df_result.columns: #每月最后一天
for stock in df_result.index:
tmap = df_ann_date.loc[stock] #tmap索引为报告期(每季度最后一天),值为相应财报发布时间
tmap = tmap[tmap<calday] #在那个历史节点,只能使用已经发布的财报,防止使用未来数据
try:
d = tmap.index[-1] #已经发布的财报里面最近一期的时间(某季度最后一天)
if d.quarter == 4: #最近一期财报是年报(第4季度)
ttm_value = df_cfps.loc[stock, d]
else: #最近一期财报是1季度,2季度,或者3季度的情形
last_q_4 = tmap.index[-1-d.quarter] #相对于那一个历史节点的上一年年报的时间
last_q_same = tmap.index[-1-4] #相对于那一个历史节点的上一年同期的时间
ttm_value = df_cfps.loc[stock, d] + (df_cfps.loc[stock, last_q_4] - df_cfps.loc[stock, last_q_same]) #TTM=本期+(上年年报-上年同期)
#总市值/现金及现金等价物净增加额(TTM)
df_result.loc[stock, calday] = df_total_mv.loc[stock, calday]/ttm_value
except:
pass
df_result = df_result.dropna(how='all') #删掉全为空的一行
self.close_file(df_result, "pcf_ncf_ttm_m")
def create_pcf_ocf_ttm_m(self):
''' 本函数与上面的create_pcf_ncf_ttm_m类似,逻辑更优化
'''
s = pd.to_datetime('20090101') #统计周期开始
e = pd.to_datetime('20191231') #统计周期结束
new_tdays = self._get_trade_days(s, e, "M") #每月最后一个交易日
new_caldays = [self._get_month_end(tdate) for tdate in new_tdays] #每月最后一天(每月最后一个日历日)
all_stocks_info = self.meta
#-------------------------------------------------------
#总市值指标(月频)
df_total_mv = pd.DataFrame(index=all_stocks_info.index, columns=new_caldays) #总市值指标(月频)
tmp_dir = os.path.join(self.root, "__temp_daily_basic__") #每日指标表
for tday in new_tdays: #每月最后一个交易日
name = tday.strftime("%Y%m%d")
dat = pd.read_csv(os.path.join(tmp_dir, name+".csv"), index_col=[1], engine='python', encoding='gbk')
caldate = self.month_map[tday] #每月最后一个日历日
df_total_mv[caldate] = dat["total_mv"]
print(caldate)
df_total_mv = df_total_mv.dropna(how='all') #删掉全为空的一行
#-------------------------------------------------------
tmp_dir = os.path.join(self.root, "__temp_cashflow__") #现金流量表
qdays = pd.date_range(start=s, end=e, freq="Q") #每个季度最后一天
panel = {}
for d in qdays:
name = d.strftime("%Y%m%d")
dat = pd.read_csv(os.path.join(tmp_dir, name+".csv"), index_col=[1], engine='python', encoding='gbk', parse_dates=['ann_date','end_date'])
diff = dat.index.difference(all_stocks_info.index) #删除没在股票基础列表中多余的股票行
dat = dat.loc[~dat.index.isin(diff)]
dat = dat[~dat.index.duplicated(keep='last')] #财务数据中同一只股票可能会有重复的记录,删除多余重复的
del dat['Unnamed: 0']
panel[d] = dat
print(d)
panel = pd.Panel(panel)
panel = panel.to_frame()
panel = panel.stack().unstack(level=(0,1))
#-------------------------------------------------------
#开始计算结果指标(月频)
df_result = pd.DataFrame(index=all_stocks_info.index, columns=new_caldays)
'''
算法:
(1)最新报告期是年报,则TTM=年报;
(2)最新报告期不是年报,则TTM=本期+(上年年报-上年同期),如果本期、上年年报、上年同期存在空值,则不计算,返回空值;
(3)最新报告期通过财报发布时间进行判断,防止前视偏差。
'''
#按时间和股票逐个开始计算
for calday in df_result.columns: #每月最后一天
for stock in df_result.index: #每只股票
try:
datdf = panel[stock]
datdf = datdf.loc[datdf['ann_date']<calday] #在那个历史节点,只能使用已经发布的财报,防止使用未来数据
d = datdf.iloc[-1].name #已经发布的财报里面最近一期的时间(某季度最后一天)
if d.quarter == 4: #最近一期财报是年报(第4季度)
ttm_value = datdf.iloc[-1].at['n_cashflow_act']
else: #最近一期财报是1季度,2季度,或者3季度的情形
last_q_4 = datdf.iloc[-1-d.quarter] #相对于那一个历史节点的上一年年报
last_q_same = datdf.iloc[-1-4] #相对于那一个历史节点的上一年同期
#TTM=本期+(上年年报-上年同期)
ttm_value = datdf.iloc[-1].at['n_cashflow_act'] + (last_q_4.at['n_cashflow_act'] - last_q_same.at['n_cashflow_act'])
#总市值/经营活动产生的现金流量净额(TTM)
df_result.at[stock, calday] = df_total_mv.at[stock, calday]/ttm_value
except:
pass
print(calday)
df_result = df_result.dropna(how='all') #删掉全为空的一行
self.close_file(df_result, "pcf_ocf_ttm_m")
def create_dividendyield2_m(self):
''' 通过日频数据创建月频指标(可统一为单个函数)
'''
tmp_dir = os.path.join(self.root, "__temp_daily_basic__")
s = pd.to_datetime('20090101')
e = pd.to_datetime('20191231')
new_tdays = self._get_trade_days(s, e, "M")
new_caldays = [self._get_month_end(tdate) for tdate in new_tdays]
all_stocks_info = self.meta
df = pd.DataFrame(index=all_stocks_info.index, columns=new_caldays)
for tday in new_tdays:
name = tday.strftime("%Y%m%d")
dat = pd.read_csv(os.path.join(tmp_dir, name+".csv"), index_col=[1], engine='python', encoding='gbk')
caldate = self.month_map[tday]
df[caldate] = dat["dv_ttm"]
print(caldate)
df = df.dropna(how='all') #删掉全为空的一行
self.close_file(df, "dividendyield2_m")
def create_profit_ttm_G_m(self):
''' 通过季频数据创建月频指标,可以直接用create_indicator_m_by_q代替
'''
s = pd.to_datetime('20090101') #统计周期开始
e = pd.to_datetime('20191231') #统计周期结束
qdays = pd.date_range(start=s, end=e, freq="Q") #每个季度最后一天
mdays = pd.date_range(start=s, end=e, freq="M") #每个月最后一天
all_stocks_info = self.meta
tmp_dir = os.path.join(self.root, "__temp_fina_indicator__") #财务指标表
panel = {}
for d in qdays: #每季度最后一天
name = d.strftime("%Y%m%d")
dat = pd.read_csv(os.path.join(tmp_dir, name+".csv"), index_col=[1], engine='python', encoding='gbk', parse_dates=['ann_date','end_date'])
diff = dat.index.difference(all_stocks_info.index) #删除没在股票基础列表中多余的股票行
dat = dat.drop(labels=diff)
dat = dat[~dat.index.duplicated(keep='last')] #财务数据中同一只股票可能会有重复的记录,删除多余重复的