-
Notifications
You must be signed in to change notification settings - Fork 0
/
qbods.py
1706 lines (1298 loc) · 66.9 KB
/
qbods.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
import pandas as pd
import re
import statistics
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import textwrap
import inspect
from IPython.display import Markdown as md
import datetime
from datetime import datetime, date
import networkx as nx
import random
import os
cols = ['#363487', '#9bb9d3', '#006a9e', '#f2f4f8', '#dfd5c3', '#f5a00d']
def getBodsData(url):
"""
Description: downloads and unzips BODS data in csv format
Arguments:
folder: url link to the csv files from the BODS data analysis tools csv output
Returns: a folder called 'csv' containing all data, downloaded to the current working directory
"""
os.system("rm -rf csv* *json output/*")
os.system("wget " + url)
os.system("unzip csv")
os.system("rm csv.zip")
def readBodsData(folder):
"""
Description: Reads in a set of BODS data in csv format
Arguments:
folder: a folder containing ONLY the csv files from the BODS data analysis tools csv output
Returns: a dictionary of dataframes, with names corresponding to the filename handle
"""
files = os.listdir(folder)
output = {}
for file in files:
output[file[:-4]] = pd.read_csv(folder+'/'+file)
return (output)
def getQueryDescription(query):
"""
Description: Gets the query description from a qbods query
Arguments:
Query: a function in the qbods module. This MUST have the query description on a single
line in the docstring that start with 'Description:'
Returns: a markdown string containing the query description
"""
f = inspect.getsource(query)
flist = f.split('\n')
for item in flist:
if item.strip().startswith('Description:'):
return (md(item.strip()))
break
def bodsInfo(data):
"""
Description: Summarises a BODS data frame
Arguments:
data: a BODS dataframe read in from the BODS data analysis tools csv format
Returns: a dataframe containing the the number and proportion of non-missing entries in each column of the input dataframe. This table is also written as tab delimited text to the output folder if an outname is provided (this needs to exist)
"""
out = data.count(0).to_frame().rename(
columns={0: 'Number non-missing entries'})
cond = out.index.str.contains('_link')
out = out.drop(out[cond].index.values)
out['Proportion non-missing entries'] = out['Number non-missing entries'] / \
len(data)
out = out.round(2)
return (out)
def propObjectInStatement(obj, statement):
"""
Description: calculates the proportion of statements that contain a given object
Arguments:
obj: a BODS dataframe that is an object within an entity statement, person statement
or ownership or control statement
statement: a BODS dataframe containing the higher level statements within wich obj
is nested
Returns: a float representing the proportion of statements that contain at least one entry for
the object
"""
colnames = list(obj)
colname = [colname for colname in colnames if '_link_' in colname][0]
out = len(obj[colname].unique())/len(statement)
return (out)
def camel_to_snake(name):
"""
Description: Converts a string from camel to snake case
Arguments:
name: a string in camel case
Returns: a string in snake case
"""
name = re.sub('(.)([A-Z][a-z]+)', r'\1-\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1-\2', name).lower()
def read_codelist(url, case='camel'):
"""
Description: reads in a BODS codelist in csv format
Arguments:
url: the url containing the raw csv data
case: a string specifying the case to return the codelist
must be 'camel' or 'snake'
Returns: a list of codelist items
"""
df = pd.read_csv(url)
if case == 'snake': # can return in snake case with required
return (df['code'].apply(camel_to_snake).tolist())
else:
if case == 'camel':
return (df['code'].tolist())
def sortCounts(df):
"""
Description: Takes an output from a qbods query and puts columns and rows with 'missing' or 'all' at the end. Also renames 'all' to 'total'
Arguments:
df: a qbods set of counts in pandas dataframe format
Returns: a resorted and renamed dataframe
"""
def moveToEnd(l, string):
l.append(l.pop(l.index(string)))
return (l)
if 'Missing' in df.index:
l = df.index.tolist()
l = moveToEnd(l, 'Missing')
df = df.reindex(l)
if 'Missing' in list(df):
df.columns = moveToEnd(list(df), 'Missing')
if 'All' in df.index:
l = df.index.tolist()
l = moveToEnd(l, 'All')
df = df.reindex(l).rename(index={'All': 'Total'})
if 'All' in list(df):
df.columns = moveToEnd(list(df), 'All')
df = df.rename(columns={'All': 'Total'})
return (df)
def q111(ownershipOrControlInterest, ownershipOrControlStatement):
"""
Description: Provides a breakdown of the beneficial ownership or control field in ownership or control statement interests
Arguments:
ownershipOrControlInterests: a pandas dataframe containing ownership or control interests data
ownershipOrControlStatement: a pandas dataframe containing ownership or control statements
Returns: a list containing a pandas dataframe of counts, and a barplot of the same counts
"""
# join interests table with ownership or control statements table to get missing values
df = pd.merge(ownershipOrControlStatement['_link'],
ownershipOrControlInterest[[
'_link_ooc_statement', 'type', 'beneficialOwnershipOrControl']],
how='left',
left_on='_link',
right_on='_link_ooc_statement')
# Generate output table
out = df['beneficialOwnershipOrControl'].fillna(
'Missing').value_counts().to_frame()
out = sortCounts(out)
# Make figure
ax = out.plot.barh(stacked=True)
ax.set(ylabel=None, xlabel="Number of OOC statements")
fig = ax.get_figure()
plt.close()
return ([out, fig])
def q121(ownershipOrControlInterest, ownershipOrControlStatement, personStatement, entityStatement):
"""
Description: Provides a breakdown of interested parties in ownership or control statements according to whether at least one beneficial ownership or control interest is declared
Arguments:
ownershipOrControlInterest: a pandas dataframe containing ownership or control interests
ownershipOrControlStatement: a pandas dataframe containing ownership or control statements
personStatement: a pandas dataframe containing person statements
entityStatement: a pandas dataframe containing entity statements
Returns: a list containing a pandas dataframe of counts, and a barplot of the same counts.
"""
# Merge OOC and person statement tables by interested party
ooc_ps = pd.merge(ownershipOrControlStatement.dropna(subset=['interestedParty_describedByPersonStatement'])[['_link', 'interestedParty_describedByPersonStatement']],
personStatement[['statementID', 'personType']],
left_on='interestedParty_describedByPersonStatement',
right_on='statementID',
how='left')
# Now merge with interests
ooci_int = ownershipOrControlInterest[[
'_link_ooc_statement', 'beneficialOwnershipOrControl']].replace({True: 1, False: 0})
interestSums = ooci_int.groupby('_link_ooc_statement').agg(
beneficialOwnershipOrControl=pd.NamedAgg(
column='beneficialOwnershipOrControl', aggfunc=sum)
)
interestSums[interestSums > 1] = 1
interestSums['beneficialOwnershipOrControl'] = interestSums['beneficialOwnershipOrControl'].replace({
1: True, 0: False})
ooc_ps_ooci = pd.merge(ooc_ps,
interestSums,
left_on='_link',
right_on='_link_ooc_statement',
how='left')
# Merge OOC and entity statement tables by interested party
ooc_es = pd.merge(ownershipOrControlStatement.dropna(subset=['interestedParty_describedByEntityStatement'])[['_link', 'interestedParty_describedByEntityStatement']],
entityStatement[['statementID', 'entityType']],
left_on='interestedParty_describedByEntityStatement',
right_on='statementID',
how='left')
# Now merge with interests
ooc_es_ooci = pd.merge(ooc_es,
interestSums,
left_on='_link',
right_on='_link_ooc_statement',
how='left')
# Bind person and entity statements
ooc_ps_es_ooci = ooc_ps_ooci[['personType', 'beneficialOwnershipOrControl']].rename(columns={'personType': 'ownerType'}).append(
ooc_es_ooci[['entityType', 'beneficialOwnershipOrControl']].rename(
columns={'entityType': 'ownerType'})
)
# Crosstab of person types of with beneficial ownership
ownerCounts = pd.crosstab(ooc_ps_es_ooci['ownerType'].fillna(
'Missing'), ooc_ps_es_ooci['beneficialOwnershipOrControl'].fillna('Missing'), margins=True)
if True not in ownerCounts.columns:
ownerCounts[True] = 0
if False not in ownerCounts.columns:
ownerCounts[False] = 0
if 'Missing' not in ownerCounts.columns:
ownerCounts['Missing'] = 0
out = ownerCounts[[True, False, 'Missing', 'All']]
# Read in all person and entity types from codelist and append
ptypes = read_codelist('https://raw.githubusercontent.com/openownership/data-standard/0.2.0/schema/codelists/personType.csv',
case='camel')
etypes = read_codelist('https://raw.githubusercontent.com/openownership/data-standard/0.2.0/schema/codelists/entityType.csv',
case='camel')
alltypes = ptypes+etypes+['All']
# Add missing codelists and fill with zero
out = out.reindex(index=alltypes, fill_value=0)
out = sortCounts(out).rename(columns={
True: 'BO interests', False: 'Non-BO interests', 'Missing': 'BO data missing'})
out.index.name = 'Interested party type'
# Barplot
ax = out.drop(columns=['Total']).drop(
index=['Total']).plot.barh(stacked=True, color=cols)
ax.set(ylabel=None, xlabel="Number of OOC statements")
fig = ax.get_figure()
plt.close()
return ([out, fig])
def q122(ownershipOrControlInterest, ownershipOrControlStatement, entityStatement):
"""
Description: Provides a count of the number of instances where an entity is listed as a beneficial owner alongside the jurisdiction of declaring companies and interested parties where an entity is listed as a BO
Arguments:
ownershipOrControlInterest: a pandas dataframe containing ownership or control interests
ownershipOrControlStatement: a pandas dataframe containing ownership or control statements
entityStatement: a pandas dataframe containing entity statements
Returns: a list containing i) a pandas dataframe of counts, and ii) a barplot of the same counts. If there are no entities of beneficial owners a list of two placeholder strings is returned with this message
"""
# Merge interests where BO == True with ooc statements and filter for ownership by entities
df = pd.merge(ownershipOrControlInterest[ownershipOrControlInterest['beneficialOwnershipOrControl'] == True]['_link_ooc_statement'],
ownershipOrControlStatement[[
'_link', 'subject_describedByEntityStatement', 'interestedParty_describedByEntityStatement']],
how='left',
left_on='_link_ooc_statement',
right_on='_link')
df = df.loc[df['interestedParty_describedByEntityStatement'].notnull()]
# Only do the rest if there are entities with beneificial owners
if len(df) > 0:
df = pd.merge(df,
entityStatement[['statementID',
'incorporatedInJurisdiction_name']],
how='left',
left_on='subject_describedByEntityStatement',
right_on='statementID')
df = df.drop_duplicates(subset=['statementID'])
out = df['incorporatedInJurisdiction_name'].fillna(
'Missing').value_counts().to_frame()
# Add totals row
out = out.append(pd.DataFrame(sum(out['incorporatedInJurisdiction_name']),
columns=[
'incorporatedInJurisdiction_name'],
index=['All']))
# Plot
ax = out.drop(labels=['Total']).head(10).plot.barh()
ax.set(ylabel=None, xlabel="Number of OOC statements")
fig = ax.get_figure()
plt.close()
return ([out, fig])
else:
print('No entities with other entities as beneficial owners')
return (['No table returned', 'No plot returned'])
def q131(ownershipOrControlInterest, ownershipOrControlStatement):
"""
Description: Checks the breakdown of interest types and beneficial ownership or control flags in ownership or control statements
Arguments:
ownershipOrControlInterest: a pandas dataframe containing ownership or control interests
ownershipOrControlStatement: a pandas dataframe containing ownership or control statements
Returns: a list containing i) a pandas dataframe of counts, and ii) a barplot of the same counts
"""
# merge ooci table with ooc table to get missing values
df = pd.merge(ownershipOrControlStatement['_link'],
ownershipOrControlInterest[[
'_link_ooc_statement', 'type', 'beneficialOwnershipOrControl']],
how='left',
left_on='_link',
right_on='_link_ooc_statement')
# Generate table with crosstab
out = pd.crosstab(df['type'].fillna(
'Missing'), df['beneficialOwnershipOrControl'].fillna('Missing'), margins=True)
# Add in missing codelist entries and replace with zeros
rights = read_codelist(
'https://raw.githubusercontent.com/openownership/data-standard/0.2.0/schema/codelists/interestType.csv')
out = out.reindex(index=rights+['Missing', 'All'], fill_value=0)
# Sort
out = out.sort_values(by=['All'], ascending=False)
out = sortCounts(out).rename(columns={
True: 'BO interests', False: 'Non-BO interests', 'Missing': 'BO data missing'})
# Graph
ax = out.drop(labels=['Total']).drop(
columns=['Total']).plot.barh(stacked=True, color=cols)
ax.set(ylabel=None, xlabel="Number of OOC statements")
fig = ax.get_figure()
plt.close()
return ([out, fig])
def q132(ownershipOrControlInterest, ownershipOrControlStatement):
"""
Description: Checks the breakdown of direct and indirect interests in ownership or control statements
Arguments:
ownershipOrControlInterest: a pandas dataframe containing ownership or control interests
ownershipOrControlStatement: a pandas dataframe containing ownership or control statements
Returns: a list containing i) a pandas dataframe of counts, and ii) a barplot of the same counts
"""
# Generate output table with crosstab
df = pd.merge(ownershipOrControlStatement['_link'],
ownershipOrControlInterest[[
'_link_ooc_statement', 'interestLevel', 'beneficialOwnershipOrControl']],
how='left',
left_on='_link',
right_on='_link_ooc_statement')
out = pd.crosstab(df['interestLevel'].fillna(
'Missing'), df['beneficialOwnershipOrControl'].fillna('Missing'), margins=True)
levels = read_codelist(
'https://raw.githubusercontent.com/openownership/data-standard/0.2.0/schema/codelists/interestLevel.csv')
out = out.reindex(index=levels+['Missing', 'All'], fill_value=0)
out = out.sort_values(by='All', ascending=False).rename(
columns={False: 'False', True: 'True'})
out = sortCounts(out)
# Plot
ax = out.drop(labels=['Total']).drop(
columns=['Total']).plot.barh(stacked=True)
ax.set(ylabel=None, xlabel="Number of OOC statements")
fig = ax.get_figure()
plt.close()
return ([out, fig])
def q141(ownershipOrControlInterest):
"""
Description: Determines whether the data contain minimum, maximum and/or exact shares.
Arguments:
ownershipOrControlInterest: a pandas dataframe containing ownership or control interests
Returns: a list containing i) a pandas dataframe of counts, and ii) a barplot of the same counts
"""
shares = ['share_exact', 'share_minimum', 'share_maximum']
df = ownershipOrControlInterest.reindex(columns=shares, fill_value=None)
out = df.notna().sum().to_frame(name='Number non-missing values')
out = sortCounts(out)
ax = out.plot.barh(legend=False)
ax.set(ylabel=None, xlabel='Number of non-missing values')
fig = ax.get_figure()
plt.close()
return ([out, fig])
def q142(ownershipOrControlInterest, threshold):
"""
Description: Determines whether the data contain minimum, maximum and/or exact shares.
Arguments:
ownershipOrControlInterest: a pandas dataframe containing ownership or control interests
threshold: a number corresponding to the declaration threshold in the declaring country, in percent
Returns: a list containing i) a pandas dataframe of counts, and ii) a barplot of the same counts
"""
shares = ['share_exact', 'share_minimum', 'share_maximum']
df = ownershipOrControlInterest.reindex(columns=shares, fill_value=None)
df['max-min share'] = df['share_maximum'] - df['share_minimum']
idx = ['Most common value', 'Number of unique values',
'Minimum share', 'Maximum share']
out = df.mode().append(df.nunique(), ignore_index=True).append(
df.min(), ignore_index=True).append(df.max(), ignore_index=True)
out.index = idx
finalout = [out]
if out['share_exact']['Number of unique values'] > 0:
ax = df['share_exact'].hist()
ax.set(xlabel='Exact share (%)', ylabel='Number of entries')
ax.axvline(threshold)
fig1 = ax.get_figure()
plt.close()
finalout.append(fig1)
if out['share_minimum']['Number of unique values'] > 0:
ax1 = df['share_minimum'].hist()
ax1.set(xlabel='Minimum share (%)', ylabel='Number of entries')
ax1.axvline(threshold)
fig2 = ax1.get_figure()
plt.close()
finalout.append(fig2)
if out['share_maximum']['Number of unique values'] > 0:
ax2 = df['share_maximum'].hist()
ax2.set(xlabel='Maximum share (%)', ylabel='Number of entries')
ax2.axvline(threshold)
fig3 = ax2.get_figure()
plt.close()
finalout.append(fig3)
return (finalout)
def q211(entityStatement):
"""
Description: Calculates the number of entities that have names
Arguments:
entityStatement: a pandas dataframe containing entity statements
Returns: a list containing i) a pandas dataframe of counts, and ii) a barplot of the same counts
"""
d = {'Name': [sum(entityStatement['name'].notna()),
sum(entityStatement['name'].isna())]}
out = pd.DataFrame(d, index=['Present', 'Missing'])
ax = out.plot.barh(legend=False)
ax.set(xlabel=None, ylabel='Number of entries')
fig = ax.get_figure()
plt.close()
return ([out, fig])
def q212(entityStatement, entityIdentifier):
"""
Description: Checks the breakdown of entity types across all entity statements, alongside the presence/absence of identifiers, to determine which types of entities provide identifying information.
Arguments:
entityStatement: a pandas dataframe containing entity statements
entityIdentifier: a pandas dataframe containing entity identifiers
Returns: a list containing i) a pandas dataframe of counts, and ii) a barplot of the same counts
"""
# Add a column determining if identifiers present and do a crosstab
es_subset = entityStatement.assign(identifiersPresent=entityStatement['_link'].isin(
entityIdentifier['_link_entity_statement']).tolist())[['identifiersPresent', 'entityType']]
out = pd.crosstab(es_subset['entityType'].fillna(
'Missing'), es_subset['identifiersPresent'].fillna('Missing'), margins=True)
if True not in out.columns:
out[True] = 0
if False not in out.columns:
out[False] = 0
if 'Missing' not in out.columns:
out['Missing'] = 0
out = out[[True, False, 'Missing', 'All']]
# Read in all person and entity types from codelist and append
etypes = read_codelist('https://raw.githubusercontent.com/openownership/data-standard/0.2.0/schema/codelists/entityType.csv',
case='camel')
alltypes = etypes+['All']
# Add missing codelists and fill with zero
out = out.reindex(index=alltypes, fill_value=0).rename(
columns={True: 'True', False: 'False'})
out = sortCounts(out)
# Plot
ax = out.drop(labels=['Total']).drop(
columns=['Total']).plot.barh(stacked=True)
ax.set(ylabel=None, xlabel="Number of entity statements")
fig = ax.get_figure()
plt.close()
return ([out, fig])
def q213(ownershipOrControlInterest, ownershipOrControlStatement, entityStatement):
"""
Description: Provides a breakdown of subjects in ownership or control statements according to whether at least one beneficial ownership or control interest is declared
Arguments:
ownershipOrControlInterest: a pandas dataframe containing ownership or control interests
ownershipOrControlStatement: a pandas dataframe containing ownership or control statements
entityStatement: a pandas dataframe containing entity statements
Returns: a list containing i) a pandas dataframe of counts, and ii) a barplot of the same counts.
"""
# Merge OOC and entity statement tables by subject
ooc_es = pd.merge(ownershipOrControlStatement.dropna(subset=['subject_describedByEntityStatement'])[['_link', 'subject_describedByEntityStatement']],
entityStatement[['statementID', 'entityType']],
left_on='subject_describedByEntityStatement',
right_on='statementID',
how='left')
# Now merge with interests
ooci_int = ownershipOrControlInterest[[
'_link_ooc_statement', 'beneficialOwnershipOrControl']].replace({True: 1, False: 0})
interestSums = ooci_int.groupby('_link_ooc_statement').agg(
beneficialOwnershipOrControl=pd.NamedAgg(
column='beneficialOwnershipOrControl', aggfunc=sum)
)
interestSums[interestSums > 1] = 1
interestSums['beneficialOwnershipOrControl'] = interestSums['beneficialOwnershipOrControl'].replace({
1: True, 0: False})
ooc_es_ooci = pd.merge(ooc_es,
interestSums,
left_on='_link',
right_on='_link_ooc_statement',
how='left')
# Crosstab of person types of with beneficial ownership
ownerCounts = pd.crosstab(ooc_es_ooci['entityType'].fillna(
'Missing'), ooc_es_ooci['beneficialOwnershipOrControl'].fillna('Missing'), margins=True)
if True not in ownerCounts.columns:
ownerCounts[True] = 0
if False not in ownerCounts.columns:
ownerCounts[False] = 0
if 'Missing' not in ownerCounts.columns:
ownerCounts['Missing'] = 0
out = ownerCounts[[True, False, 'Missing', 'All']]
# Read in all person and entity types from codelist and append
etypes = read_codelist('https://raw.githubusercontent.com/openownership/data-standard/0.2.0/schema/codelists/entityType.csv',
case='camel')
alltypes = etypes+['All']
# Add missing codelists and fill with zero
out = out.reindex(index=alltypes, fill_value=0)
out = sortCounts(out).rename(columns={
True: 'BO interests', False: 'Non-BO interests', 'Missing': 'BO data missing'})
# Barplot
ax = out.drop(columns=['Total'], index=['Total']
).plot.barh(stacked=True, color=cols)
ax.set(ylabel=None, xlabel="Number of OOC statements")
fig = ax.get_figure()
plt.close()
return ([out, fig])
def q214(ownershipOrControlStatement, entityStatement):
"""
Description: Provides a breakdown of entities by jurisdiction and counts the number of entities that do not list a jurisdiction. This is further broken down into whether entities are subjects or interested parties in ownership or control statements.
Arguments:
ownershipOrControlStatement: a pandas dataframe containing ownership or control statements
entityStatement: a pandas dataframe containing entity statements
Returns: a list containing i) a pandas dataframe of counts, and ii) a barplot of the same counts, with countries with fewer than 500 statements grouped together.
"""
# Get single column of entities with column idneitfying if they're subjects or interested parties
ooc_long = ownershipOrControlStatement.assign(type='Subject')[['subject_describedByEntityStatement', 'type']].rename(columns={'subject_describedByEntityStatement': 'statementID'}).append(
ownershipOrControlStatement.assign(type='Interested party')[['interestedParty_describedByEntityStatement', 'type']].rename(columns={'interestedParty_describedByEntityStatement': 'statementID'})).dropna()
# #Join to entity statemennts
ooc_es_long = pd.merge(ooc_long,
entityStatement[['statementID',
'incorporatedInJurisdiction_name']],
left_on='statementID',
right_on='statementID',
how='left')
out = pd.crosstab(ooc_es_long['incorporatedInJurisdiction_name'].fillna('Missing'),
ooc_es_long['type'].fillna('Missing'), margins=True)
out = sortCounts(out)
# Barplot - group countries with less than 500 ooc statements together
outplot = out.copy(deep=True)
outplot['jurisdictionOther'] = np.where(
outplot['Total'] > 500, outplot.index, 'Other')
outplot = outplot.groupby(['jurisdictionOther']).sum(
).sort_values(by=['Total'], ascending=False)
ax = outplot.drop(columns=['Total'], index=[
'Total']).plot.barh(stacked=True)
ax.set(ylabel=None, xlabel="Number of OOC statements")
fig = ax.get_figure()
plt.close()
return ([out, fig])
def q221(entityStatement):
"""
Description: Provides a count of reasons given for not displaying entity details, broken down by entity type, alongside the number of descriptions provided
Arguments:
entityStatement: a pandas dataframe containing entity statements
Returns: a list containing i) a pandas dataframe of counts, and ii) a barplot of the same counts
"""
unspecReason = pd.crosstab(entityStatement['unspecifiedEntityDetails_reason'].fillna('Missing'),
entityStatement['entityType'].fillna('Missing'),
margins=True)
unspecDescription = entityStatement.copy(deep=True)
if 'unspecifiedEntityDetails_description' in list(entityStatement):
unspecDescription['descriptionProvided'] = unspecDescription['unspecifiedEntityDetails_description'].notna()
else:
unspecDescription['descriptionProvided'] = False
unspecDescription = unspecDescription[[
'unspecifiedEntityDetails_reason', 'descriptionProvided']]
unspecDescription = unspecDescription.groupby(
['unspecifiedEntityDetails_reason']).sum()
out = pd.concat([unspecReason, unspecDescription], axis=1).fillna(int(0))
# Read in all entity types from codelist and append
reasontypes = read_codelist('https://raw.githubusercontent.com/openownership/data-standard/0.2.0/schema/codelists/unspecifiedReason.csv',
case='camel')+['Missing', 'All']
etypes = read_codelist('https://raw.githubusercontent.com/openownership/data-standard/0.2.0/schema/codelists/entityType.csv',
case='camel')+['Missing', 'All']
# Add missing codelists and fill with zero
out = out.reindex(index=reasontypes, columns=etypes +
['descriptionProvided'], fill_value=0)
out = sortCounts(out)
# Barplot
ax = out.drop(columns=['Total', 'Missing', 'descriptionProvided'], index=[
'Total', 'Missing']).plot.barh(stacked=True, color=cols)
ax.set(ylabel=None, xlabel="Number of OOC statements")
fig = ax.get_figure()
plt.close()
return ([out, fig])
def q222(personStatement):
"""
Description: Provides a count of reasons given for not displaying person details, broken down by person type, alongside the number of descriptions provided
Arguments:
personStatement: a pandas dataframe containing person statements
Returns: a list containing i) a pandas dataframe of counts, and ii) a barplot of the same counts
"""
unspecReason = pd.crosstab(personStatement['unspecifiedPersonDetails_reason'].fillna('Missing'),
personStatement['personType'].fillna('Missing'),
margins=True)
unspecDescription = personStatement.copy(deep=True)
if 'unspecifiedPersonDetails_description' in list(personStatement):
unspecDescription['descriptionProvided'] = unspecDescription['unspecifiedPersonDetails_description'].notna()
else:
unspecDescription['descriptionProvided'] = False
unspecDescription = unspecDescription[[
'unspecifiedPersonDetails_reason', 'descriptionProvided']]
unspecDescription = unspecDescription.groupby(
['unspecifiedPersonDetails_reason']).sum()
out = pd.concat([unspecReason, unspecDescription], axis=1).fillna(int(0))
# Read in all person types from codelist and append
reasontypes = read_codelist('https://raw.githubusercontent.com/openownership/data-standard/0.2.0/schema/codelists/unspecifiedReason.csv',
case='camel')+['Missing', 'All']
ptypes = read_codelist('https://raw.githubusercontent.com/openownership/data-standard/0.2.0/schema/codelists/personType.csv',
case='camel')+['Missing', 'All']
# Add missing codelists and fill with zero
out = out.reindex(index=reasontypes, columns=ptypes +
['descriptionProvided'], fill_value=0)
out = sortCounts(out)
# Barplot
ax = out.drop(columns=['Total', 'descriptionProvided'], index=[
'Total', 'Missing']).plot.barh(stacked=True)
ax.set(ylabel=None, xlabel="Number of person statements")
fig = ax.get_figure()
plt.close()
return ([out, fig])
def q223(entityStatement, personStatement):
"""
Description: Provides a set of unique descriptions for unspecified entities or persons:
Arguments:
entityStatement: a pandas dataframe containing entity statements
personStatement: a pandas dataframe containing person statements
Returns: a string with one line per unique description
"""
esout = []
psout = []
if 'unspecifiedEntityDetails_description' in list(entityStatement):
esout = esout + entityStatement[entityStatement['unspecifiedEntityDetails_description'].notna(
)]['unspecifiedEntityDetails_description'].unique().tolist()
esout = ['unspecified entity description: ' + item for item in esout]
if 'unspecifiedPersonDetails_description' in list(personStatement):
psout = psout + personStatement[personStatement['unspecifiedPersonDetails_description'].notna(
)]['unspecifiedPersonDetails_description'].unique().tolist()
psout = ['unspecified person description: ' + item for item in psout]
out = '\n'.join([str(len(esout)+len(psout)) +
' statements detected ---']+esout+psout)
return (print(out))
def q224(personStatement, minimumAge, maximumAge):
"""
Description: If age-based exemptions from declaration exist, provides a count of person statements are within and outside of the eligible age range.
Arguments:
personStatement: a pandas dataframe containing person statements
minimumAge: The youngest age for which declaration is permitted under reporting regime
maximumAge: The oldest age for which declaration is permitted under reporting regime
Returns: A list containig a dataframe of counts, and corresponding barplot of the same counts
"""
now = pd.Timestamp('now')
psdate = personStatement.copy(deep=True)
psdate['birthDate'] = pd.to_datetime(psdate['birthDate'])
psdate['birthDate'] = psdate['birthDate'].where(
psdate['birthDate'] < now, psdate['birthDate'] - np.timedelta64(100, 'Y'))
psdate['age'] = (now - psdate['birthDate']).astype('<m8[Y]')
d = {'Count': [sum((psdate['age'] >= minimumAge) & (psdate['age'] <= maximumAge)),
sum((psdate['age'] < minimumAge) |
(psdate['age'] > maximumAge)),
sum(psdate['age'].isna()),
len(psdate)]}
out = pd.DataFrame(data=d,
index=['Within eligible range', 'Outside eligible range', 'Missing', 'All'])
out = sortCounts(out)
# Barplot
ax = out.drop(index=['Total']).plot.barh(stacked=True)
ax.set(ylabel=None, xlabel="Number of person statements")
fig = ax.get_figure()
plt.close()
return ([out, fig])
def q311(personStatement, personNationalities, personIdentifiers, personNames, declaringCountry):
"""
Description: Provides a breakdown of presence/absence of birthdates, identifiers, names, for domestic and foreign nationals
Arguments:
personStatement: a pandas dataframe containing person statements
personNationalities: a pandas dataframe containing person nationalities
personIdenifiers: a pandas dataframe containing person identifiers
personNames: a pandas dataframe containing person names
declaringCountry: the two letter country code of the declaring country
Returns: A dataframe of counts, with comma separated values corresponding to number and proportion of non missing values
"""
ps_pnat = pd.merge(personStatement[['_link', 'birthDate']],
personNationalities[['_link_person_statement', 'code']],
left_on='_link',
right_on='_link_person_statement',
how='left').dropna()
ps_pnat[ps_pnat['code'] != declaringCountry] = 'other'
ps_pnat['birthDate'] = ps_pnat['birthDate'].notna()
ps_pnat['identifiers'] = ps_pnat['_link'].isin(
personIdentifiers['_link_person_statement'])
ps_pnat['name'] = ps_pnat['_link'].isin(
personNames['_link_person_statement'])
out = ps_pnat[['code', 'birthDate', 'identifiers', 'name']
].groupby(['code']).sum().transpose()
meanout = ps_pnat[['code', 'birthDate', 'identifiers', 'name']].groupby(
['code']).mean().transpose().round(2)
out[declaringCountry] = out[declaringCountry].astype(
str).str.cat(meanout[declaringCountry].astype(str), sep=', ')
out['other'] = out['other'].astype(str).str.cat(
meanout['other'].astype(str), sep=', ')
out = sortCounts(out)
return (out)
def q312(personIdentifiers):
"""
Description: Provides a breakdown of identifiers
Arguments:
PersonIdenifiers: a pandas dataframe containing person identifiers
Returns: A list contaning a dataframe of counts, and a corresponding barplot
"""
out = personIdentifiers['scheme'].fillna(
'Missing').value_counts().to_frame()
out = sortCounts(out)
# Barplot
ax = out.plot.barh(legend=False)
ax.set(ylabel=None, xlabel="Number of identifier statements")
fig = ax.get_figure()
plt.close()
return ([out, fig])
def q313(personNationalities):
"""
Description: Provides a breakdown of person nationalities
Arguments
personNationalities: a pandas dataframe containing person identifiers
Returns: A list containing a dataframe of counts, and a corresponding barplot, with countries with less than 500 entries grouped as other
"""
out = personNationalities['name'].fillna(
'Missing').value_counts().to_frame()
out = sortCounts(out)
# Barplot
outplot = out.copy(deep=True)
outplot['nameOther'] = np.where(
outplot['name'] > 500, outplot.index, 'Other')
outplot = outplot.groupby(['nameOther']).sum(
).sort_values(by=['name'], ascending=False)
ax = outplot.plot.barh(legend=False)
ax.set(ylabel=None, xlabel="Number of nationality statements")
fig = ax.get_figure()
plt.close()
return ([out, fig])
def q314(personStatement):
"""
Description: Provides a breakdown of person birth years
Arguments:
personStatement: a pandas dataframe containing person statements
Returns: A dataframe of counts by decade, and a corresponding histogram showing distribution by birth year
"""
out = personStatement.copy(deep=True)['birthDate'].to_frame()
out['birthDate'] = pd.to_datetime(out['birthDate'],errors='coerce')
out['birthYear'] = pd.DatetimeIndex(out['birthDate']).year/10
out['birthDecadeStart'] = out['birthYear'].apply(np.floor)*10+1
out['birthDecadeEnd'] = out['birthDecadeStart']+9
out['birthYear'] = out['birthYear']*10
out = out[['birthDecadeStart', 'birthDecadeEnd',
'birthYear']].dropna().astype(int)
out['birthDecade'] = out['birthDecadeStart'].astype(
str).str.cat(out['birthDecadeEnd'].astype(str), sep='-')
finalout = out['birthDecade'].value_counts(
sort=False).to_frame().sort_index()
# Barplot
ax = out['birthYear'].hist(color=cols[0])
ax.set(ylabel="Frequency", xlabel="Birth year")
fig = ax.get_figure()
plt.close()
return ([finalout, fig])
def q315(personTaxResidencies):
"""
Description: Provides a breakdown of tax residencies NOT CHECKED
Arguments:
personTaxResidencies: a pandas dataframe containing person tax residencies
Returns: A list containing a dataframe of counts by tax residency, and a corresponding barplot of the same counts
"""
out = personTaxResidencies['name'].fillna(
'Missing').value_counts().to_frame()
out = sortCounts(out)
# Barplot
ax = out.plot.barh(legend=False)
ax.set(ylabel=None, xlabel="Number of identifier statements")
fig = ax.get_figure()
plt.close()
return ([out, fig])
def q321(entityIdentifiers):
"""
Description: Provides a breakdown of entity identifiers
Arguments:
entityIdentifiers: a pandas dataframe containing entity identifiers
Returns: A list contaning a dataframe of counts, and a corresponding barplot
"""
out = entityIdentifiers['scheme'].fillna(
'Missing').value_counts().to_frame()
out = sortCounts(out)
# Barplot
outplot = out.copy(deep=True)
outplot['schemeOther'] = np.where(
outplot['scheme'] > 500, outplot.index, 'Other')
outplot = outplot.groupby(['schemeOther']).sum(
).sort_values(by=['scheme'], ascending=False)
ax = outplot.plot.barh(legend=False)
ax.set(ylabel=None, xlabel="Number of identifier statements")
fig = ax.get_figure()
plt.close()
return ([out, fig])
def q322(entityAddresses):
"""
Description: Provides a breakdown of entity addresses
Arguments:
entityAddresses: a pandas dataframe containing entity addresses