-
Notifications
You must be signed in to change notification settings - Fork 0
/
KPMG data analysis.py
1585 lines (1250 loc) · 54 KB
/
KPMG data analysis.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
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import numpy as np
import networkx as nx
from addEdge import addEdge
import os
import jieba
import jieba.analyse
from collections import Counter
import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
from scipy.stats import linregress
from IPython import embed
named_colorscales = px.colors.named_colorscales()
# In[2]:
score = pd.DataFrame({'公司':[],
'第10款':[],
'第31款':[],
'第51款':[],
'第11款':[],
'第14款':[],
'第20款':[],
'第23款':[],
'第8款':[],
'平均收帳天數':[],
'現金流動比率':[],
'每股盈餘':[],
'借款依存度':[],
'母公司背書保證佔淨值比':[],
'母公司資金貸放佔淨值比':[],
'M-Score':[],
'結構異常':[],
'董監持股':[],
'董監質押股':[]})
# In[3]:
score = pd.read_csv('score.csv')
# In[4]:
#### Read Data ####
#Indicator
df_raw = pd.read_excel("./data/指標數值.xlsx", engine='openpyxl', sheet_name = None)
xls = pd.ExcelFile("./data/指標數值.xlsx",engine='openpyxl')
sheet_names = xls.sheet_names
#Important Message
important_message = pd.read_csv('./data/important_massage.csv')
important_message = important_message.loc[:, ~important_message.columns.astype(str).str.contains('^Unnamed')]
important_message['條款'] = important_message['符合條款'].apply(lambda x: str(x.split(' ')[1]))
#Company Sheet
corporate = pd.read_excel('./data/發生時間及對照公司(改).xlsx', engine='openpyxl')
corporate = corporate.loc[:, ~corporate.columns.astype(str).str.contains('^Unnamed')]
corporate['公司名稱'][2] = '齊民'
corporate['公司名稱'][13] = '吉祥全'
#Node
company_node = pd.read_csv('./data/company_node3.csv')
company_node[company_node['職稱'] == '重整人']['職稱'] = '董事'
company_node[company_node['職稱'] == '臨時管理人']['職稱'] = '董事'
company_node[company_node['職稱'] == '重整監督人']['職稱'] = '董事'
company_node[company_node['職稱'] == '常務董事 (獨立董事)']['職稱'] = '獨立董事'
company_node = company_node[company_node['姓名'] != '公司已廢止 ,董事會已不存在 ,依公司法第83條規定,清算人之就任、解任等均應向法院聲報;依民法第42條第1項規定,清算中之公司,係屬法院監督範疇。']
company_node = company_node[company_node['姓名'] != '董事']
company_node = company_node[company_node['姓名'] != '暫缺']
company_node = company_node.dropna(subset=['姓名']).reset_index(drop=True)
color_map = {'董事':'#3366CC', '獨立董事':'#FF9900', '代表人':'#4ecc63', '董事長':'#0099c6', '監察人':'#DD4477', '副董事長':'#316395', '公司':'#b07b4a'}
company_node['顏色'] = company_node['職稱']
company_node['顏色'] = company_node['顏色'].map(color_map)
# In[5]:
terms_of_corporate_governance = ['8']
terms_of_corporate_finance = ['14', '20', '11', '23']
terms_of_corporate_operating = ['31', '10', '51']
# In[6]:
t = [8,14, 20, 11, 23,31, 10, 51]
# In[7]:
for corporate_name, compare_name in zip(corporate['公司名稱'][14:], corporate['公司名稱'][:14]):
#embed()
# corporate_name = '歌林'
# compare_name = '聲寶'
# ### 資料準備
# In[8]:
#### Data Preparing ####
score_dict = {}
score_dict['公司'] = corporate_name
df_corporate = df_raw.get(corporate_name)
df_corporate = df_corporate.loc[:, ~df_corporate.columns.astype(str).str.contains('^Unnamed')].iloc[11:21, 2:7]
df_corporate.columns = [str(d.year) for d in list(df_corporate)]
important_message_corporate = important_message[important_message['公司'] == int(corporate[corporate['公司名稱'] == corporate_name]['股票代碼'].values[0])]
important_message_corporate['年份'] = important_message_corporate['年份'].astype(str)
df_compare = df_raw.get(compare_name)
df_compare = df_compare.loc[:, ~df_compare.columns.astype(str).str.contains('^Unnamed')].iloc[11:21, 2:7]
df_compare.columns = [str(d.year) for d in list(df_compare)]
important_message_compare = important_message[important_message['公司'] == int(corporate[corporate['公司名稱'] == compare_name]['股票代碼'].values[0])]
important_message_compare['年份'] = important_message_compare['年份'].astype(str)
# ### Corporate Operating
# In[9]:
#terms_of_corporate_operating
important_message_operating_unusual = important_message_corporate[important_message_corporate ['條款'].isin(terms_of_corporate_operating)]
important_message_operating_usual = important_message_corporate[~important_message_corporate.isin(important_message_operating_unusual)].dropna()
important_message_operating_unusual.iloc[:,:10].to_csv('./visual_output/operating/original_table/{}_important_message_operating.csv'.format(corporate_name), encoding='utf-8-sig', header=None, index=False)
score_dict['第10款'] = sum(important_message_operating_unusual['符合條款'].str.contains('10'))
score_dict['第31款'] = sum(important_message_operating_unusual['符合條款'].str.contains('31'))
score_dict['第51款'] = sum(important_message_operating_unusual['符合條款'].str.contains('51'))
usual = important_message_operating_usual.groupby('年份').count().reset_index()
unusual = important_message_operating_unusual.groupby('年份').count().reset_index()
if len(usual) == 0:
usual = pd.DataFrame({'年份':[2005,2006,2007,2008,2009], '公司':[0,0,0,0,0], '條款':[0,0,0,0,0]})
if len(unusual) == 0:
unusual = pd.DataFrame({'年份':[2005,2006,2007,2008,2009], '公司':[0,0,0,0,0], '條款':[0,0,0,0,0]})
usual['條款狀態'] = '正常'
unusual['條款狀態'] = '有舞弊風險'
group_df = usual.append(unusual)
group_df.rename(columns={'公司':'重大訊息數量'}, inplace=True)
fig = px.bar(group_df, x="年份", y="重大訊息數量", color="條款狀態", title="重大訊息-條款年份統計")
fig.write_html("./visual_output/operating/important_message/{}_important_message_operating.html".format(corporate_name))
#fig.show()
# In[10]:
# Statistic of unusual terms
unusual = important_message_operating_unusual.groupby(['年份','條款']).count().reset_index().rename(columns={'公司':'舞弊訊息數量','條款':'第幾款'})
if len(unusual) == 0:
unusual = pd.DataFrame({'年份':[2005,2006,2007,2008,2009], '舞弊訊息數量':[0,0,0,0,0], '條款':[0,0,0,0,0], '第幾款':[0,0,0,0,0]})
fig = px.bar(unusual, x="年份", y="舞弊訊息數量", color="第幾款", title="重大訊息-潛在舞弊條款統計", color_discrete_sequence=px.colors.qualitative.G10[1:4])
fig.write_html("./visual_output/operating/unusual_message/{}_unusual_message_operating.html".format(corporate_name))
#fig.show()
# ## Corporate Finace
# In[11]:
a = list(df_corporate.loc[11])[-4:]
b = list(range(len(a)))
model = linregress(a, b)
slope, intercept = model.slope, model.intercept
if slope>0:
score_dict['平均收帳天數'] = 10
else:
score_dict['平均收帳天數'] = 0
for i in a:
if i<=50:
continue
elif 50<i<100:
score_dict['平均收帳天數'] += 2
elif i>=100:
score_dict['平均收帳天數'] += 5
# In[12]:
#Average collection days
title = ['本公司平均收帳天數', '對照公司平均收帳天數']
labels = ['本公司平均', '整體平均']
colors = ['rgb(49,130,189)', 'rgb(115,115,115)']
mode_size = [12, 8]
line_size = [4, 2]
x_data = np.array([list(df_corporate)[-4:],list(df_compare)[-4:]])
y_data = np.array([list(df_corporate.loc[11])[-4:],list(df_compare.loc[11])[-4:]])
fig = go.Figure()
for i in range(0, 2):
fig.add_trace(go.Scatter(x=x_data[i], y=y_data[i], mode='lines',
name=labels[i],
line=dict(color=colors[i], width=line_size[i]),
connectgaps=True,
))
# endpoints
fig.add_trace(go.Scatter(
x=[x_data[i][0], x_data[i][-1]],
y=[y_data[i][0], y_data[i][-1]],
mode='markers',
marker=dict(color=colors[i], size=mode_size[i])
))
fig.update_layout(
xaxis=dict(
showline=True,
showgrid=False,
showticklabels=True,
linecolor='rgb(204, 204, 204)',
linewidth=2,
ticks='outside',
tickfont=dict(
family='Arial',
size=12,
color='rgb(82, 82, 82)',
),
),
yaxis=dict(
showgrid=False,
zeroline=False,
showline=False,
showticklabels=False,
),
autosize=False,
margin=dict(
autoexpand=False,
l=100,
r=20,
t=110,
),
showlegend=False,
plot_bgcolor='white'
)
annotations = []
# Adding labels
# labeling the left_side of the plot
annotations.append(dict(xref='paper', x=0.05, y=y_data[0][0],
xanchor='right', yanchor='top',
text=labels[0] + ' {}'.format(y_data[0][0]),
font=dict(family='Arial',
size=13),
showarrow=False))
# labeling the right_side of the plot
annotations.append(dict(xref='paper', x=0.95, y=y_data[0][3],
xanchor='left', yanchor='middle',
text='{}'.format(y_data[0][3]),
font=dict(family='Arial',
size=13),
showarrow=False))
# labeling the left_side of the plot
annotations.append(dict(xref='paper', x=0.05, y=y_data[1][0],
xanchor='right', yanchor='bottom',
text=labels[1] + ' {}'.format(y_data[1][0]),
font=dict(family='Arial',
size=13),
showarrow=False))
# labeling the right_side of the plot
annotations.append(dict(xref='paper', x=0.95, y=y_data[1][3],
xanchor='left', yanchor='middle',
text='{}'.format(y_data[1][3]),
font=dict(family='Arial',
size=13),
showarrow=False))
# Title
annotations.append(dict(xref='paper', yref='paper', x=0.5, y=1.05,
xanchor='center', yanchor='bottom',
text='平均收帳天數',
font=dict(family='Arial',
size=16),
showarrow=False))
fig.update_layout(annotations=annotations)
fig.write_html("./visual_output/finance/average_collection_days/{}_average_collection_days.html".format(corporate_name))
#fig.show()
# In[13]:
a = list(df_corporate.loc[12])[-4:]
b = list(range(len(a)))
model = linregress(a, b)
slope, intercept = model.slope, model.intercept
if slope<0:
score_dict['現金流動比率'] = 10
else:
score_dict['現金流動比率'] = 0
for i in a:
if i>100:
continue
elif 0<=i<=100:
score_dict['現金流動比率'] += 2
elif i<0:
score_dict['現金流動比率'] += 5
# In[14]:
#Cash flow ratio
title = ['本公司現金流動比率', '對照公司現金流動比率']
labels = ['本公司比率', '整體平均比率']
colors = ['rgb(49,130,189)', 'rgb(115,115,115)']
mode_size = [8, 8]
line_size = [4, 2]
x_data = np.array([list(df_corporate)[-4:],list(df_compare)[-4:]])
y_data = np.array([list(df_corporate.loc[12])[-4:],list(df_compare.loc[12])[-4:]])
fig = go.Figure()
for i in range(0, 2):
x_red = []
y_red = [d for d in y_data[i] if d<0]
for index in y_red:
x_red.append(np.where(y_data[i] == index)[0][0])
x_yellow = []
y_yellow = [d for d in y_data[i] if 0<=d<100]
for index in y_yellow:
x_yellow.append(np.where(y_data[i] == index)[0][0])
fig.add_trace(go.Scatter(x=x_data[i], y=y_data[i], mode='lines',
name=labels[i],
line=dict(color=colors[i], width=line_size[i]),
connectgaps=True,
))
# yellow point
fig.add_trace(go.Scatter(
x=[v for i,v in enumerate(x_data[i].tolist()) if i in x_yellow],
y=y_yellow,
mode='markers',
marker=dict(color='#ffb751', size=mode_size[i])
))
# redpoint
fig.add_trace(go.Scatter(
x=[v for i,v in enumerate(x_data[i].tolist()) if i in x_red],
y=y_red,
mode='markers',
marker=dict(color='#c52828', size=mode_size[i])
))
fig.update_layout(
xaxis=dict(
showline=True,
showgrid=True,
showticklabels=True,
linecolor='rgb(204, 204, 204)',
linewidth=2,
ticks='outside',
tickfont=dict(
family='Arial',
size=12,
color='rgb(82, 82, 82)',
),
),
yaxis=dict(
showgrid=False,
zeroline=False,
showline=False,
showticklabels=False,
),
autosize=False,
margin=dict(
autoexpand=False,
l=100,
r=20,
t=110,
),
showlegend=False,
plot_bgcolor='white'
)
annotations = []
# Adding labels
# labeling the left_side of the plot
annotations.append(dict(xref='paper', x=0.05, y=y_data[0][0],
xanchor='right', yanchor='top',
text=labels[0] + ' {}'.format(y_data[0][0]),
font=dict(family='Arial',
size=13),
showarrow=False))
# labeling the right_side of the plot
annotations.append(dict(xref='paper', x=0.95, y=y_data[0][3],
xanchor='left', yanchor='middle',
text='{}'.format(y_data[0][3]),
font=dict(family='Arial',
size=13),
showarrow=False))
# labeling the left_side of the plot
annotations.append(dict(xref='paper', x=0.05, y=y_data[1][0],
xanchor='right', yanchor='bottom',
text=labels[1] + ' {}'.format(y_data[1][0]),
font=dict(family='Arial',
size=13),
showarrow=False))
# labeling the right_side of the plot
annotations.append(dict(xref='paper', x=0.95, y=y_data[1][3],
xanchor='left', yanchor='middle',
text='{}'.format(y_data[1][3]),
font=dict(family='Arial',
size=13),
showarrow=False))
# Title
annotations.append(dict(xref='paper', yref='paper', x=0.5, y=1.05,
xanchor='center', yanchor='bottom',
text='現金流動比率',
font=dict(family='Arial',
size=16,),
showarrow=False))
fig.update_layout(annotations=annotations)
fig.write_html("./visual_output/finance/cash_flow_ratio/{}_cash_flow_ratio.html".format(corporate_name))
#fig.show()
# In[15]:
#Earnings per share
earnings_per_share = pd.DataFrame(df_corporate.loc[13]).reset_index().rename(columns={'index':'year', 13:'earnings per share'})
colors_mark_line = ['lightslategray',]*len(earnings_per_share)
for i,v in enumerate(earnings_per_share['earnings per share']):
if v<0: colors_mark_line[i] = '#c52828'
elif 0<v<5 : colors_mark_line[i] = '#ffb751'
else: continue
fig = go.Figure(data=[go.Bar(
x=earnings_per_share['year'],
y=earnings_per_share['earnings per share'],
marker_color='lightslategray', # marker color can be a single color value or an iterable
marker_line_color=colors_mark_line,
marker_line_width=3,
)])
fig.update_layout(
title_text='每股盈餘',
xaxis=dict(
title='年份',
titlefont_size=16,
tickfont_size=14,
),
yaxis=dict(
title='盈餘',
titlefont_size=16,
tickfont_size=14,
),)
fig.write_html("./visual_output/finance/earnings_per_share/{}_earnings_per_share.html".format(corporate_name))
#fig.show()
# In[16]:
a = list(earnings_per_share['earnings per share'])
b = list(range(len(a)))
model = linregress(a, b)
slope, intercept = model.slope, model.intercept
if slope<0:
score_dict['每股盈餘'] = 10
else:
score_dict['每股盈餘'] = 0
for i in a:
if i>5:
continue
elif 0<=i<=5:
score_dict['每股盈餘'] += 2
elif i<0:
score_dict['每股盈餘'] += 5
# In[17]:
a = list(df_corporate.loc[17])
b = list(range(len(a)))
model = linregress(a, b)
slope, intercept = model.slope, model.intercept
if slope>0:
score_dict['母公司背書保證佔淨值比'] = 10
else:
score_dict['母公司背書保證佔淨值比'] = 0
for i in a:
if 0<=i<10:
continue
elif 10<=i<20:
score_dict['母公司背書保證佔淨值比'] += 2
elif (i>=20 or i<0):
score_dict['母公司背書保證佔淨值比'] += 5
a = list(df_corporate.loc[18])
b = list(range(len(a)))
model = linregress(a, b)
slope, intercept = model.slope, model.intercept
if slope>0:
score_dict['母公司資金貸放佔淨值比'] = 10
else:
score_dict['母公司資金貸放佔淨值比'] = 0
for i in a:
if 0<=i<10:
continue
elif 10<=i<20:
score_dict['母公司資金貸放佔淨值比'] += 2
elif (i>=20 or i<0):
score_dict['母公司資金貸放佔淨值比'] += 5
# In[18]:
#parent company
legend_x = 0
legend_y = 1
if (df_corporate.loc[17][0]>70 or df_corporate.loc[18][0]>70):
legend_x = 0.78
legend_y = 1
if (df_corporate.loc[17][-1]>70 or df_corporate.loc[18][-1]>70):
legend_x = 1
legend_y = 1
years = list(df_corporate)
color_endorse = ['rgb(55, 83, 109)']*len(years)
for i,v in enumerate(list(df_corporate.loc[17])):
if (v>=20 or v<0): color_endorse[i] = '#c52828'
elif 10<=v<20 : color_endorse[i] = '#ffb751'
else: continue
color_funds = ['lightslategray']*len(years)
for i,v in enumerate(list(df_corporate.loc[18])):
if (v>=20 or v<0): color_funds[i] = '#c52828'
elif 10<=v<20 : color_funds[i] = '#ffb751'
else: continue
fig = go.Figure()
fig.add_trace(go.Bar(x=years,
y=df_corporate.loc[17],
name='母公司背書保証佔淨值比',
marker_color='rgb(55, 83, 109)',
marker_line_color=color_endorse,
marker_line_width=3
))
fig.add_trace(go.Bar(x=years,
y=df_corporate.loc[18],
name='母公司資金貸放佔淨值比',
marker_color='lightslategray',
marker_line_color=color_funds,
marker_line_width=3,
))
fig.update_layout(
title='母公司背書保証/資金貸放佔淨值比',
xaxis_tickfont_size=14,
yaxis=dict(
title='佔比(%)',
titlefont_size=16,
tickfont_size=14,
),
xaxis=dict(
title='年份',
titlefont_size=16,
tickfont_size=14,
),
legend=dict(
x=legend_x,
y=legend_y,
bgcolor='rgba(255, 255, 255, 0)',
bordercolor='rgba(255, 255, 255, 0)'
),
barmode='group',
bargap=0.15, # gap between bars of adjacent location coordinates.
bargroupgap=0.1 # gap between bars of the same location coordinate.
)
fig.write_html("./visual_output/finance/endorse_funds/{}_endorse_funds.html".format(corporate_name))
#fig.show()
# In[19]:
#Borrowing dependence
borrowing_dependence = pd.DataFrame(df_corporate.loc[16]).reset_index().rename(columns={16:'借款依存度', 'index':'年份'})
color = ['#096148']*len(borrowing_dependence['年份'])
for i,v in enumerate(list(borrowing_dependence['借款依存度'])):
if (v<0 or v>200): color[i] = '#c52828'
elif 100<=v<=200 : color[i] = '#ffb751'
else: continue
fig = go.Figure()
fig.add_trace(dict(
x=borrowing_dependence["年份"],
y=borrowing_dependence["借款依存度"],
hoverinfo='x+y',
mode='lines',
name = '借款依存度',
line=dict(width=0.5,
color='#096148'),
stackgroup='one'
))
fig.add_trace(go.Scatter(
x=borrowing_dependence["年份"],
y=borrowing_dependence["借款依存度"],
mode='markers',
marker=dict(color=color, size=5)
))
fig.update_layout(
title='借款依存度',
showlegend=False,
xaxis_tickfont_size=14,
yaxis=dict(
title='借款依存度',
titlefont_size=16,
tickfont_size=14,
),
xaxis=dict(
title='年份',
titlefont_size=16,
tickfont_size=14,
),
legend=dict(
x=legend_x,
y=legend_y,
bgcolor='rgba(255, 255, 255, 0)',
bordercolor='rgba(255, 255, 255, 0)'
),
barmode='group',
bargap=0.15, # gap between bars of adjacent location coordinates.
bargroupgap=0.1 # gap between bars of the same location coordinate.
)
fig.write_html("./visual_output/finance/borrowing_dependence/{}_borrowing_dependence.html".format(corporate_name))
#fig.show()
# In[20]:
a = list(df_corporate.loc[16])
b = list(range(len(a)))
model = linregress(a, b)
slope, intercept = model.slope, model.intercept
if slope>0:
score_dict['借款依存度'] = 10
else:
score_dict['借款依存度'] = 0
for i in a:
if 0<i<100:
continue
elif 100<=i<=200:
score_dict['借款依存度'] += 2
elif i<0 or i>200:
score_dict['借款依存度'] += 5
# In[21]:
a = list(df_corporate.loc[19])[-2:]
b = list(range(len(a)))
model = linregress(a, b)
slope, intercept = model.slope, model.intercept
if slope>0:
score_dict['M-Score'] = 4
else:
score_dict['M-Score'] = 0
for i in a:
if i<(-2.277):
continue
elif -2.277<=i<=(-1.837):
score_dict['M-Score'] += 2
elif i>(-1.837):
score_dict['M-Score'] += 5
# In[22]:
# M score
M_score = pd.DataFrame(df_corporate.loc[19]).reset_index().rename(columns={19:'M score', 'index':'年份'})
years = list(M_score['年份'])[-2:]
color = ['rgb(55, 83, 109)']*len(years)
for i,v in enumerate(list(df_corporate.loc[19])[-2:]):
if v>-1.837: color[i] = '#c52828'
elif -2.277<=v<=-1.837 : color[i] = '#ffb751'
else: continue
fig = go.Figure()
fig.add_trace(go.Bar(x=M_score['年份'][-2:],
y=M_score['M score'][-2:],
name='M score',
marker_color='rgb(55, 83, 109)',
marker_line_color=color,
marker_line_width=3
))
fig.update_layout(
title='M score',
xaxis_tickfont_size=14,
yaxis=dict(
title='M score',
titlefont_size=16,
tickfont_size=14,
),
xaxis=dict(
title='年份',
titlefont_size=16,
tickfont_size=14,
),
legend=dict(
x=0,
y=1,
bgcolor='rgba(255, 255, 255, 0)',
bordercolor='rgba(255, 255, 255, 0)'
),
barmode='group',
bargap=0.15, # gap between bars of adjacent location coordinates.
bargroupgap=0.1 # gap between bars of the same location coordinate.
)
fig.write_html("./visual_output/finance/M_score/{}_M_score.html".format(corporate_name))
#fig.show()
# In[23]:
#terms_of_corporate_finance
important_message_finance_unusual = important_message_corporate[important_message_corporate ['條款'].isin(terms_of_corporate_finance)]
important_message_finance_usual = important_message_corporate[~important_message_corporate.isin(important_message_finance_unusual)].dropna()
important_message_finance_unusual.iloc[:,:10].to_csv('./visual_output/finance/original_table/{}_important_message_finance.csv'.format(corporate_name), encoding='utf-8-sig', header=None, index=False)
score_dict['第11款'] = sum(important_message_finance_unusual['符合條款'].str.contains('11'))
score_dict['第14款'] = sum(important_message_finance_unusual['符合條款'].str.contains('14'))
score_dict['第20款'] = sum(important_message_finance_unusual['符合條款'].str.contains('20'))
score_dict['第23款'] = sum(important_message_finance_unusual['符合條款'].str.contains('23'))
usual = important_message_finance_usual.groupby('年份').count().reset_index()
unusual = important_message_finance_unusual.groupby('年份').count().reset_index()
if len(usual) == 0:
usual = pd.DataFrame({'年份':[2005,2006,2007,2008,2009], '公司':[0,0,0,0,0], '條款':[0,0,0,0,0]})
if len(unusual) == 0:
unusual = pd.DataFrame({'年份':[2005,2006,2007,2008,2009], '公司':[0,0,0,0,0], '條款':[0,0,0,0,0]})
usual['條款狀態'] = '正常'
unusual['條款狀態'] = '有舞弊風險'
group_df = usual.append(unusual)
group_df.rename(columns={'公司':'重大訊息數量'}, inplace=True)
fig = px.bar(group_df, x="年份", y="重大訊息數量", color="條款狀態", title="重大訊息-條款年份統計")
fig.write_html("./visual_output/finance/important_message/{}_important_message_finance.html".format(corporate_name))
#fig.show()
# In[24]:
# Statistic of unusual terms
unusual = important_message_finance_unusual.groupby(['年份','條款']).count().reset_index().rename(columns={'公司':'舞弊訊息數量','條款':'第幾款'})
if len(unusual) == 0:
unusual = pd.DataFrame({'年份':[2005,2006,2007,2008,2009], '公司':[0,0,0,0,0], '第幾款':[0,0,0,0,0]})
x = sorted(list(unusual['年份'].unique()))
fig = go.Figure()
color = ['#DC3912', '#FF9900', 'indianred', 'lightsalmon']
for i,t in enumerate(terms_of_corporate_finance):
y_data = []
unusual[unusual['第幾款'] == t]
for y in x:
try:
y_data.append(int(unusual[unusual['第幾款'] == t][unusual[unusual['第幾款'] == t]['年份'] == y]['舞弊訊息數量']))
except:
y_data.append(0)
fig.add_trace(go.Bar(x=x, y=y_data, name=t, marker_color=color[i]))
fig.update_layout(
barmode='stack',
title='重大訊息-潛在舞弊條款統計',
xaxis_tickfont_size=14,
yaxis=dict(
title='舞弊訊息數量',
titlefont_size=16,
tickfont_size=14,
),
xaxis=dict(
categoryorder='category ascending',
title='年份',
titlefont_size=16,
tickfont_size=14,
),
legend=dict(
title='第幾款',
x=1,
y=1,
bgcolor='rgba(255, 255, 255, 0)',
bordercolor='rgba(255, 255, 255, 0)'
),
bargap=0.15, # gap between bars of adjacent location coordinates.
bargroupgap=0.1 # gap between bars of the same location coordinate.
)
fig.write_html("./visual_output/finance/unusual_message/{}_unusual_message_finance.html".format(corporate_name))
#fig.show()
# ## Governance
# In[25]:
#terms_of_corporate_governance
important_message_governance_unusual = important_message_corporate[important_message_corporate ['條款'].isin(terms_of_corporate_governance)]
important_message_governance_usual = important_message_corporate[~important_message_corporate.isin(important_message_governance_unusual)].dropna()
important_message_governance_unusual.iloc[:,:10].to_csv('./visual_output/governance/original_table/{}_important_message_governance.csv'.format(corporate_name), encoding='utf-8-sig', header=None, index=False)
score_dict['第8款'] = sum(important_message_governance_unusual['符合條款'].str.contains('8'))
usual = important_message_finance_usual.groupby('年份').count().reset_index()
unusual = important_message_finance_unusual.groupby('年份').count().reset_index()
if len(usual) == 0:
usual = pd.DataFrame({'年份':[2005,2006,2007,2008,2009], '公司':[0,0,0,0,0], '條款':[0,0,0,0,0]})
if len(unusual) == 0:
unusual = pd.DataFrame({'年份':[2005,2006,2007,2008,2009], '公司':[0,0,0,0,0], '條款':[0,0,0,0,0]})
usual['條款狀態'] = '正常'
unusual['條款狀態'] = '有舞弊風險'
group_df = usual.append(unusual)
group_df.rename(columns={'公司':'重大訊息數量'}, inplace=True)
fig = px.bar(group_df, x="年份", y="重大訊息數量", color="條款狀態", title="重大訊息-條款年份統計")
fig.write_html("./visual_output/governance/important_message/{}_important_message_governance.html".format(corporate_name))
#fig.show()
# In[26]:
# Statistic of unusual terms
unusual = important_message_governance_unusual.groupby(['年份','條款']).count().reset_index().rename(columns={'公司':'舞弊訊息數量','條款':'第幾款'})
if len(unusual) == 0:
unusual = pd.DataFrame({'年份':[2005,2006,2007,2008,2009], '公司':[0,0,0,0,0], '第幾款':[0,0,0,0,0]})
x = sorted(list(unusual['年份'].unique()))
fig = go.Figure()
color = ['indianred', 'lightsalmon', '#DC3912', '#FF9900']
for i,t in enumerate(terms_of_corporate_governance):
y_data = []
unusual[unusual['第幾款'] == t]
for y in x:
try:
y_data.append(int(unusual[unusual['第幾款'] == t][unusual[unusual['第幾款'] == t]['年份'] == y]['舞弊訊息數量']))
except:
y_data.append(0)
fig.add_trace(go.Bar(x=x, y=y_data, name=t, marker_color=color[i], showlegend=True))
fig.update_layout(
barmode='stack',
title='重大訊息-潛在舞弊條款統計',
xaxis_tickfont_size=14,
yaxis=dict(
title='舞弊訊息數量',
titlefont_size=16,
tickfont_size=14,
),
xaxis=dict(
categoryorder='category ascending',
title='年份',
titlefont_size=16,
tickfont_size=14,
),
legend=dict(
title='第幾款',
x=1,
y=1,
bgcolor='rgba(255, 255, 255, 0)',
bordercolor='rgba(255, 255, 255, 0)',
),
bargap=0.15, # gap between bars of adjacent location coordinates.
bargroupgap=0.1 # gap between bars of the same location coordinate.
)
fig.write_html("./visual_output/governance/unusual_message/{}_unusual_message_operating.html".format(corporate_name))
#fig.show()
# In[27]:
a = list(df_corporate.loc[14])
b = list(range(len(a)))
model = linregress(a, b)
slope, intercept = model.slope, model.intercept
if slope<0:
score_dict['董監持股'] = 10
else:
score_dict['董監持股'] = 0
for i in a:
if i>20:
continue
elif 10<i<20:
score_dict['董監持股'] += 2
elif i<=10:
score_dict['董監持股'] += 5
a = list(df_corporate.loc[15])
b = list(range(len(a)))
model = linregress(a, b)
slope, intercept = model.slope, model.intercept
if slope>0:
score_dict['董監質押股'] = 10
else:
score_dict['董監質押股'] = 0
for i in a:
if i<=10:
continue
elif 10<i<33: