-
Notifications
You must be signed in to change notification settings - Fork 105
Expand file tree
/
Copy pathfunctions.py
More file actions
2146 lines (1740 loc) · 73.3 KB
/
functions.py
File metadata and controls
2146 lines (1740 loc) · 73.3 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
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 math
import numpy as np
import pandas as pd
import math
import datetime
from dateutil.relativedelta import relativedelta
from typing import Union
from fastapi import FastAPI, HTTPException, Query
# Function to Calculate Simple Interest Rate
def simple_interest_rate(amount_paid: float, principle_amount: float, months: int):
term = months / 12
interest_paid = amount_paid - principle_amount
rate = decimal_to_percent(interest_paid) / (principle_amount * term)
return rate
# Calculate percent to decimal
# def percent_to_decimal(percent: int | float) -> float:
# return (percent / 100)
def percent_to_decimal(percent: Union[int, float]) -> float:
return (percent / 100)
# Calculate decimal to percent
def decimal_to_percent(decimal: Union[int, float]) -> float:
return decimal * 100
# Function to Calculate Loan Emi
def loan_emi(principle_amount: float, annual_rate: float, months: int):
monthly_rate = percent_to_decimal(annual_rate) / 12
emi = (principle_amount * monthly_rate * (1 + monthly_rate) ** months) / (
((1 + monthly_rate) ** months - 1)
)
return emi
def future_sip(
interval_investment: float, rate_of_return: float, number_of_payments: int
):
interest = percent_to_decimal(rate_of_return) / 12
value = (
interval_investment
* ((1 + interest) ** number_of_payments - 1)
* (1 + interest)
/ interest
)
return value
def payback_period(
years_before_recovery: int, unrecovered_cost: float, cash_flow: float
):
period = years_before_recovery + (unrecovered_cost / cash_flow)
return period
# Function to Calculate Compound Intrest
def compound_interest(
principal_amount: float, intrest_rate: float, years: int, compounding_period: int
):
amount = principal_amount * (
pow((1 + (intrest_rate / compounding_period)),
(compounding_period * years))
)
print(amount)
return amount
# Function to Calculate Inflation
def inflation(present_amount: float, inflation_rate: float, years: int):
future_amount = present_amount * (
pow((1 + percent_to_decimal(inflation_rate)), years)
)
return future_amount
# Function to Calculate Effective Annual Rate
def effective_annual_rate(annual_interest_rate: float, compounding_period: int):
EAR = pow((1 + (annual_interest_rate / compounding_period)),
compounding_period) - 1
return EAR
# Function to Calculate Certificate of Deposit (CD)
def certificate_of_deposit(
principal_amount: float, interest_rate: float, yrs: int, compounding_per_yr: int
):
cd = principal_amount * (
1 + interest_rate / decimal_to_percent(compounding_per_yr)
) ** (compounding_per_yr * yrs)
return float(cd)
# Function to Calculate Return on Investment
def return_on_investment(current_value_of_investment: float, cost_of_investment: float):
roi = (current_value_of_investment -
cost_of_investment) / cost_of_investment
return decimal_to_percent(roi)
# Function to calculate Jensens Alpha
def jensens_alpha(
return_from_investment: float,
return_of_appropriate_market_index: float,
risk_free_rate: float,
beta: float,
):
alpha = return_from_investment - (
risk_free_rate + beta *
(return_of_appropriate_market_index - risk_free_rate)
)
return alpha
# Function to calculate Weighted Average Cost of Capital (WACC)
def weighted_average_cost_of_capital(
firm_equity: float,
firm_debt: float,
cost_of_equity: float,
cost_of_debt: float,
corporate_tax_rate: float,
):
v = firm_debt + firm_equity
wacc = (firm_equity * cost_of_equity / v) + (
firm_debt * cost_of_debt * (1 - corporate_tax_rate) / v
)
return wacc
# Function to calculate variance of a two asset portfolio
def asset_portfolio(
price_A: float,
price_B: float,
retrun1: float,
return2: float,
standard_dev_A: float,
standard_dev_B: float,
stock_correlation: float,
):
weight_A = price_A / (price_A + price_B)
weight_B = price_B / (price_A + price_B)
cov = stock_correlation * standard_dev_A * standard_dev_B
portfolio_variance = (
weight_A * weight_A * standard_dev_A * standard_dev_A
+ weight_B * weight_B * standard_dev_B * standard_dev_B
+ 2 * weight_A * weight_B * cov
)
return portfolio_variance
# Function to calculate the future price in a put - call parity
def put_call_parity(call_price: float, put_price: float, strike_price: float):
future_price = call_price + strike_price - put_price
return future_price
# Function to calculate break even point
def break_even_point(fixed_cost: float, selling_price: float, variable_cost: float):
contribution_margin = selling_price - variable_cost
units = fixed_cost // contribution_margin
rupees = fixed_cost // (contribution_margin / selling_price)
return units, rupees
# Function to calculate free cash flow to firm
def free_cash_flow_to_firm(
sales: float,
operating_cost: float,
depreciation: float,
interest: float,
tax_rate: float,
fcInv: float,
wcInv: float,
):
ebitda = sales - operating_cost
ebit = ebitda - depreciation
ebt = ebit - interest
eat = ebt - ebt / (tax_rate * 0.01)
wcInv = abs(wcInv)
return (ebit * (1 - tax_rate * 0.01)) + depreciation - fcInv - wcInv
# Function to calculate the Price-to-Earning ratio (P/E ratio):
def price_to_earning_ratio(share_price: float, earnings_per_share: float):
p_e_ratio = share_price // earnings_per_share
return p_e_ratio
# Function to calculate the Dividend yield ratio:
def dividend_yield_ratio(dividend_per_share: float, share_price: float):
dividend_yield = dividend_per_share // share_price
return dividend_yield
# Function to calculate the dividend payout ratio
def dividend_payout_ratio(dividend_per_share: float, earnings_per_share: float):
dividend_payout = dividend_per_share // earnings_per_share
return dividend_payout
# Function to calculate the debt-to-income ratio (DTI ratio):
def debt_to_income_ratio(annual_income: float, total_debt_per_month: float):
income_per_month = percent_to_decimal(annual_income) / 12
DTI = total_debt_per_month // income_per_month
return DTI
# Function to calculate the Fixed-charge coverage ratio :
def fixed_charge_coverage_ratio(
earnings_before_interest_taxes: float,
fixed_charge_before_tax: float,
interest: float,
):
a = earnings_before_interest_taxes + fixed_charge_before_tax
b = interest + fixed_charge_before_tax
fccr = a // b
return fccr
# Function to calculate Inventory Shrinkage
def inventory_shrinkage_rate(recorded_inventory: float, actual_inventory: float):
inventory_shrinkage_rate = (
recorded_inventory - actual_inventory
) / recorded_inventory
return inventory_shrinkage_rate
# Function to calculate Markup Percentage
def markup_percentage(price: float, cost: float):
markup_percentage = decimal_to_percent((price - cost) / cost)
return markup_percentage
# Function to calculate Sharpe Ratio
def sharpe_ratio(
portfolio_return: float,
risk_free_rate: float,
standard_deviation_of_portfolio: float,
):
sharpe_ratio_val = (portfolio_return - risk_free_rate) / standard_deviation_of_portfolio
return sharpe_ratio_val
# Function to calculate Purchasing Power
def purchasing_power(initial_amount: float, annual_inflation_rate: float, time: float):
a = initial_amount * ((100 / (100 + annual_inflation_rate)) ** time)
return a
# Function to create Monthly EMI
def monthly_emi(loan_amt: float, interest_rate: float, number_of_installments: float):
emi = (
loan_amt
* interest_rate
* ((1 + interest_rate) ** number_of_installments)
/ ((1 + interest_rate) ** number_of_installments - 1)
)
return emi
# Function to calculate doubling time
def doubling_time(r: float):
t = math.log(2) / math.log(1 + percent_to_decimal(r))
return t
# Function to calculate Weighted Average
def weighted_average(ratio: list, rates: list):
wa = 0
for i in range(len(ratio)):
wa = wa + ratio[i] * rates[i]
# print("Weighted Average returns: ",wa)
return wa
# Function to calculate calculate Capital Asset Pricing Model
def Capital_Asset_Pricing_Model(
risk_free_interest_rate: float,
beta_of_security: float,
expected_market_return: float,
):
capital_asset_expected_return = risk_free_interest_rate + beta_of_security * (
expected_market_return - risk_free_interest_rate
)
return capital_asset_expected_return
# Function to calculate cost of equity:
def cost_of_equity(
risk_free_rate_of_return: float, Beta: float, market_rate_of_return: float
):
costOfEquity = risk_free_rate_of_return + Beta * (
market_rate_of_return - risk_free_rate_of_return
)
return costOfEquity
# Function to calculate cost of goods sold
def cost_of_goods_sold(
beginning_inventory: float, purchases: float, ending_inventory: float
):
cogs = beginning_inventory + purchases - ending_inventory
return cogs
# Function to calculate Rule of 72
def rule_of_72(rate_of_roi: float):
time_period = 72 / rate_of_roi
return time_period
# Function to calculate Acid test ratio
def acid_test_ratio(
cash: float,
marketable_securitie: float,
accounts_receivable: float,
current_liabilities: float,
):
ratio = (cash + marketable_securitie +
accounts_receivable) / current_liabilities
return round(ratio, 2)
# Function to calculate inflation adjusted return
def inflation_adjusted_return(
beginning_price: float,
ending_price: float,
dividends: float,
beginning_cpi_level: float,
ending_cpi__level: float,
):
stock_return = (ending_price - beginning_price +
dividends) / beginning_price
inflation = (ending_cpi__level - beginning_cpi_level) / beginning_cpi_level
inflation_adj = decimal_to_percent(
(1 + stock_return) / (1 + inflation) - 1)
return round(inflation_adj, 2)
# Function to calculate compound annual growth rate
def compound_annual_growth_rate(
beginning_value: float, ending_value: float, years: int
):
rate = decimal_to_percent(
pow((beginning_value / ending_value), 1 / years) - 1)
return round(rate, 1)
# Function to calculate current liability coverage ratio
def current_liability_coverage_ratio(
net_cash_from_operating_activities: float,
total_current_liabilities: float,
number_of_liabilities: int,
):
average_current_liabilities = total_current_liabilities / number_of_liabilities
current_liability_coverage_ratio = (
net_cash_from_operating_activities / average_current_liabilities
)
return current_liability_coverage_ratio
# Function to calculate Levered beta:
def levered_beta(unlevered_beta: float, tax_rate: float, debt: float, equity: float):
l_beta = unlevered_beta * (1 + (1 - tax_rate) * (debt // equity))
return l_beta
# Function to calculate monthly payment:
def monthly_payment(
principal: float,
interest_rate: float,
number_of_periods: float,
payments_per_period: float,
):
a = principal * (interest_rate // payments_per_period)
b = 1 - (1 + (interest_rate // payments_per_period)) ** (
-payments_per_period * number_of_periods
)
monthly_pay = a // b
return monthly_pay
# Function to calculate Duration With Convexity Adjustment
def duration(
rate: float,
coupon_rate: float,
frequency: float,
face_value: float,
settlement_date: float,
maturity_date: float,
):
try:
settlement_date = pd.to_datetime(settlement_date, format="%d/%m/%Y")
except:
settlement_date = pd.to_datetime(settlement_date, format="%d-%m-%Y")
try:
maturity_date = pd.to_datetime(maturity_date, format="%d/%m/%Y")
except:
maturity_date = pd.to_datetime(maturity_date, format="%d-%m-%Y")
data = pd.DataFrame()
rate = percent_to_decimal(rate)
coupon_rate = percent_to_decimal(coupon_rate)
n = pd.to_numeric(
((pd.to_datetime(maturity_date) - pd.to_datetime(settlement_date)) / 365).days
)
total_payment = n * frequency
coupon_payment = coupon_rate / frequency * face_value
payment = [coupon_payment] * \
(total_payment - 1) + [coupon_payment + face_value]
data["period"] = pd.DataFrame(np.arange(1, total_payment + 1))
data["payment"] = pd.DataFrame(payment)
data["dcoupon"] = data["payment"] / \
((1 + rate / frequency) ** data["period"])
data["pv"] = data["dcoupon"] / frequency * \
data["period"] / data["dcoupon"].sum()
duration = data["pv"].sum()
m_duration = duration / (1 + rate / frequency)
factor = 1 / (data["dcoupon"].sum() * (1 + rate / frequency) ** 2)
data["cf"] = (
data["dcoupon"]
* (data["period"] ** 2 + data["period"])
/ (1 + rate / frequency) ** data["period"]
)
convexity = factor * data["cf"].sum()
result = round(duration, 3)
return result
# Function to calculate current ratio
def current_ratio(total_current_assets: float, total_liabilities: float):
ratio = total_current_assets / total_liabilities
return round(ratio, 3)
# Function to calculate inventory turnover ratio
def inventory_turnover_ratio(
cost_of_goods_sold: float, beginning_inventory: float, ending_inventory: float
):
avg_inventory = (beginning_inventory + ending_inventory) / 2
ratio = cost_of_goods_sold / avg_inventory
return round(ratio, 2)
# Function to calculate Inflation Rate
def inflation_rate(bigger_year: int, smaller_year: int, base_year: int):
inflation_rate = decimal_to_percent(
(bigger_year - smaller_year) / base_year)
return inflation_rate
# Function to calculate Herfindal index
def herfindal_Index(Firms_market_shares: str):
market_share_list = []
i = 0
breaker = 0
while i < len(Firms_market_shares):
share = ""
if Firms_market_shares[i] == " ":
for j in range(breaker, i):
share = share + Firms_market_shares[j]
market_share_list.append(int(share))
breaker = i + 1
i = i + 1
market_share_list.append(
int(
Firms_market_shares[len(Firms_market_shares) -
2: len(Firms_market_shares)]
)
)
herfindal_Index = 0
for i in market_share_list:
herfindal_Index = herfindal_Index + i**2
herfindal_Index = herfindal_Index
return herfindal_Index
# function to calculate discount opex
def discount_opex(annual_opex: float, wacc: float, project_lifetime: float):
a = annual_opex // wacc
b = 1 - 1 // ((1 + wacc) ** project_lifetime)
dis_opex = a * b
return dis_opex
# function to calculate project efficiency
def project_efficiency(annual_production: float, collector_surface: float, dni: float):
project_eff = annual_production // (collector_surface * dni)
return project_eff
# Function to calculate Real GDP
def real_gdp(nominal_gdp: float, gdp_deflator: float):
real_gdp = decimal_to_percent(nominal_gdp / gdp_deflator)
return real_gdp
# Function to calculate excess reserves
def excess_reserves(deposits: float, reserve_requirement: float):
excess_reserves = deposits - deposits * reserve_requirement
return excess_reserves
# function to calculate discounted cash flow
def discounted_cash_flow(
real_feed_in_tariff: float,
annual_production: float,
wacc: float,
project_lifetime: float,
):
a = (real_feed_in_tariff * annual_production) // wacc
b = 1 - (1 // (1 + wacc) ** project_lifetime)
d_cash_flow = a * b
return d_cash_flow
# Function to calculate GDP growth rate
def gdp_growth_rate(current_year_gdp: float, last_year_gdp: float):
gdp_growth_rate = decimal_to_percent(
(current_year_gdp - last_year_gdp) / last_year_gdp
)
return gdp_growth_rate
# function to calculate credit card equation
def credit_card_equation(
balance: float, monthly_payment: float, daily_interest_rate: float
):
a = np.log(1 + (balance // monthly_payment) *
(1 - (daily_interest_rate) ** 30))
b = np.log(1 + daily_interest_rate)
N = -(1 // 30) * (a // b)
return N
# function to calculate the payoff of multiple credit cards using Debt Avalanche method
def credit_card_payoff(
debts: list, interest_rates: list, minimum_payments: list, monthly_payment: int
):
cards = []
for i in range(len(debts)):
cards.append(
{
"index": i,
"debt": int(debts[i]),
"minimum_payment": int(minimum_payments[i]),
"interest_rate": int(interest_rates[i]),
"interest_paid": 0,
"month": 0,
"total_payment": 0,
}
)
# Sort the list of dictionaries by interest rate, in descending order
cards.sort(key=lambda x: x["interest_rate"], reverse=True)
extra = 0
while sum(d["debt"] for d in cards) > 0:
highest_interest_index = cards.index(
max((d for d in cards if d["debt"] > 0),
key=lambda x: x["interest_rate"])
) # highest index of the interest rate
total_minimum_payment = sum(
c["minimum_payment"] for c in cards if c["debt"] > 0
)
extra_payment = monthly_payment - total_minimum_payment + extra
extra = 0
for i in range(len(cards)):
if cards[i]["debt"] > 0:
interest = round(
percent_to_decimal(
cards[i]["debt"] * cards[i]["interest_rate"])
/ 12,
2,
)
payment = cards[i]["minimum_payment"]
cards[i]["interest_paid"] += interest
cards[i]["month"] += 1
if i == highest_interest_index:
payment += extra_payment
if payment > cards[i]["debt"]:
extra = payment - cards[i]["debt"]
cards[i]["total_payment"] += cards[i]["debt"]
cards[i]["debt"] = 0
else:
cards[i]["debt"] -= payment
cards[i]["total_payment"] += payment
if cards[i]["debt"] == 0:
cards[i]["total_payment"] += cards[i]["interest_paid"]
cards.sort(key=lambda x: x["index"])
return cards
# function to calculate future value of the ordinary annuity
def future_value_of_ordinary_due(
periodic_payment: float, number_of_periods: int, effective_interest_rate: float
):
future_value_of_ordinary_due = (
periodic_payment
* (((1 + effective_interest_rate) ** (number_of_periods)) - 1)
/ effective_interest_rate
)
return future_value_of_ordinary_due
# Function to calculate future value of annuity due
def future_value_of_annuity_due(
periodic_payment: float, number_of_periods: int, effective_interest_rate: float
):
future_value_of_annuity_due = (
periodic_payment
* (((1 + effective_interest_rate) ** (number_of_periods)) - 1)
* (1 + effective_interest_rate)
/ effective_interest_rate
)
return future_value_of_annuity_due
# Function to calculate present value of annuity due
def present_value_of_annuity_due(
periodic_payment: float, number_of_periods: int, rate_per_period: float
):
present_value_of_annuity_due = periodic_payment + periodic_payment * (
(1 - (1 + rate_per_period) ** (-number_of_periods + 1)) / rate_per_period
)
return present_value_of_annuity_due
# Function to calculate loan to value
def loan_to_value(mortage_value: float, appraised_value: float):
ratio = mortage_value / appraised_value
return decimal_to_percent(ratio)
# Function to calculate Retention Rate
def retention_ratio(net_income: float, dividends: float):
retention_ratio = (net_income - dividends) / net_income
return retention_ratio
# Function to calculate Tax Equivalent Yield
def tax_equivalent_yield(tax_free_yield: float, tax_rate: float):
tax_equivalent_yield = tax_free_yield / (1 - tax_rate)
return tax_equivalent_yield
# Function to calculate year over year growth
def year_over_year(later_period_value: float, earlier_period_value: float):
growth = (later_period_value - earlier_period_value) / earlier_period_value
return decimal_to_percent(growth)
# function to calculate future value of the annuity
def future_value_of_annuity(
payments_per_period: float, interest_rate: float, number_of_periods: float
):
a = (((interest_rate + 1) ** number_of_periods) - 1) // interest_rate
fva = payments_per_period * a
return fva
# Function to calculate Balloon Balance of a Loan
def balloon_balance_of_loan(
present_value: float,
payment: float,
rate_per_payment: float,
number_of_payments: float,
):
balloon_balance_of_loan = present_value * (
(1 + rate_per_payment) ** number_of_payments
) - payment * (
(((1 + rate_per_payment) ** number_of_payments) - 1) / rate_per_payment
)
return balloon_balance_of_loan
# Function to calculate discounted payback period
def discounted_payback_period(outflow: float, rate: float, periodic_cash_flow: float):
discounted_payback_period = np.log(
1 / (1 - (outflow * rate / periodic_cash_flow)),10
) / np.log(1 + rate,10)
return discounted_payback_period
# Function to calculate periodic lease payment
def periodic_lease_payment(
Asset_value: float,
monthly_lease_interest_rate: float,
number_of_lease_payments: float,
):
periodic_lease_payment = (Asset_value * monthly_lease_interest_rate) / (
1 - (1 / (1 + monthly_lease_interest_rate) ** number_of_lease_payments)
)
return periodic_lease_payment
# Function to calculate weighted average
def weighted_average_of_values(Assigned_weight_values: str, data_point_values: str):
weights = list(map(int, Assigned_weight_values.split()))
data_values = list(map(int, data_point_values.split()))
total_data_point_weighted_value = 0
sum_assigned_weight_values = 0
for i in weights:
sum_assigned_weight_values = sum_assigned_weight_values + i
for i in range(len(weights)):
total_data_point_weighted_value = total_data_point_weighted_value + (
weights[i] * data_values[i]
)
weighted_average = total_data_point_weighted_value / sum_assigned_weight_values
return weighted_average
# Function to calculate Yield to maturity
def yield_to_maturity(
bond_price: float, face_value: float, coupon_rate: float, years_to_maturity: float
):
yield_cal = (
coupon_rate * percent_to_decimal(face_value)
+ (face_value - bond_price) / years_to_maturity
) / ((face_value + bond_price) / 2)
return round(decimal_to_percent(yield_cal), 2)
# Function to calculate perpetuity payment
def perpetuity_payment(present_value: float, rate: float):
payment = present_value * percent_to_decimal(rate)
return payment
# Function to calculate Zero Coupon Bond value
def zero_coupon_bond_value(
face_value: float, rate_of_yield: float, time_of_maturity: float
):
zcbv = face_value / \
pow((1 + percent_to_decimal(rate_of_yield)), time_of_maturity)
return round(zcbv, 2)
# function to calculate Zero Coupon Bond Effective Yield
def zero_coupon_bond_yield(
face_value: float, present_value: float, time_of_maturity: float
):
zcby = pow((face_value / present_value), (1 / time_of_maturity)) - 1
return round(decimal_to_percent(zcby), 1)
# Function to calculate Profitability Index
def profitability_index(initial_investment: float, pv_of_future_cash_flows: float):
profitability_index = pv_of_future_cash_flows / initial_investment
return profitability_index
# Function to calculate Profitability index using annual cash flows
def profitability_index2(
initial_inverstment: float, annual_cash_flows: str, discount_rate: float
):
annual_cash_flow_list = list(map(int, annual_cash_flows.split()))
pv_cash_flow_list = []
for i in range(len(annual_cash_flow_list)):
pv_cash_flow_list.append(
(annual_cash_flow_list[i])
/ ((1 + percent_to_decimal(discount_rate)) ** (i + 1))
)
total_pv_cash_flow = sum(pv_cash_flow_list)
profitability_index = total_pv_cash_flow / initial_inverstment
return profitability_index
# Function to calculate Receivables Turnover Ratio
def receivables_turnover_ratio(sales_revenue: float, avg_accounts_receivable: float):
receivables_turnover_ratio = sales_revenue / avg_accounts_receivable
return receivables_turnover_ratio
# Function to calculate Remaiing balance
def remaining_balance(
regular_payment: float,
interest_rate_per_period: float,
number_of_payments: float,
number_of_payments_done: float,
):
B = regular_payment * (
(
1
- (
(1 + interest_rate_per_period)
** (-(number_of_payments - number_of_payments_done))
)
)
// interest_rate_per_period
)
return B
# Function to calculate Net present value
def net_present_value(cash_flows: str, discount_rate: float, initial_investment: float):
cash_flow_list = list(map(int, cash_flows.split()))
net_present_value = -1 * (initial_investment)
for i in range(len(cash_flow_list)):
net_present_value = net_present_value + (
cash_flow_list[i] /
((1 + percent_to_decimal(discount_rate)) ** (i + 1))
)
return net_present_value
def leverage_income(debt_payments: int, income: int):
return float(debt_payments) / float(income)
def leverage_equity(debt: int, equity: int):
return float(debt) / float(equity)
# Function to calculate time period required for given growth
def time_period_required_for_growth(interest_rate: float, growth_factor: int):
time_period_required_for_growth = math.log(growth_factor) / math.log(
1 + percent_to_decimal(interest_rate)
)
return time_period_required_for_growth
# Function to calculate preferred stock value
def preferred_stock_value(dividend: float, discount_rate: float):
preferred_stock_value = dividend / discount_rate
return preferred_stock_value
# Function to calculate present value of annuity due
def present_value_of_annuity_due(
periodic_payment: float, number_of_periods: int, rate_per_period: float
):
present_value_of_annuity_due = (
periodic_payment
* ((1 - (1 / (1 + rate_per_period) ** (number_of_periods))) / rate_per_period)
* (1 + rate_per_period)
)
return present_value_of_annuity_due
# Function to Calculate Asset Turnover Ratio
def asset_turnover_ratio(
net_sales: float, total_asset_beginning: float, total_asset_ending: float
):
avg_total_asset = (total_asset_beginning + total_asset_ending) / 2
asset_turnover_ratio = net_sales / avg_total_asset
return asset_turnover_ratio
# Function to calculate Bid Ask Spread
def bid_ask_spread(ask_price: float, bid_price: float):
bid_ask_spread = ask_price - bid_price
return bid_ask_spread
# Function To calculate No of Periods(Time in years) with respect to Present value(PV) and Future value(FV)
def CalculatePeriods(present_val: float, future_val: float, rate: float):
n = math.log(future_val / present_val) / \
math.log(1 + percent_to_decimal(rate))
return n
# Function to calculate payments on a loan that has balance remaining after all periodic payments
# are made
def balloon_loan_payment(
principal: float,
interest_rate: float,
term_years: float,
balloon_payment_year: float,
):
monthly_interest_rate = percent_to_decimal(interest_rate) / 12
months_paid = balloon_payment_year * 12
rs = (1 + monthly_interest_rate) ** months_paid
term_months = term_years * 12
monthly_payment = (principal * monthly_interest_rate) / (
1 - 1 / (1 + monthly_interest_rate) ** term_months
)
balloon_payment = principal * rs - monthly_payment * (
(rs - 1) / monthly_interest_rate
)
return balloon_payment
# Function to calculate Monthly lease payment
def monthly_lease_payment(
Asset_value: float,
monthly_lease_interest_rate: float,
number_of_lease_payments: float,
):
periodic_payment = periodic_lease_payment(
Asset_value, monthly_lease_interest_rate, number_of_lease_payments
)
monthly_payment = periodic_payment / number_of_lease_payments
return monthly_payment
# Function to calculate 401k
def calculate_401k(
income: float,
contribution_percentage: float,
current_age: int,
age_at_retirement: int,
rate_of_return: float,
salary_increase_rate: float,
):
contribution_amount = income * percent_to_decimal(contribution_percentage)
number_of_years = age_at_retirement - current_age
amount = 0
for _ in range(number_of_years):
amount = (amount + contribution_amount) * (
1 + percent_to_decimal(rate_of_return)
)
contribution_amount = (contribution_amount) * (
1 + percent_to_decimal(salary_increase_rate)
)
return round(amount, 3)
# Function to calculate Mortgage Amortization
def calculate_mortgage_interest(
mortgage_amount: float,
mortgage_deposit: float,
annual_interest_rate: float,
loan_term: int,
):
annual_interest_rate = percent_to_decimal(annual_interest_rate)
loan_amount = mortgage_amount * percent_to_decimal(100 - mortgage_deposit)
power = (1 + annual_interest_rate) ** loan_term
mortgage_annual_payment = loan_amount * \
(annual_interest_rate * power) / (power - 1)
return round(mortgage_annual_payment, 3)
# Function to calculate the FHA mortgage
def calculate_fha_mortgage_interest(
mortgage_amount: float,
mortgage_deposit_percentage: float,
annual_interest_rate: float,
fha_annual_interest_rate: float,
loan_term: int,
):
mortgage_amount = mortgage_amount - (
mortgage_amount * percent_to_decimal(mortgage_deposit_percentage) * 0.1
)
# Calculate upfront MIP and monthly <MIP> interest rates
upfront_mip_percentage = 1.75
upfront_mip = mortgage_amount * percent_to_decimal(upfront_mip_percentage)
monthly_mip_percentage = percent_to_decimal(fha_annual_interest_rate) / 12
monthly_mip = mortgage_amount * monthly_mip_percentage
# Calculate monthly mortage payment
loan_term_months = loan_term * 12
monthly_interest_rate = percent_to_decimal(annual_interest_rate) / 12
power = (1 + monthly_interest_rate) ** loan_term_months
monthly_payment = mortgage_amount * \
(monthly_interest_rate * power) / (power - 1)
# Calculate total FHA loan amount and total monthly payment
total_fha_loan_amount = mortgage_amount + upfront_mip
total_monthly_payment = monthly_payment + monthly_mip
total_loan_cost = total_monthly_payment * loan_term_months + upfront_mip
return (
upfront_mip,
monthly_payment,
monthly_mip,
total_fha_loan_amount,
total_monthly_payment,
total_loan_cost,
)
def roth_ira(
principal: float,
interest_rate: float,
years: int,
tax_rate: float,
annual_contribution: float,
):
roth_ira_balance = principal
taxable_balance = principal
for _ in range(years):
roth_ira_balance = (roth_ira_balance + annual_contribution) * (
1 + percent_to_decimal(interest_rate)