-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BalanceSheet.py
2067 lines (1501 loc) · 71.3 KB
/
BalanceSheet.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
#Accounting Rules:
## Rule1: Accounting Equation: totalAssets == totalLiabilities + totalEquities
## Rule2: NetWorth : totalAssets - totalLiabilities == totalEquities
##Note: the equations above are equivalent, in addition.
## Rule3: bookValue of totalEquities calculated by : totalAssets less totalLiabilities. if its value is different than `totalEquities`
"""
Created on Fri Apr 7 09:24:32 2023
@author: Ahmad Lutfi
"""
"""
TODO:
totalLiabilities -> totalLiabilitiesSubtotal [done]
totalEquities -> totalEquitiesSubTotal
"""
"""
# Accounting Rules:
# Rule1: Accounting Equation: totalAssets == totalLiabilities + totalEquities
# Rule2: NetWorth : totalAssets - totalLiabilities == totalEquities
# Note: the equations above are equivalent, in addition.
# Rule3: bookValue of totalEquities calculated by : totalAssets less totalLiabilities. if its value is different than `totalEquities`
If that is the case, then further `Auditing` Might be required (to discover the source of error, and `mis-balanced` accounts, in Accounting ).
"""
# class partialEntry:
# 5.1.1. Using Lists as Stacks
"""
The list method` make it is easy to use a list as a stack,
where the last element added at the first, element ( that is retrieved )
(“last-in, first-out”). To add an item to the top of the stack, use append().
-To retrieve an item from the top of the stack,
-use pop() without an explicit index. For example:
>>>
stack = [3, 4, 5]
stack.append(6)
stack.append(7)
stack
[3, 4, 5, 6, 7]
stack.pop()
7
stack
[3, 4, 5, 6]
stack.pop()
6
stack.pop()
5
stack
[3, 4]
"""
""" a list of items """
# using list as stack
"""
def add(lst, i):
"""
# adds a new name, and price
"""
lst.
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
pass
def print():
print(thislist)
pass
"""
class Dict():
def __init__(self):
self.d = {}
def add():
pass
"""
add( name, price)
{'cash': 2000, 'AccountsRecievable': 5000, 'bankAccount': 10000}
"""
def print():
pass
# for i, v in enumerate(['one', 'two', 'three']):
# print(i, v)
# Idea:
class partialEntry:
""" Captures a specific part of a `transaction` which can either assume the drSide or the crSide
Purpose: acts as a bridge, between a `Report` (balanceSheet in this module`)and a `Transction` (of a Journal Entry )
- Hint: when we interact with a `Transaction`, we only need a part of it: let it be its Debit Side ( or its Credit Side).
-If we could only add that, as a function, in a transaction class, instead,
then, we would have made things more "Straight-Forward, & easy
(For all users: developers & end-users alike)
"""
def __init__(self, drSide, crSide, amount, isDebit=True, MsgError="Unexpected Error Occured, please recheck input, then retry"):
# Check `isDebit` flag , if so, return the ``drSide` Object & the amount
if isDebit == True:
self.transactionSide = drSide
self.amount = amount
# return self.transactionSide, self.amount
# otherwise, return `crSide` and the amount provided (in the consructor )
elif isDebit == False:
self.transactionSide = crSide
self.amount = amount
# return self.transactionSide, self.amount
else:
raise ValueError(MsgError)
# in a constructor, cannot return ,thus, we create a function getTransactionSide, returns above are both equal
def getTransactionSide(self):
""" returns a transaction side, and the amount (of the `partialEntry`)
(whether it's a debit, or a credit side)
"""
return self.transactionSide, self.amount
# Now we can capture any part (of any transaction ) with its corresponding amount, accordingly
# Take the debit side (of a transaction) with its amount
# debitSide when `1isDebit` equals `True`
pEntry1 = partialEntry("cash", "bankAccount", 100, isDebit=True)
transactionside, amount = pEntry1.getTransactionSide()
print("debit Side = ", transactionside, " , amount = ", amount)
# Seemingly,take the credit side (of a transaction) with its amount
# creditside when `isDebit` equals `False`
pEntry2 = partialEntry("cash", "bankAccount", 100, isDebit=False)
transactionside, amount = pEntry2.getTransactionSide()
print("credit Side = ", transactionside, " , amount = ", amount)
# E.g. for the balance sheet: we can take `cash`, add it into i.e. `currentAssetNames` list, with its amount,
# and creditside: `bankAmount` into currentEquitiesname` list with its amount, as well.
"""
name: str ,price : float
1. Creating a new class creates a new type of object,
2. Allowing new instances of that type to be made.
3. Each class instance can have many attributes (attached to it) for maintaining its state.
4. Class instances can also have methods (defined by its class) for modifying its state.
"""
class Report:
dict = {} # dictionary is the not a very efficient, it holds name, and price
# as we could possibly have endless years, going back in time, each with different values
# It's better to zip whichever years with values, with functions, to get the subTotal
def iterateSubtotals(subTotals, printFunction=None):
_sum = 0
for item in subTotals:
_sum += item
return _sum
def __init__(self, names, prices):
pass
# def calcSubtotal(self):
# pass
def getSubtotal(self, subTotal):
self.subTotal = subTotal
CAprice2020 = [38016, 52927, 16120, 4061, 21325, 11264]
# subTotalCA2020 = iterateSubtotals(CAprice2020)
subTotalCA2020 = Report.iterateSubtotals(CAprice2020)
# class-agnostic , static function
# APPL's data: @credit: : investopedia:
# image url source: https://www.investopedia.com/thmb/gUuGSjZWpXoc2miE2QfC-Z4Q6no=/1500x0/filters:no_upscale():max_bytes(150000):strip_icc()/phpdQXsCD-3c3af916d04a4afaade345b53094231c.png
# Balance Sheet's "positive-side" includes the following debit accounts :
# 1. Assets : ["Cash", "marketable security", "Account recievable"
# 2. SOCI "statementt of Comprehensive Income : "Inventories", "Vendor"
# 3. CashFlow "statement of Cash Flows"
"""
Q. Why expense is a debit account?
Q. Why are expenses debited?
A. no answer [direct answer]
Hint: `Expenses` cause `stockholder equity` to decrease
Value is not made, but is transformed, from one form to another
thus it is conserved
Dr DrAccount -> [Increase ]
# transaction Example:
# Scenario: Incremenental Transaction:
Dr cash 1000 [UP] [Asset grows]
Cr Bank Account 1000 [UP] [(theoretical bank) Account also grows ]
# -----------
def __ ( | context = Bank Account (Personal | owned) )
1. bank account(virtual) grows by the Asset invested in it (cash) by 1000
2. bank account is increased the same amount of cash depositied into that account
3. This context is limited to: the (context) bank account (Personal)
# -----------
Dichotomy:
Issue:
As of result, the `pocket Money` account is now less by 1000
def __ ( | context =`pocketMoney` Account )
# `pocketMoney` Account
# Cash on hand : becomes less (by a 1000)
we should also write this
As an `Expense` of opening a `bank Account` (by a 1000) [in local currency, in local time]
Dr Expense 1000 [UP] [Expense Increases]
cr Cash 1000 [Down] [Asset dimishes]
(Comment: being payment to `top-up` a bank account)
| Context: Pocket Money ( a liquid, personal account)
"""
# incomeStatement
"""asssumes there is a salary
and cogs (cost of goods sold)
"""
# code that bridges between partial Entry's output (value) and a list
# List CRUD ops:
# Create
def add(_lst, _value):
""" adds a value to a list"""
_lst.append(_value)
return _lst
def Insert(_lst, _idx):
pass
def updateAt(lst, idx=2, newValue=4):
""" update a `newValue` by an index """
oldIndex = idx
# Do computation (update):
# 1. Remove the value at`oldIndex`
lst = removebyIdx(lst, oldIndex)
# 2. Insert the `newValue` at the `oldIndex`
lst.insert(oldIndex, newValue)
# 3. return `lst`
def update(lst, oldValue=3, newValue=4):
""" Updates an `oldValue` with a new `newValue` , in a list `_lst """
# 1. store Index of `oldValue` in an `oldIndex`
oldIndex = lst.index(oldValue) # 1 #store old index
# Do computation (update):
# 1. remove `oldIndex`
lst = removebyIdx(lst, oldIndex)
# 2. insert the `newValue` at the `oldIndex`
lst.insert(oldIndex, newValue)
# 3. return `lst`
return lst
def remove(lst, _value):
""" removes value from lst , if it exists"""
_idx = lst.index(_value)
if not _idx is None:
# remove value in a `_lst`
del lst[_idx]
return lst
def removebyIdx(lst, _idx):
if not _idx is None:
# remove value in a `_lst`
del lst[_idx]
return lst
lst = [2, 3]
print("lst.index(3) = ", lst.index(3))
index = 3
newValue = 4
oldIndex = lst.index(3) # 1 #store old index
# Do computation (update):
# 1. remove
lst = removebyIdx(lst, oldIndex)
# insert
lst.insert(oldIndex, newValue)
print("new lst = ", lst)
# lst.insert(lst.index(3), 4)
print("lst, post-modification= ", lst)
# def update(_lst, _oldValue, _newValue):
# pass
# class BalanceSheet(Report): # TODO: complete
# TODO: partial Entry : depends upon it
def iterateSubtotals(subTotals, printFunction=None):
_sum = 0
for item in subTotals:
_sum += item
return _sum
# TODO: do sth useful, for the printFunction
# Demo : Balance sheet
# currentAssets:
# names:
# Current Assets
# date Precedence: from newest, to oldest: 2020, 2019
currentAssets = ["Cash", "marketable security", "Account recievable",
"Inventories", "Vendor", "other currentAssets"] # Dt accounts
CAprice2020 = [38016, 52927, 16120, 4061, 21325, 11264]
subTotalCA2020 = iterateSubtotals(CAprice2020)
print("current Assets Subtotal 2020 = ", subTotalCA2020)
CAprice2019 = [48844, 51713, 22926]
years = [CAprice2020, CAprice2019] # TODO: later
# subtotalCurrentAssets2019 = iterateSubtotals(CAprice2019) # TODO: compre with later
# for y in years no (take in the Same Year, first
# nonCurrentAssets:
nonCurrentAssets = ["Marketable Securities",
"Property, plant", "equipment net"]
nCA2020 = [100887, 36766, 42522]
subTotalNonCurrentAssets = iterateSubtotals(nCA2020)
print("Subtotal 2020 = ", subTotalNonCurrentAssets)
totalAssets = subTotalCA2020 + subTotalNonCurrentAssets
print("total Assets 2020 = ", totalAssets)
# lvl 2
# Ratios:
""" Ratios:
CashRatio = cash / CurrentLiabilities
CurrentRatio = CurrentAssets / CurrentLiabilities
Quick Ratio = (Cash & Equivalents + Accounts Receivable (A/R) / CurrentLiabilities
"""
def cashRatio(cash, CurrentLiabilities):
"""Cash Ratio = Cash / Current Liabilities."""
return cash / CurrentLiabilities
def currentRatio(CurrentAssets, CurrentLiabilities):
""" CurrentRatio = CurrentAssets / CurrentLiabilities"""
return CurrentAssets / CurrentLiabilities
def quickRatio(cashEquivalents, aReceivable, currentLiabilities):
"""
Quick Ratio = (Cash & Equivalents + Accounts Receivable (A/R) / CurrentLiabilities
source: https://www.investopedia.com/terms/a/accountsreceivable.asp
Key Takeaways:
Accounts receivable (AR) are an asset account on the balance sheet
that represents money due to a company in the short term.
AR = Accounts receivable are created when a company lets a
buyer purchase their goods or services on credit.
"""
cashRecievable = cashEquivalents + aReceivable
quickRatio = cashRecievable / currentLiabilities
return quickRatio
# quickRatio = (cashRecievable / currentLiabilities )
"""
cashEquivalents = cashEquivalents + aReceivable
cashEquivalents / currentLiabilities
Cash & Equivalents + A/R) / CurrentLiabilities
"""
"""
Lastly: estimate Doubtful Debt:
#:~:text=It%20estimates%20the%20allowance%20for,10%2C000%20x%200.05%20%3D%20500
Source: https://www.indeed.com/career-advice/career-development/allowance-for-doubtful-accounts
-Stimates the allowance for doubtful accounts [HOW?]: by multiplying the accounts receivable by:
1--"appropriate percentage" for the aging period
2 -- then adds the sum of those (2) totals together.
example: 2,000 x 0.10 = 200.
10,000 x 0.05 = 500.
"""
# for item in Assets
# total assets 2020 , 2019
# TODO: try running the function ,for different years
assets2020 = [CAprice2019, nCA2020]
# for item in assets2020:
# item
# subtotal:
# totalAssets
# ----
# Current Liabilities:
currentLiabilities = ["AccountsPayable", "other current Liabilities",
"Deferred revenue", "Commercial paper", "Term Debt"]
cl2020 = [42296, 42684, 6643, 4996, 8773]
# Noncurrent Liabilities
nonCurrentLiabilities = ["Term debt", "Other non-current Liabilities"]
ncl2020 = [98667, 54490]
subTotalCurrentLiabilities2020 = iterateSubtotals(cl2020)
subTotalNonCurrentLiabilities2020 = iterateSubtotals(ncl2020)
totalLiabilitiesSubtotal = subTotalCurrentLiabilities2020 + \
subTotalNonCurrentLiabilities2020
print("totalLiabilities = ", totalLiabilitiesSubtotal)
# ---
# Capital : is about
# Commitments & Contingencies , a.k.a
# Shareholder's equity
shareholderEquity = ["Common Stock", "Retained Earnings",
"Accumulated Other comprehensive income (loss)"]
shEquity2020 = [50779, 14966, -406]
shEquity2019 = [45174, 45898, -584]
subTotalEquities2020 = iterateSubtotals(shEquity2020) # get equity
print("subTotalEquity2020 = ", subTotalEquities2020)
totalEquities = subTotalEquities2020
# subEquity2019 = iterateSubtotals(shEquity2019)
# ---
# def calc_grossMargin():
# class Income Statement
def calcCogs(subTotals):
cogs = iterateSubtotals(subTotals)
return cogs
# def caclGrossMargin():
# TODO: move to new module]
# ---
# Balnace sheet [static ] methods
def isBalanced(totalAssetsSubTotal, totalLiabilitiesSubTotal, totalEquitiesSubTotal): # +
"""
Checks whether Accounts in the balanceSheet is balanced
By checking whether totalAssets equals: `totalLiabilities` plut `totalEquities`
Applies to the classical `Accounting Equation`
As: Assets = Liabilities + Equities
"""
# 1. Assign Variables
condition = totalAssetsSubTotal == totalLiabilitiesSubtotal + totalEquitiesSubTotal
return condition
def getDifference(LHS, RHS): # -
"""for networth
totalAssets + totalLiabilities == totalEquities """
return abs(LHS) - abs(RHS)
def setRhsLhs(totalAssetsSubTotal, totalLiabilitiesSubTotal, totalEquitiesSubTotal): # +
""" sets the left & right, for the Classical Accounting Equation : A = L + E """
LHS = totalAssetsSubTotal
RHS = totalLiabilitiesSubTotal + totalEquitiesSubTotal
return LHS, RHS
def getDifference2(totalAssetsSubTotal, totalLiabilitiesSubTotal, totalEquitiesSubTotal): # + = (-) == 0
""" Checks whether the sides (of a classical Accounting Equation are equal """
# LHS =?= LHS
# totalAssets == totalLiabilities + totalEquities
LHS, RHS = setRhsLhs(totalAssetsSubTotal,
totalLiabilitiesSubTotal, totalEquitiesSubTotal) # +
# If accounts are balanced, their total should be equal to 0
figure = getDifference(LHS, RHS)
# either Assets == Liabilities + Equities OR
# Assets - Liabilities -Equities == 0 OR Assets - (Liabilities +Equities) == 0
return figure
# Note: setRhsLhs (getDifference) != getNetWorth as:
# Rules:
# Rule1: AccountingEquation: totalAssets == totalLiabilities + totalEquities
# Rule2: Networth : totalAssets - totalLiabilities == totalEquities
# Networth
# getNetWorth(totalAssets, totalLiabilities)
# getRelationNetWorthAccouting():
# Note: from (1) we can arrive to formula (2) how: by subtracting both sides of (1) by totalLiabilities
def getRelationNetWorthAccounting(totalAssetsSubTotal, totalLiabilitiesSubTotal, totalEquitiesSubTotal, ErrorMsg="Unexpected error Occured, check input, then retry"):
""" gets relationship between `NetWorth` and `Accounting` Equation [How?]
by Asking:
What is the difference between equivalence relations of Accounting against NetWorth` ?
# accounting: totalAssets == totalLiabilities + totalEquities (1)
# networth: totalAssets - totalLiabilities == totaEquities (2) then:
# accounting == networth as
# accounting - networth == 0
# Only iff (tne Equivalence Relation Exists):
# totalAssets == (totalLiabilities + totalEquities) === (totalAssets - totalLiabilities) == totaEquities
or
totalAssets - totalLiabilities == totalEquities === (totalAssets - totalLiabilities) == totalEquities
# note2: it's enough to show (1) relation which equals to (from left equivalence Relation) :
totalAssets - totalLiabilities == totalEquities === ...
OR
totalAssets - totalLiabilities - totalEquities == 0 ===
or totalAssets - (totalLiabilities + totalEquities ) == 0
"""
# subtract totalLiabilities
LHS = totalAssetsSubTotal - totalLiabilitiesSubTotal - totalEquitiesSubTotal # 0
RHS = totalAssetsSubTotal - \
(totalLiabilitiesSubTotal + totalEquitiesSubTotal) # 0
condition = LHS == RHS # 0
if condition == True:
return True
elif condition == False:
return False
else:
raise ValueError(ErrorMsg)
def getNetWorth(totalAssetsSubTotal, totalLiabilitiesSubTotal): # ok
""" calculates `NetWorth` (original):
NetWorth = totalAssets - totalLiabilities ( == totalEquities ) """
LHS = totalAssetsSubTotal - totalLiabilitiesSubTotal # Rule: `Networth == totalEquities
RHS = totalEquitiesSubTotal
# setRhsLhs(totalAssets, totalLiabilities, totalEquities)
return abs(LHS) - abs(RHS)
# isNetworth(totalAssets, totalLiabilities, totalEquities)
def isNetworth(totalAssetsSubTotal, totalLiabilitiesSubTotal, totalEquitiesSubTotal): # New #checked
""" checks if accounts (Assets, Liabilities, Equities) are balanced, through
Evaluating the total of : (totalAssets - totalLiabilities) = + totalEquities
OR (this Equation is equivalent to): (totalAssets - totalLiabilities) - totalEquities = 0
"""
return (totalAssetsSubTotal - totalLiabilitiesSubTotal) - totalEquitiesSubTotal
# TODO: appply flip of `networth` parameter in implementation
def verifyNetWorth1(totalAssetsSubTotal, totalLiabilitiesSubTotal, networth):
""" verifies `NetWorth, by comparing it with `totalAssets` and `totalLiabilities` """
# networth = totalAssets - totalLiabilities == totalEquities [both sides should be equal]
# totalAssets - totalLiabilities
condition = networth == getNetWorth(
totalAssetsSubTotal, totalLiabilitiesSubTotal)
return condition
def verifyNetWorth2(networth, totalEquitiesSubTotal, ErrorMsg: str = "Exception Raised: Value Error, please check all inputs, then retry"):
""" Verify `NetWorth`against `totalEquitiesSubTotal`
- Hint: NetWorth (in business) is also referred to as Equity
- Applying the 3 condition logic: if, elif, else (raises an Error)
- with error handling: `ValueError` exceptions
"""
try:
# networth>0 and totalEquitiesSubTotal > 0
condition = networth == totalEquitiesSubTotal
if condition == False:
# pass
return condition
elif condition == True:
pass
# condition = networth == totalEquitiesSubTotal #True (or False)
return condition
else:
raise ValueError("Please Check Input then try again, later")
except ValueError:
print(ErrorMsg)
def printIsEqual(totalAssetsSubTotal, totalLiabilitiesSubTotal, totalEquitiesSubTotal):
""" Apply the accounting Equation : A = L + E
"""
RHS = totalAssetsSubTotal
LHS = totalLiabilitiesSubTotal + totalEquitiesSubTotal
print("totalAssets = ", totalAssetsSubTotal)
print("totalLiabilities = ", totalLiabilitiesSubTotal)
print("totalEquity = ", totalEquitiesSubTotal)
print("LHS = ", LHS)
print("RHS = ", RHS)
boolIsEqual = printIsEqual2()
return boolIsEqual
def printIsEqual2(LHS, RHS):
""" checks if both sides are equal: an alternative way that accountance use to verify accounts
- By calculating Owner's networth = Assets - Liabilities)
- In subtrcating: RHS from LHS (accounting terminology: `LHS` Less `RHS` )
"""
condition = RHS == LHS
return condition
totalAssetsSubTotal = 10000
totalLiabilitiesSubtotal = 5000
totalEquitiesSubtotal = 5000
totalEquitiesSubTotal = totalEquitiesSubtotal
RHS = totalAssetsSubTotal
LHS = totalLiabilitiesSubtotal + totalEquitiesSubtotal
print(" Right side = totalAssets = ", RHS)
print(" Left side = = totalLiabilities + totalEquities = ", LHS)
print("RHS == LHS = ", RHS == LHS)
RHS == LHS
equals = isBalanced(totalAssetsSubTotal,
totalLiabilitiesSubtotal, totalEquitiesSubTotal)
print("Accounts equal = ", equals)
print(" Right side = ", RHS)
print(" Left side = ", LHS)
# TODO: also do accounts balance (i.e. equal 0 )
print("Difference LHS-RHS= ", LHS-RHS)
print("Accounts Balnce : totalAssets + totalLiabilities = totalEquity \n",
"Right hand: Assets = ", RHS, "\n", " ", "Left hand side = Liabilities + Equity ", LHS,)
print("try1: is isBalanced = ", isBalanced(
totalAssetsSubTotal, totalLiabilitiesSubtotal, totalEquitiesSubtotal))
# DEMO 1:
# 1. Data Handling
# Example APPLE INC
# Consolidated Balance Sheet
# source: https://www.investopedia.com/terms/b/balancesheet.asp
# 1.1 current Assets
ca2020 = [38016, 52927, 16120, 4061, 21325, 11264]
subtotal1 = iterateSubtotals(ca2020)
print(subtotal1)
# 1.2. nonCurrent Assets
nca2020 = [100887, 36766, 42522]
subtotal2 = iterateSubtotals(nca2020)
print(subtotal2)
# 2. Total Assets:
totalAssets = subtotal1 + subtotal2
print("total Assets", totalAssets) # 323888
# --
# 1.1 currentLiabilities
cl2020 = [42296, 42684, 6643, 4996, 8773]
subtotal1 = iterateSubtotals(cl2020)
print(subtotal1)
# 1.2 nonCurrent Liabilities
ncl2020 = [98667, 54490]
subtotal2 = iterateSubtotals(ncl2020)
print(subtotal2)
# 2. Total Liabilities
totalLiabilities = subtotal1 + subtotal2
print("total Liabilities", totalLiabilities) # 258549
# Capital [ (Owner's) Equity ]
# 1. Current Equities
equity2020 = [50779, 14966, -406]
# 2. Total Equities
totalEquities = iterateSubtotals(equity2020)
print("totalEquities = ", totalEquities) # 65339
# --
# 2. Information Processing
# 2.1 isEqual(totalAssets, totalLiabilities, totalEquity)
_flag_isequal = isBalanced(
totalAssets, totalLiabilities, totalEquities) # isEqual()
# print("Accounts (in the accounting equation RHS = LHS : Assets+Liabilities = Equity",_flag_isequal)
# 2.2. getDifference2(totalAssets, totalLiabilities, totalEquity)
diff = getDifference2(totalAssetsSubTotal,
totalLiabilitiesSubtotal, totalEquitiesSubtotal)
# print("difference = ", diff)
# DEMO2:
assets = 302083 # 352755
liabilities = 152452 # 302083
equities = 149631
_flag_accepted = isBalanced(assets, liabilities, equities) # isEqual()
print("is equal = ", _flag_accepted)
# ( getDifference2(assets, liabilities, equities))
_diff = getDifference2(assets, liabilities, equities)
print("difference : ", _diff)
# As always, there is Stucture, just like in everything else
class balanceSheet:
"""
Balance is time oriented, usually a year ( in which we would stick to it )
We can do a balance (at any given moment: month, quarter, year) so we can get a gist of what we have, and do not have
- This we owe to others,
The things others owe to us
Finally, balance is important, as from it,we can get to the
Functions:
# CalcAssets
# calcCurrentAssetsSubTotal
# calcNonCurrentAssetsSubTotal(self,_nonCurrentAssets)
# calcAssets(self, _currentAssets, _nonCurrentAssets)
# calcCurrentLiabilitiesSubTotal(self, _currentLiabilities)
# calcNonCurrentLiabilitiesSubTotal(self, _nonCurrentLiabilities)
# calcTotalLiabilities(self, _currentLiabilities, _nonCurrentLiabilities )
"""
# Helper functions:
# iterateSubtotals
def iterateSubtotals(self, subTotals, printFunction=None):
_sum = 0
for item in subTotals:
_sum += item
return _sum
# def setTitle(self, title: str ):
# """ sets the title of a report instance """
# if not optionalDesc is None:
# self.description = optionalDesc
#
# self.title = title
# return title
# pass
def __init__(self, year: int, proprietor: str):
""" at each triad, there is a Duo """
self.proprietor = proprietor
self.year = year
# the sacred Triad of a BalanceSheet: 1. Asset 2. Liability 3. Equity
# 1. self.Assets :
# which is defined by the Duo:
self.currentAssets = []
self.nonCurrentAssets = []
self.totalAssetsSubtotal = 0
self.currentAssetsSubTotal = 0
self.nonCurrentAssetsSubTotal = 0
self.totalAssetsSubtotal = self.currentAssetsSubTotal + \
self.nonCurrentAssetsSubTotal # 0
# which is defined by the Duo:
# 2. Liabilities
self.currentLiabilities = []
self.nonCurrentLiabilities = []
self.totalLiabilitiesSubtotal = 0
self.currentLiabilitiesSubTotal = 0
self.nonCurrentLiabilitiesSubTotal = 0
self.totalLiabilitiesSubtotal = self.currentLiabilitiesSubTotal + \
self.nonCurrentLiabilitiesSubTotal # 0
# 3. Equities
# which is defined by :
self.currentEquities = []
self.currentEquitesSubTotal = 0
self.totalEquitiesSubtotal = 0
# self.nonCurrentEquity = []
# self.nonCurrentEquitySubTotal = 0
# Now: totalEquities == currentEquitiesSubtotal
self.totalEquitiesSubtotal = self.currentEquitesSubTotal # 0
def __init__2(self, year: int, proprietor: str, currentAssets, nonCurrentAssets, currentLiabilities, nonCurrentLiabilities,
currentEquities):
""" at each triad, there is a Duo """
self.proprietor = proprietor
self.year = year
# the sacred Triad of a BalanceSheet:
# self.Assets :
self.totalAssetsSubtotal = 0
# which is defined by the Duo:
self.currentAssets = currentAssets # []
self.nonCurrentAssets = nonCurrentAssets # []
self.currentAssetsSubTotal = self.iterateSubtotals(self.currentAssets)
self.nonCurrentAssetsSubTotal = self.iterateSubtotals(
self.nonCurrentAssets)
self.totalAssets = self.currentAssetsSubTotal + self.nonCurrentAssetsSubTotal
# self.Liabilities
self.totalLiabilities = []
self.totalLiabilitiesSubtotal = 0
# which is defined by the Duo:
self.currentLiabilities = currentLiabilities # []
self.nonCurrentLiabilities = nonCurrentLiabilities # []
self.currentLiabilitiesSubTotal = self.iterateSubtotals(
self.currentLiabilities)
self.nonCurrentLiabilitiesSubTotal = self.iterateSubtotals(
self.nonCurrentLiabilities)
self.totalLiabilitiesSubtotal = self.currentLiabilitiesSubTotal + \
self.nonCurrentLiabilitiesSubTotal
# self.equity
# which is defined by (~the Duo~) the mono `currentEquities`:
self.totalEquitiesSubTotal = 0
self.currentEquities = currentEquities # []
# self.nonCurrentEquity = []
self.currentEquitesSubTotal = self.iterateSubtotals(
self.currentEquities) # 0
# self.nonCurrentEquitySubTotal = 0
# Now: totalEquities == currentEquitiesSubtotal
self.totalEquitiesSubTotal = self.currentEquitesSubTotal # 0
# vital
def checkIsNone(self, x):
self.x = x
if self.totalLiabilitiesSubtotal is None:
raise ValueError(f"Inappropriate value for `{x}`")
# getTotalAssets# get totals from subtotals
def getTotalAssets1(self, currentAssetsSubTotal, nonCurrentAssetsSubTotal):
"""returns TotalAssets, from Subtotal of currentAssets, nonCurrentAssets """
# 1. Assign
self.currentAssetsSubTotal = currentAssetsSubTotal
self.nonCurrentAssetsSubTotal = nonCurrentAssetsSubTotal
# 2. Add
self.totalAssetsSubtotal = self.currentAssetsSubTotal + self.nonCurrentAssetsSubTotal
# 3. Return
return self.totalAssetsSubtotal
def getTotalAssets2(self, totalAssets):
"""Assigns and returns TotalAsset
gets the total if found to be of valid value, assign it, otherwise, raises a
`ValueError """
# 1.Assign
self.totalAssetsSubtotal = totalAssets
# checkIsNone
# self.checkIsNone(totalAssets)
# 2. Return
return self.totalAssetsSubtotal
def getTotalLiabilities1(self, currentLiabilitiesSubTotal, nonCurrentLiabilitiesSubTotal):
"""returns Liabilities, from Subtotal of `currentLiabilities`, `nonCurrentLiabilities`
gets the total if found to be of valid value, assign it, otherwise, raises a
`ValueError"""
# 1. Assign
self.currentLiabilitiesSubTotal = currentLiabilitiesSubTotal
self.nonCurrentLiabilitiesSubTotal = nonCurrentLiabilitiesSubTotal
# 2. Add
self.totalLiabilitiesSubtotal = self.currentLiabilitiesSubTotal + \
self.nonCurrentLiabilitiesSubTotal
# check for None : if so, error is raised
# self.checkIsNone(self.totalLiabilities)
# 3. Return
return self.totalLiabilitiesSubtotal
def getTotalLiabilities2(self, totalLiabilities):
"""Assigns and returns `totalLiabilities`, from Subtotal of `currentLiabilities`, `nonCurrentLiabilities` """
# 1. Assign
self.totalLiabilitiesSubTotal = totalLiabilities
# 2. Return `self.totalLiabilities`
return self.totalLiabilitiesSubTotal
def getTotalLiabilities3(self):
"""returns `totalLiabilities` stored in instance """
# 1. Return `self.totalLiabilities`
return self.totalLiabilitiesSubTotal
# nonCurrentEquitySubTotal):
# Rule: pre-check user-defined values (programming-logic), before they are run on business logic
# def getTotalEquities1(self):
# """ Returns totalEquities (from current """
# if not self.currentEquities is None:
# self.totalEquities = self.CurrentEquities
# return self.totalEquities
def getTotalEquities(self): # , nonCurrentEquitySubTotal):
"""returns Equities, from Subtotal of `currentEquities`, `nonCurrentEquities` """""" Assigns currentEquitySubtotal """
# 1. Return