-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathsession3_from_nb.py
More file actions
926 lines (478 loc) · 14 KB
/
session3_from_nb.py
File metadata and controls
926 lines (478 loc) · 14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
#!/usr/bin/env python
# coding: utf-8
# # Session 3: Python commands and variable types.
# ## [EAA - ARC Python Primer for Accounting Research](https://martien.netlify.app/book/example/)
# #### This notebook explains the main Python variable types. It uses a file with Bank Holding Company financial data from the National Information Center.
# Click [here](https://www.ffiec.gov/npw/FinancialReport/FinancialDataDownload?selectedyear=2020) to download the file [BHCF20201231.ZIP](https://www.ffiec.gov/npw/FinancialReport/FinancialDataDownload?selectedyear=2020) and save it file to a folder on your PC, e.g. `D:/Users/myusername/EAA_python/code/`.
#
# Note, the file is a csv file, but you **do not** have to **unzip** the file!
#
# ---
#
# The cells below demonstrate the following data types:
#
# + Strings
# + Integers
# + Tuples
# + Floats
# + Booleans
# + Date variables
# + Lists
# + Dictionaries
#
# The cells below also demonstrate:
#
# + if-then-else statements
# + pretty printing numbers
# + a function that acts like a judge
#
# The output of this notebook generates a data frame that it exports to Stata, including the variable labels.
#
# ---
# Open Spyder or a Jupyter notebook and make a habit of entering these three lines in the editor pane (Spyder) or cell (Jupyter).
#
# ---
# In[ ]:
import os
import pandas as pd
import numpy as np
# ---
#
# Using the following commands, I set the working folder, the location on your hard drive where you will store data for this session.
# In[ ]:
if os.name=='nt': # for Windows users
os.chdir('D:/users/martien/EAA_python/code/') # note the forward slashes, change 'martien' to your user name
else:
os.chdir('/home/martien/EAA_python/code/') # For Linux or Mac
# Press \[CTRL-ENTER\] to execute the cell code.
#
# ---
#
# Note that I use cells in the Jupyter to execute bits of code. Spyder has the same functionality if you add
#
# `#%%`
#
# `before and after`
#
# `#%%`
#
# your code snippet.
#
# ---
# Download 'BHCF20201231.ZIP' from [https://www.ffiec.gov/npw/FinancialReport/FinancialDataDownload?selectedyear=2020](https://www.ffiec.gov/npw/FinancialReport/FinancialDataDownload?selectedyear=2020)
# and save it to the folder mentioned in the cell above.
# ---
# #### My first **string**: `fname`.
#
# I assign the string 'BHCF20201231.ZIP' to the variable `fname`:
# In[ ]:
fname = 'BHCF20201231.ZIP'
print(fname)
# I use the string to load the Bank Holding Company financial data from the folder `../EAA_python/code/`, see the explanation above.
#
# Normally you can use the command `df = pd.read_csv(fname)`, but that generates an ugly error message.
#
# Instead I use:
# In[ ]:
df = pd.read_csv(fname, sep='^', encoding = "ISO-8859-1", low_memory=False)
# Which aknowledges the funny separator (^) the FED uses as a field separator, the file encoding, and the fact that it is a big file.
#
# We do not have to worry about the fact that the file is compressed (zip).
#
# ---
# Very basic string manipulations:
# In[ ]:
fname = 'BHCF20201231' + '.ZIP'
print(fname)
# In[ ]:
fname = fname.lower()
print(fname)
fname = fname.upper()
print(fname)
# Trimming
# In[ ]:
fname = " " + fname + " "
print(fname,'.')
fname = fname.strip()
print(fname)
# Explore the file using head and tail:
# In[ ]:
df.head()
# In[ ]:
df.tail()
# #### My first **Integer**: `nrows`.
# This shows the number of rows in the data frame.
# In[ ]:
nrows = len(df)
print(nrows)
# ---
# Count the number of valid observations for Total Assets (BHCK2170)
# In[ ]:
n_of_ta = df['BHCK2170'].count()
print(n_of_ta)
# ---
# #### My first **tuple**: `coordinate`.
# In[ ]:
coordinate = (47.559601, 7.588576)
coordinate[0]
# In[ ]:
coordinate[1]
# #### Another **Tuple**:
# In[ ]:
nrows, ncols = df.shape
print(nrows, ncols)
# In[ ]:
len(df)
# In[ ]:
df.shape[0]
# In[ ]:
df.shape[1]
# ---
# #### My first **float**: `max_ta`.
# In[ ]:
max_ta = df['BHCK2170'].max()
max_ta
# In[ ]:
min_ta = df['BHCK2170'].min()
min_ta
# #### Printing
# In[ ]:
print(max_ta)
print()
print('Maximum value of Total assets: ', max_ta)
print('Maximum value of Total assets: ', int(max_ta)) # convert to integer
print('Maximum value of Total assets: {:,.0f}'.format(max_ta)) # format method version
print(f"Maximum value of Total assets: ${max_ta:,.0f}, minimum value: ${min_ta:,.0f}") # f-string version
print(f"\nMaximum value of Total assets: ${max_ta:,.0f}, minimum value: ${min_ta:,.0f}\n(in thousands).")
# ---
# #### In 2006, the threshold for filing FR Y-9C forms changed from \\$150 million in total assets to \\$500 million in total assets.
# Before we can check if smaller banks file the form nevertheless, we should divide Total Asset values by 1,000, convert values to millions:
# In[ ]:
min_ta = min_ta / 1000
min_ta
# But easier is this, using the division operator followed by the equal sign:
# In[ ]:
min_ta = df['BHCK2170'].min() # Obain again the minimum value for Total Assets:
print(min_ta)
min_ta /= 1000
print('Minumum valube of Total assets, in millions: ${:,.2f}'.format(min_ta))
# Likewise, using the same method for adding numbers:
# In[ ]:
a = 1
print(a)
a += 1
print(a)
# ---
# #### The **if-statement**:
# In[ ]:
print('Total assets, lowest value in data frame: ${:,.0f} million.'.format(min_ta))
if min_ta > 500:
print('Above threshold')
else:
print('Below threshold')
# Note the indents, which is characteristic for Python
#
# Likewise:
# In[ ]:
if max_ta/1000 > 500:
print('Above threshold')
else:
print('Below threshold')
# ---
# Most operators are straightforward: + - * / etc. See for documentation this [site](https://www.w3schools.com/python/python_operators.asp).
#
# But note these two:
# In[ ]:
min_ta ** 2 # squared
# In[ ]:
min_ta ** 0.5 # square root
# ---
# #### My first **boolean** variable: `low_mem`.
# In[ ]:
low_mem = False
df = pd.read_csv(fname, sep='^', encoding = "ISO-8859-1", low_memory=low_mem)
# Note that the result of `ncols == nrows` in the if-statement below is a boolean:
# In[ ]:
if ncols == nrows:
print('Square dataframe')
else:
print('Rectangular dataframe')
# If-statements can take up many lines.
#
# The **ternary operator**, however, allows you to write an if-statement in a single line:
# In[ ]:
guilty = True
verdict = "Innocent" if not guilty else "Guilty"
print(verdict)
# Let's write a function and play judge:
# In[ ]:
def judge(guilty_or_not):
verdict = "innocent" if not guilty_or_not else "guilty"
return 'The defendant is '+verdict
judge(True)
# In[ ]:
judge(False)
# Likewise:
# In[ ]:
text = "Square " if ncols == nrows else 'Rectangular '
print(text + 'dataframe')
# If-statement with multiple choices:
# In[ ]:
if ncols == nrows:
print('Square dataframe')
elif ncols > nrows: # you can add more elifs
print('Wide dataframe')
else:
print('Narrow dataframe')
# ---
# #### My first **datetime** variabele: `datadate`
#
# To work with date variables, please import the datetime library first:
# In[ ]:
from datetime import datetime
# In[ ]:
datadate = df['RSSD9999'].max()
print(datadate)
# In[ ]:
datadate = df['RSSD9999'].min()
print(datadate)
datadate = str(datadate) # Turn into a string
print(datadate)
datadate = datetime.strptime(datadate, '%Y%m%d') # Convert to a datetime variable
print(datadate)
# Once a datetime variable, Python can properly work with it:
# In[ ]:
datadate.strftime('%m-%d-%Y') # String from time
# In[ ]:
datadate.strftime('%d %m %y') # String from time
# Extract year, month, day, quarter
# In[ ]:
print(f"Year: {datadate.year}")
print(f"Month: {datadate.month}")
print(f"Day: {datadate.day}")
print(f"Quarter: {(datadate.month-1)//3+1}")
# ---
# More flexible is the use of `parser`, which copes with most date formats:
# In[ ]:
from dateutil.parser import parse
print(parse("31;12;2001"))
# In[ ]:
# and for U.S. notation:
print(parse("9/11/2001", dayfirst=False))
# ---
# Calculations with dates: lapsed days.
# In[ ]:
delta = datetime.now() - datadate
print(f"Days from year-end of the data frame: {delta.days}")
# ---
# Calculations with dates: determine a future date.
# In[ ]:
from datetime import timedelta
fdate = datadate + timedelta(90) # Filing deadline assumed to be 90 days after year-end
print(fdate)
fdate = fdate.strftime('%d/%m/%Y')
print(f"10K filing date: " + fdate)
# ---
# #### My first **list**: `months`
# In[ ]:
months = 'JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC' # String
print(months + '\n')
months = months.split(",")
print(months)
# Likewise:
# In[ ]:
month_num = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
print(month_num)
# #### Slicing lists
#
# The syntax for slicing is `list[start:stop:step]`.
#
# Note that Python counts from zero, not one:
# In[ ]:
months[0:3]
# In[ ]:
months[5:]
# In[ ]:
months[-3:]
# In[ ]:
months[-6:-3]
# In[ ]:
col_names = df.columns
print(list(col_names)[0::100]) # I am not going to list all variables!
# #### Reversing lists
# In[ ]:
months[::-1]
# Adding to list:
# In[ ]:
month_num = month_num + [13]
month_num
# Deleting from list:
# In[ ]:
del month_num[11] # position
month_num
# Restoring that list:
# In[ ]:
month_num = list(range(1, 13))
month_num
# Removing from list
# In[ ]:
months.remove('DEC')
months
# Restoring that list:
# In[ ]:
months = months + ['DEC']
months
# ---
# Sorting lists
# In[ ]:
month_num.sort()
month_num
# In[ ]:
month_num.sort(reverse = True)
month_num
# Restoring order:
# In[ ]:
month_num.sort()
print(month_num)
# ---
# ### List comprehension
#
# List comprehension allows one to quickly iterate over a list. This is often much more efficient than using a traditional for-next loop:
#
# ---
#
# The hard way:
# In[ ]:
for x in range(0, 12):
print(x, months[x])
# ---
# It is better to use this instead:
# In[ ]:
for x in months:
print(x)
# The approaches above create a variable (`x`), which we probably won't use going forward.
# In[ ]:
print(x)
# Let's try list comprehension, which creates a new list:
# In[ ]:
[y for y in months]
# In[ ]:
'y' in locals() # No y-variable to be seen!
# I can also edit the items in the list, for example by adding a characters (`Q-`) before the month:
# In[ ]:
["Q-"+x for x in months]
# Or select months starting with a `J` and convert them to lower case:
# In[ ]:
[x.lower() for x in months if x.startswith('J')]
# ---
# Select from the data frame the variables that contain text:
# In[ ]:
text_cols = [x for x in df if x.startswith('TEXT')]
print(len(text_cols))
print()
print(text_cols[::10])
# Selecting column names starting with `RSSD`:
# In[ ]:
rssd_cols = [x for x in df if x.startswith('RSSD')]
print(len(rssd_cols))
print()
print(rssd_cols[::5])
# Selecting all other column names:
# In[ ]:
bhc_cols = [x for x in df if not x.startswith('RSSD') and not x.startswith('TEXT')]
print(len(bhc_cols))
print()
print(bhc_cols[::100])
# Extracting the numbers from the RSSD variable codes ending with '9', then convert them in to integers:
# In[ ]:
[int(x[-4:]) for x in rssd_cols if x.endswith('9')]
# ---
# #### My first **dictionary**: `weekday`
#
# Dictionaries are the Python equivalent of `=vlookup()` in Excel, but much more versatile of course!
# In[ ]:
weekday = {"Mon": 0, "Tue": 1, "Wed": 2, "Thu": 3, "Fri": 4, "Sat": 5, "Sun": 6}
weekday["Thu"]
# Deleting a key-value pair, I don't like Mondays:
# In[ ]:
del weekday['Mon']
weekday
# Adding a key-value pair:
# In[ ]:
weekday['Mon'] = 0
weekday
# Check before adding
# In[ ]:
if "Sun" in weekday:
print("Sunday is definitively there!")
else:
print("Sunday is missing.")
# Alternatively, using `.keys()`
# In[ ]:
someday = 'Sun'
if someday in weekday.keys():
print(f"{someday}day is definitively there!")
else:
print(f"{someday}day is missing :-(")
# Likewise, using `.values()`
# Check if a value is present in the dictionary:
# In[ ]:
somedaynum = 1
if somedaynum in weekday.values():
print(f"{str(somedaynum)} is definitively there!") # convert somedaynum to a string first, using str()
else:
print(f"{str(somedaynum)} is missing :-(") # convert somedaynum to a string first, using str()
# ---
# Iterating over a dictionary:
# In[ ]:
for key, value in weekday.items():
print('Key:', key, '- Value:', value)
# More efficient is this:
# In[ ]:
[key for key, value in weekday.items()] # keys
# In[ ]:
[value for key, value in weekday.items()] # values
# In[ ]:
[key for key, value in weekday.items() if value == 3] # select a key-value pair
# Dictionary comprehension - create a new dictionary from an existing one:
# In[ ]:
{key:value+1 for (key, value) in weekday.items()}
# Flipping keys and values of a dictionary:
# In[ ]:
dayweek = {value: key for key, value in weekday.items()}
dayweek
# In[ ]:
dayweek[0]
# Obtain values using `.get()`. This does not give an error if a key is missing. Instead it returns 'None' or a variable of choice:
# In[ ]:
print(weekday.get('Sun'))
print(weekday.get('Sin'))
print(weekday.get('Sin', "The key doesn't exist"))
# ---
# Create a dictionary from two lists:
# In[ ]:
print(month_num)
print(months)
# In[ ]:
monts_dict = dict(zip(month_num, months))
monts_dict
# ---
# We can apply this to our dataframe to generate lables for the variable columns.
#
# The labels are from the Micro Data Reference Manual [MDRM](https://www.federalreserve.gov/apps/mdrm/).
# In[ ]:
list(df)[::200] # these are the variable names in the data frame, way too many, so I list every 200-th item:
# We want the names of some of the items in the data frame:
# In[ ]:
var = ['RSSD9001', 'RSSD9999', 'BHCK2170', 'BHCK3210']
labels = ['ID RSSD', 'Reporting date', 'Total Assets', "Total Equity Capital"]
# In[ ]:
df[var].head(10)
# The dictionary:
# In[ ]:
bhc_dict = dict(zip(var, labels))
bhc_dict
# ---
# We can now export these four variables to Stata, including the lables.
# In[ ]:
df[var].to_stata('my_first_stata_output.dta', write_index=False, version=114, variable_labels=bhc_dict)