From 1c2fac6390f6bd7404df85be4be40e9630f721b8 Mon Sep 17 00:00:00 2001 From: Mridul Date: Tue, 6 Jun 2023 11:03:27 +0530 Subject: [PATCH 01/66] Completed the issues #229 and #230 --- .../unicode_data/13.0.0/charmap.json.gz | Bin 0 -> 20988 bytes ENDPOINTS.md | 28 ++++- helpers/functions.py | 103 ++++++++++++++++++ main.py | 49 +++++++++ 4 files changed, 179 insertions(+), 1 deletion(-) create mode 100644 .hypothesis/unicode_data/13.0.0/charmap.json.gz diff --git a/.hypothesis/unicode_data/13.0.0/charmap.json.gz b/.hypothesis/unicode_data/13.0.0/charmap.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..30309b5be700c1ea9dda4f6456cf1c1f32beb6fc GIT binary patch literal 20988 zcmbUIV{|25`0fkGcGBtCM#r|@vDvZFvD2|_t=P7$PC7PMY?~`5&))y{J$sDv<&5*? zs;g#I%{l9yg;Do!7I73D95@&l7{sTGog>R{cNTMF4{I<5{l8N~T~0pV1}%t(nzJkn z3CRN-Ks!m8kRn}Bj<=v+%LCKjl?4j(*)b#@RrEh5n0i4M0RN9H!;jmEr!2#m$I{Ma zulGYuyBwj9@*=~}N2ceF;WofXAG*ysuj%b`vxSVeXr#JOudeh30Ka3& z82{6>cy8P>Q1bCrXz^C4X@03f@#lJ5p!4UJyU?#Q#napkH{jjr)CZya52u@m%E9(q zqtAtEp7-7(zUJxaQC}?gAm=zge?48<&dbA&CmWh{_&a*_V{$ci76shuRTf zHHsC3fPl33iKiWZtpfa!T+WsFgQo*Q?g7`;UB|jidG6oMg0!u*?t|uH_TI#jV(^IW z?WxDh8|Ao~mSpqPp_^HYP2ieJ=0hhBg=!K)=r zshV0jop_JX5dR{+70p^;wIGF^H1F^G#LymHS2LTt@#_+oZdzaHS0p*`2#b}r)Xo$a zlAE4$4U0Bi8N|87+csV$a~Z6VkZxFScOOC~II=7b}?9=%% zFRJAJrYv53CMUS1|9RSQdZlY zF!R~h(-qcaXS8#&sU(kXXXCm9}E$|=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ej}g=yan~Wc;4%53Fhg^d zC#0G;AtM_MliI3Q5hNixkU!LwKh#mip{tGq;R#*bo8w#H&)BYE!y-1yFgq+obCkJ- z>@4wapnkPc`U6g*Aq2y)lM9 z4=#PxJW0H2skJ6iek4_YBvF9mZkHtRd5ZNEgm|f(h{T(fs=<|D!Aa$#-1cBb*361I zUqyFsyD&fNcUS@T(s#HMTX$lE*>r10-mnI@V-%RX#ZHpQSIXn>pvx$C{Co^yq-S!> z-Ayz36!uaxIgIF~_=#)ziQNea*L;2lYucUVr7taLOp3eg8oNix_X7^_BhEC|LoMUe z%dKklg#*z1-sS7s#}LtHwdj? zZ-j$3*CS^v=1!Leaj|~+x1RyPG^*`->a2gh9e_oaFB&h3s(+nc6gwBiZkcMM1H32) zRE>-==Kn3%hhB$^>al@AnvW$)w%Q@U&;f6{4XY8r7O|iGxxO>qkf!3VkPYKF=egm6 zZaBHYHr$NE+6X26xpbx0T%iL6+0=y)pYu6*!4k@FY!+ z@PO;&l0C2J%VCVT+6RD7LD|0_aJycQcT87_l(E}`yDxoW*gVM#+A)lyf5Hm3H}0=4 zDd*ew0PstYco*{!|7?F@)!GYvk`GY2R7i6@gKx^s-gduZNK|)Q zU$aVvx_Ws{3&hjLafy)pG(m*l_|z1Vb~qLPqb3a}EM#nzB=P@BO&ob%36rDJB%kM| zqkDKhgYPslt30efY5b?BS*<)G&O0X1s2l`NN{{gF2*P~2fig$MR*uQ2Yme9S+_`7+ zS)5lS^9cBS?5yj85Z=~_7+l=Yx*!Y7z~0srcxUVEVW-%km#{n{vVUP7}@RP008@@#a;ja literal 0 HcmV?d00001 diff --git a/ENDPOINTS.md b/ENDPOINTS.md index 9814ddf5..485394a9 100644 --- a/ENDPOINTS.md +++ b/ENDPOINTS.md @@ -1749,4 +1749,30 @@ Add-function-and-endpoint-to-calculate-lump-sum-mutual-fund-investment "Basis":3, "Accrued Interest":32.363013698630134 } -``` \ No newline at end of file +``` + +# GET # Endpoint --> '/mortrage' +Required Paramenters --> princial:int,interest_rate:float,years:int,down_payment:int,property_tax_rate:float,insurance_rate:float +Sample request --> http://127.0.0.1:8000/mortrages?princial=200000&interest_rate=4.5&years=45&down_payment=50000&property_tax_rate=1.3&insurance_rate=0.5 + +Sample Output + +{ + "Monthly Payment": 648.4110284532501, + "Total Payment": 350141.95536475506, + "Total Property Tax": 117000.00000000001, + "Total insurance cost": 45000, + "Total Cost": 512141.95536475506, + "Loan to value ratio": 75 +} + + +## GET ## Endpoint --> '/social_securities' +Required Parameters --> birth_date:str,earnings:int,retirement_age:int + +Sample request --> http://127.0.0.1:8000/social_securities?birth_date=10-08-2002&earnings=250000&retirement_age=70 +Sample Output + +[ + "The monthly benefits are 20833.333333333332 and future benefits are 55349.83286723857" +] \ No newline at end of file diff --git a/helpers/functions.py b/helpers/functions.py index b46b896c..759c8147 100644 --- a/helpers/functions.py +++ b/helpers/functions.py @@ -1459,3 +1459,106 @@ def accrint(issue_date:str, settlement_date:str, rate:float, par:float, frequenc accrint = par * rate * periods / frequency return accrint + + +def calculate_mortgage(principal, interest_rate, years, down_payment=0, property_tax_rate=0, insurance_rate=0): + """ + Calculate the monthly mortgage payment and provide additional information about the mortgage. + + Args: + principal (float): The principal amount (loan amount). + interest_rate (float): The annual interest rate (in percentage). + years (int): The number of years for the mortgage. + down_payment (float, optional): The down payment amount (default: 0). + property_tax_rate (float, optional): The annual property tax rate (in percentage) (default: 0). + insurance_rate (float, optional): The annual insurance rate (in percentage) (default: 0). + + Returns: + dict: A dictionary containing the monthly mortgage payment and additional mortgage information. + """ + monthly_interest_rate = interest_rate / 100 / 12 # Monthly interest rate + num_payments = years * 12 # Total number of payments + + # Calculate the loan amount after down payment + loan_amount = principal - down_payment + + # Calculate the monthly mortgage payment + monthly_payment = ( + loan_amount + * monthly_interest_rate + * (1 + monthly_interest_rate) ** num_payments + / ((1 + monthly_interest_rate) ** num_payments - 1) + ) + + # Calculate the total payment over the mortgage term + total_payment = monthly_payment * num_payments + + # Calculate the total property tax over the mortgage term + total_property_tax = property_tax_rate / 100 * principal * years + + # Calculate the total insurance cost over the mortgage term + total_insurance_cost = insurance_rate / 100 * principal * years + + # Calculate the total cost of the mortgage (principal + interest + property tax + insurance) + total_cost = total_payment + total_property_tax + total_insurance_cost + + # Calculate the loan-to-value (LTV) ratio + ltv_ratio = (loan_amount / principal) * 100 + + # Create a dictionary with the mortgage information + mortgage_info = { + "monthly_payment": monthly_payment, + "total_payment": total_payment, + "total_property_tax": total_property_tax, + "total_insurance_cost": total_insurance_cost, + "total_cost": total_cost, + "loan_to_value_ratio": ltv_ratio, + } + + return mortgage_info + + + +import pandas as pd + +def calculate_social_security(birth_date, earnings, retirement_age): + """ + Calculate the estimated monthly Social Security benefits based on the birth date, earnings, and retirement age. + + Args: + birth_date (str): The birth date in the format 'YYYY-MM-DD'. + earnings (float): The average indexed monthly earnings. + retirement_age (int): The desired retirement age. + + Returns: + float: The estimated monthly Social Security benefits. + """ + birth_date = pd.to_datetime(birth_date) + current_date = pd.to_datetime('today') + age = pd.Timedelta(current_date - birth_date).days / 365.25 + + # Determine the full retirement age based on the year of birth + if birth_date.year < 1938: + full_retirement_age = 65 + elif birth_date.year < 1943: + full_retirement_age = 65 + (birth_date.year - 1937) * 2 + else: + full_retirement_age = 66 + + # Calculate the reduction factor for claiming benefits before full retirement age + if retirement_age < full_retirement_age: + reduction_factor = 1 - ((full_retirement_age - retirement_age) * 5 / 900) + else: + reduction_factor = 1.0 # No reduction if retirement age is at or after full retirement age + + # Calculate the primary insurance amount (PIA) + pia = earnings * reduction_factor + + # Calculate the estimated monthly Social Security benefits + monthly_benefits = pia / 12 + + # Predict future benefits + years_to_retirement = retirement_age - age + future_benefits = monthly_benefits * (1 + 0.02) ** years_to_retirement + + return monthly_benefits, future_benefits diff --git a/main.py b/main.py index 3b0f5f65..a3427891 100644 --- a/main.py +++ b/main.py @@ -2590,6 +2590,9 @@ def personal_savings(init:int, "Monthly Contribution":monthly, "Total Amount Saved": f"{total_amount}", } + + except: + pass @app.get( "/accrint", @@ -2611,3 +2614,49 @@ def accrued_interest(issue_date:str, settlement_date:str, rate:float, par:float, } except: return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + + +@app.get('/mortrages',tags=["mortrage"],description="Endpoint to calculate Mortrages") +def mortrage(princial:int,interest_rate:float,years:int,down_payment:int,property_tax_rate:float,insurance_rate:float): + + try: + mortrage = functions.calculate_mortgage( + principal=princial, + interest_rate=interest_rate, + years=years, + down_payment=down_payment, + property_tax_rate=property_tax_rate, + insurance_rate=insurance_rate + ) + return { + "Monthly Payment": mortrage['monthly_payment'], + "Total Payment": mortrage['total_payment'], + "Total Property Tax": mortrage['total_property_tax'], + "Total insurance cost": mortrage['total_insurance_cost'], + "Total Cost": mortrage['total_cost'], + "Loan to value ratio": mortrage["loan_to_value_ratio"] + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + + + +@app.get( + '/social_securities', + tags=['Social Security'], + description="Endpoint to calculate Social securities" +) +def ss(birth_date:str,earnings:int,retirement_age:int): + + try: + monthly_benefits, future_benefits = functions.calculate_social_security( + birth_date=birth_date, + earnings=earnings, + retirement_age=retirement_age + ) + return { + f"The monthly benefits are {monthly_benefits} and future benefits are {future_benefits}" + } + + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file From 9c65a6e86143ad8614be5b049b4776719d02e571 Mon Sep 17 00:00:00 2001 From: Mridul Date: Tue, 6 Jun 2023 11:13:59 +0530 Subject: [PATCH 02/66] #229 and 230 --- ENDPOINTS.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/ENDPOINTS.md b/ENDPOINTS.md index 485394a9..b4482bf9 100644 --- a/ENDPOINTS.md +++ b/ENDPOINTS.md @@ -1751,6 +1751,7 @@ Add-function-and-endpoint-to-calculate-lump-sum-mutual-fund-investment } ``` +``` # GET # Endpoint --> '/mortrage' Required Paramenters --> princial:int,interest_rate:float,years:int,down_payment:int,property_tax_rate:float,insurance_rate:float Sample request --> http://127.0.0.1:8000/mortrages?princial=200000&interest_rate=4.5&years=45&down_payment=50000&property_tax_rate=1.3&insurance_rate=0.5 @@ -1775,4 +1776,5 @@ Sample Output [ "The monthly benefits are 20833.333333333332 and future benefits are 55349.83286723857" -] \ No newline at end of file +] +``` \ No newline at end of file From 55361f54887540ac55c1fd46b8b8d3a85fbf7253 Mon Sep 17 00:00:00 2001 From: filza2112 Date: Sat, 10 Jun 2023 02:40:08 +0530 Subject: [PATCH 03/66] Added the try and except block --- main.py | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/main.py b/main.py index f6857cec..aafd6884 100644 --- a/main.py +++ b/main.py @@ -2765,25 +2765,25 @@ def calculate_gratuity(last_salary: float, tenure_years: int, tenure_months: int except: return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) - -# Endpoint to calculate Personal Savings - - @app.get( "/personal_savings", tags=["personal_savings"], description="Calculate Simple Personal Savings", ) -def personal_savings(init: int, monthly: int, tenure: float): - total_amount = functions.personal_savings(init, monthly, tenure) - return { - "Tag": "Simple Personal Savings", - "Initial Deposit": init, - "total number of years": tenure, - "Monthly Contribution": monthly, - "Total Amount Saved": f"{total_amount}", - } - +def personal_savings(init:int, + monthly:int, + tenure:float): + try: + personal_savings = functions.personal_savings(init,monthly,tenure) + return { + "Tag": "Simple Personal Savings", + "Initial Deposit":init, + "total number of years":tenure, + "Monthly Contribution":monthly, + "Total Amount Saved": f"{total_amount}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) @app.get( "/accrint", From 10309f98ada1f33031cb87f37ca1591bad1eb4d3 Mon Sep 17 00:00:00 2001 From: Robera Negussie <47657043+roberanegussie@users.noreply.github.com> Date: Mon, 12 Jun 2023 20:37:06 +0300 Subject: [PATCH 04/66] Free Cash Flow to Equity This is an End Point for calculating the Free Cash Flow to Equity --- ENDPOINTS.md | 27 ++++++++++++++++++++++ helpers/functions.py | 24 ++++++++++++++++++++ main.py | 54 +++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 104 insertions(+), 1 deletion(-) diff --git a/ENDPOINTS.md b/ENDPOINTS.md index cbccb721..c0641f16 100644 --- a/ENDPOINTS.md +++ b/ENDPOINTS.md @@ -1857,3 +1857,30 @@ Add-function-and-endpoint-to-calculate-lump-sum-mutual-fund-investment beta: float = 1.2 } ``` + +**GET** `/free_cash_flow_to_equity` + +- Required parameters +- Sample output +```py + { + "Tag":"Free Cash Flow to Equity", + "Total Revenues": 750000.0, + "Total Expenses": 350000.0, + "Inital Cost of Asset": 900000.0, + "Life Time of Asset": 10.0, + "Change in Price, Property or Equity": 45000.0, + "Current Depreciation": 25000.0, + "Current Assets": 250000.0, + "Current Liabilities": 100000.0, + "Amount a Company Borrows": 450000.0, + "Debt it Repays": 100000.0, + "Net Income": 400000.0, + "Depreciation and Amortization": 90000.0, + "Capital Expenditures": 70000.0, + "Change in Working Capital": 150000.0, + "Net Borrowing": 350000.0, + "Free Cash Flow to Equity": 620000.0 + } + +``` diff --git a/helpers/functions.py b/helpers/functions.py index 11cdb95f..b4e1c500 100644 --- a/helpers/functions.py +++ b/helpers/functions.py @@ -1698,3 +1698,27 @@ def calculate_treynor_ratio(returns, risk_free_rate, beta): treynor_ratio = calculate_treynor_ratio(returns, risk_free_rate, beta) print(f"Treynor Ratio: {treynor_ratio}") + + +#Function to Calculate Free Cash Flow to Equity + +def free_cash_flow_to_equity( + total_revenues:float, + total_expenses:float, + initial_cost_of_asset: float, + lifetime_of_asset: float, + change_in_PPE:float, + current_depreciation:float, + current_assets:float, + current_liabilities:float, + amount_a_company_borrows:float, + debt_it_repays:float): + + net_income = total_revenues - total_expenses, + depreciation_and_amortization = initial_cost_of_asset / lifetime_of_asset, + capEx = change_in_PPE + current_depreciation, + change_in_working_capital = current_assets - current_liabilities, + net_borrowing = amount_a_company_borrows - debt_it_repays, + + fcfe = net_income + depreciation_and_amortization - capEx - change_in_working_capital + net_borrowing + return fcfe diff --git a/main.py b/main.py index f6857cec..78ea5e00 100644 --- a/main.py +++ b/main.py @@ -2973,4 +2973,56 @@ def loan_to_value_ratio (loan_amount:float, value_of_collateral:float): "Loan to Value Ratio": f"{ratio}%", } except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + +#Endpoint for function Free Cash Flow To Equity + +@app.get( + "/free_cash_flow_to_equity", + tags=["free_cash_flow_to_equity"], + description="Calculate Free Cash Flow to Equity", +) +def free_cash_flow_to_equity( + total_revenues:float, + total_expenses:float, + initial_cost_of_asset: float, + lifetime_of_asset: float, + change_in_PPE:float, + current_depreciation:float, + current_assets:float, + current_liabilities:float, + amount_a_company_borrows:float, + debt_it_repays:float): + try : + fcfe = functions.free_cash_flow_to_equity( + total_revenues, total_expenses, initial_cost_of_asset, lifetime_of_asset, + change_in_PPE, current_depreciation, current_assets, current_liabilities, + amount_a_company_borrows, debt_it_repays + ) + net_income = total_revenues - total_expenses, + depreciation_and_amortization = initial_cost_of_asset / lifetime_of_asset, + capEx = change_in_PPE + current_depreciation, + change_in_working_capital = current_assets - current_liabilities, + net_borrowing = amount_a_company_borrows - debt_it_repays, + + return { + "Tag": "Free Cash Flow to Equity", + "Total Revenues": total_revenues, + "Total Expenses": total_expenses, + "Inital Cost of Asset": initial_cost_of_asset, + "Life Time of Asset": lifetime_of_asset, + "Change in Price, Property or Equity": change_in_PPE, + "Current Depreciation": current_depreciation, + "Current Assets": current_assets, + "Current Liabilities": current_liabilities, + "Amount a Company Borrows": amount_a_company_borrows, + "Debt it Repays": debt_it_repays, + "Net Income": net_income, + "Depreciation and Amortization": depreciation_and_amortization, + "Capital Expenditures": capEx, + "Change in Working Capital": change_in_working_capital, + "Net Borrowing": net_borrowing, + "Free Cash Flow to Equity": fcfe + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) From 9102e03b7c72a18f8a1d88119a6e327930844c01 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Tue, 13 Jun 2023 00:08:28 +0530 Subject: [PATCH 05/66] Added Market Orders function --- ENDPOINTS.md | 34 ++++++++++++++++++++++++++++++++++ helpers/functions.py | 21 +++++++++++++++++++++ test_main.py | 13 +++++++++++++ 3 files changed, 68 insertions(+) diff --git a/ENDPOINTS.md b/ENDPOINTS.md index cbccb721..0b16e822 100644 --- a/ENDPOINTS.md +++ b/ENDPOINTS.md @@ -1857,3 +1857,37 @@ Add-function-and-endpoint-to-calculate-lump-sum-mutual-fund-investment beta: float = 1.2 } ``` +#Endpoints for market order function + +from fastapi import FastAPI + +app = FastAPI() + +@app.get( + "/execute_market_order_function", + tags=["execute_market_order"], + description="Execute a market order", +) +def execute_market_order_function( + order_type: str, + symbol: str, + quantity: int, +): + try: + # Your implementation to execute the market order + # Replace with your logic to execute the order on the trading platform + # Example code to return the order details + return { + "Tag": "Market Order", + "Order Type": order_type, + "Symbol": symbol, + "Quantity": quantity, + "Message": f"{order_type.capitalize()} order for {quantity} shares of {symbol} executed successfully at market price.", + } + except Exception as e: + return {"error": str(e)} + +# Run the application +if __name__ == "__main__": + import uvicorn + uvicorn.run(app, host="0.0.0.0", port=8000) diff --git a/helpers/functions.py b/helpers/functions.py index 11cdb95f..79a8127b 100644 --- a/helpers/functions.py +++ b/helpers/functions.py @@ -1698,3 +1698,24 @@ def calculate_treynor_ratio(returns, risk_free_rate, beta): treynor_ratio = calculate_treynor_ratio(returns, risk_free_rate, beta) print(f"Treynor Ratio: {treynor_ratio}") + +#To calculate market orders function + +import datetime + +def execute_market_order(order_type, symbol, quantity): + # Simulating order execution + current_price = get_current_price(symbol) # Function to get the current price for the symbol + timestamp = datetime.datetime.now() + + if order_type == "buy": + execute_buy_order(symbol, current_price, quantity) # Function to execute a buy order + print(f"Buy order for {quantity} shares of {symbol} executed at market price {current_price} at {timestamp}") + elif order_type == "sell": + execute_sell_order(symbol, current_price, quantity) # Function to execute a sell order + print(f"Sell order for {quantity} shares of {symbol} executed at market price {current_price} at {timestamp}") + else: + print(f"Invalid order type: {order_type}") + +# Example usage +execute_market_order("buy", "AAPL", 10) diff --git a/test_main.py b/test_main.py index c08ad8fa..4862863c 100644 --- a/test_main.py +++ b/test_main.py @@ -106,3 +106,16 @@ def test_calculate_treynor_ratio(): "risk_free_rate": 0.03, "treynor_ratio": 1.6 } + + +def test_main(): + # Define test parameters + order_type = "buy" + symbol = "AAPL" + quantity = 10 + + # Call the execute_market_order function + execute_market_order(order_type, symbol, quantity) + +# Call the test_main function +test_main() From 683309bd3ecd1215a26bd5bcf9753685a005ddfb Mon Sep 17 00:00:00 2001 From: Nishitbariya <85815172+Nishitbaria@users.noreply.github.com> Date: Tue, 13 Jun 2023 23:46:03 +0530 Subject: [PATCH 06/66] Create auto-comment.yml --- .github/workflows/auto-comment.yml | 60 ++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 .github/workflows/auto-comment.yml diff --git a/.github/workflows/auto-comment.yml b/.github/workflows/auto-comment.yml new file mode 100644 index 00000000..27fe7397 --- /dev/null +++ b/.github/workflows/auto-comment.yml @@ -0,0 +1,60 @@ +name: Auto Comment +on: + issues: + types: + - opened + - closed + - assigned + pull_request: + types: + - opened + - closed + +jobs: + run: + runs-on: ubuntu-latest + steps: + - name: Auto Comment on Issues Opened + uses: wow-actions/auto-comment@v1 + with: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + issuesOpened: | + πŸ‘‹ @{{ author }} + + Thank you for raising an issue. We will investigate into the matter and get back to you as soon as possible. + + Please make sure you have given us as much context as possible. + + - name: Auto Comment on Issues Closed + uses: wow-actions/auto-comment@v1 + with: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + issuesClosed: | + πŸ‘‹ @{{ author }} This issue is closed. + + - name: Auto Comment on Pull Request Merged + uses: wow-actions/auto-comment@v1 + with: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + pullRequestMerged: | + πŸ‘‹ @{{ author }} πŸŽ‰ Congrats on your merged pull request! Thanks for the valuable contribution! πŸ‘πŸŽ‰ Congrats on your merged pull request! Thanks for the valuable contribution! πŸ‘ + + - name: Auto Comment on Pull Request Opened + uses: wow-actions/auto-comment@v1 + with: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + pullRequestOpened: | + HelloπŸ‘‹ @{{ author }}, I hope you are doing well! +
+ Thank you for raising your pull request and contributing to our Community πŸŽ‰ + + Please make sure you have followed our contributing guidelines. We will review it as soon as possible. + + - name: Auto Comment on Issues Assigned + uses: wow-actions/auto-comment@v1 + with: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + issuesAssigned: | + Hello @{{ author }}, thank you for raising an issue. πŸ™Œ I have assigned the issue to you. You can now start working on it. If you encounter any problems, please feel free to connect with us. πŸ‘ + + From 1567bf3b3544d9268ba220d9e5ccd89f74c18b22 Mon Sep 17 00:00:00 2001 From: Anshu Ranjan Date: Thu, 15 Jun 2023 19:05:19 +0530 Subject: [PATCH 07/66] corrected all errors --- helpers/functions.py | 247 ++++++++++++++++++++++++++----------------- main.py | 232 +++++++++++++++++++++++----------------- 2 files changed, 285 insertions(+), 194 deletions(-) diff --git a/helpers/functions.py b/helpers/functions.py index e90f0e32..031b83c8 100644 --- a/helpers/functions.py +++ b/helpers/functions.py @@ -4,6 +4,7 @@ import math import datetime from dateutil.relativedelta import relativedelta +from typing import Union # Function to Calculate Simple Interest Rate @@ -15,12 +16,15 @@ def simple_interest_rate(amount_paid: float, principle_amount: float, months: in # Calculate percent to decimal -def percent_to_decimal(percent: int | float) -> float: - return percent / 100 - +# 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: int | float) -> int | float: + + +def decimal_to_percent(decimal: Union[int, float]) -> float: return decimal * 100 @@ -58,7 +62,8 @@ 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)) + pow((1 + (intrest_rate / compounding_period)), + (compounding_period * years)) ) print(amount) return amount @@ -74,7 +79,8 @@ def inflation(present_amount: float, inflation_rate: float, years: int): # 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 + EAR = pow((1 + (annual_interest_rate / compounding_period)), + compounding_period) - 1 return EAR @@ -90,7 +96,8 @@ def certificate_of_deposit( # 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 + roi = (current_value_of_investment - + cost_of_investment) / cost_of_investment return decimal_to_percent(roi) @@ -111,7 +118,8 @@ def jensens_alpha( beta: float, ): alpha = return_from_investment - ( - risk_free_rate + beta * (return_of_appropriate_market_index - risk_free_rate) + risk_free_rate + beta * + (return_of_appropriate_market_index - risk_free_rate) ) return alpha @@ -242,7 +250,8 @@ def sharpe_ratio( risk_free_rate: float, standard_deviation_of_portfolio: float, ): - sharpe_ratio = (portfolio_return - risk_free_rate) / standard_deviation_of_portfolio + sharpe_ratio = (portfolio_return - risk_free_rate) / \ + standard_deviation_of_portfolio return sharpe_ratio @@ -321,7 +330,8 @@ def acid_test_ratio( accounts_receivable: float, current_liabilities: float, ): - ratio = (cash + marketable_securitie + accounts_receivable) / current_liabilities + ratio = (cash + marketable_securitie + + accounts_receivable) / current_liabilities return round(ratio, 2) @@ -333,11 +343,13 @@ def inflation_adjusted_return( beginning_cpi_level: float, ending_cpi__level: float, ): - stock_return = (ending_price - beginning_price + dividends) / beginning_price + 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) + inflation_adj = decimal_to_percent( + (1 + stock_return) / (1 + inflation) - 1) return round(inflation_adj, 2) @@ -345,7 +357,8 @@ def inflation_adjusted_return( 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) + rate = decimal_to_percent( + pow((beginning_value / ending_value), 1 / years) - 1) return round(rate, 1) @@ -412,11 +425,14 @@ def duration( ) total_payment = n * frequency coupon_payment = coupon_rate / frequency * face_value - payment = [coupon_payment] * (total_payment - 1) + [coupon_payment + 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() + 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) @@ -450,7 +466,8 @@ def inventory_turnover_ratio( # 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) + inflation_rate = decimal_to_percent( + (bigger_year - smaller_year) / base_year) return inflation_rate @@ -469,7 +486,8 @@ def herfindal_Index(Firms_market_shares: str): i = i + 1 market_share_list.append( int( - Firms_market_shares[len(Firms_market_shares) - 2 : len(Firms_market_shares)] + Firms_market_shares[len(Firms_market_shares) - + 2: len(Firms_market_shares)] ) ) herfindal_Index = 0 @@ -530,7 +548,8 @@ def gdp_growth_rate(current_year_gdp: float, last_year_gdp: float): 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)) + 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 @@ -560,7 +579,8 @@ def credit_card_payoff( 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"]) + 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 @@ -570,7 +590,8 @@ def credit_card_payoff( for i in range(len(cards)): if cards[i]["debt"] > 0: interest = round( - percent_to_decimal(cards[i]["debt"] * cards[i]["interest_rate"]) + percent_to_decimal( + cards[i]["debt"] * cards[i]["interest_rate"]) / 12, 2, ) @@ -744,7 +765,8 @@ def perpetuity_payment(present_value: float, rate: float): 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) + zcbv = face_value / \ + pow((1 + percent_to_decimal(rate_of_yield)), time_of_maturity) return round(zcbv, 2) @@ -810,7 +832,8 @@ def net_present_value(cash_flows: str, discount_rate: float, initial_investment: 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)) + cash_flow_list[i] / + ((1 + percent_to_decimal(discount_rate)) ** (i + 1)) ) return net_present_value @@ -866,7 +889,8 @@ def bid_ask_spread(ask_price: float, bid_price: float): # 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)) + n = math.log(future_val / present_val) / \ + math.log(1 + percent_to_decimal(rate)) return n @@ -936,7 +960,8 @@ def calculate_mortgage_interest( 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) + mortgage_annual_payment = loan_amount * \ + (annual_interest_rate * power) / (power - 1) return round(mortgage_annual_payment, 3) @@ -962,7 +987,8 @@ def calculate_fha_mortgage_interest( 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) + 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 @@ -993,7 +1019,8 @@ def roth_ira( 1 + percent_to_decimal(interest_rate) ) taxable_balance = (taxable_balance + annual_contribution) * ( - 1 + percent_to_decimal(interest_rate) * (1 - percent_to_decimal(tax_rate)) + 1 + percent_to_decimal(interest_rate) * + (1 - percent_to_decimal(tax_rate)) ) return math.ceil(roth_ira_balance), math.ceil(taxable_balance) @@ -1157,7 +1184,8 @@ def personal_loan( # Function to calculate lump-sum mutual fund investment def calculate_lumpsum(principal, interest_rate, years): - total_amount = principal * ((1 + percent_to_decimal(interest_rate)) ** years) + total_amount = principal * \ + ((1 + percent_to_decimal(interest_rate)) ** years) interest_earned = total_amount - principal return (total_amount, interest_earned) @@ -1166,7 +1194,8 @@ def main(): principal = float(input("Enter the principal amount: ")) interest_rate = float(input("Enter the interest rate (%): ")) years = int(input("Enter the number of years: ")) - total_amount, interest_earned = calculate_lumpsum(principal, interest_rate, years) + total_amount, interest_earned = calculate_lumpsum( + principal, interest_rate, years) print(f"Total Amount: Rs.{total_amount:.2f}") print(f"Interest Earned: Rs.{interest_earned:.2f}") @@ -1182,7 +1211,8 @@ def calculate_fha_loan(): down_payment_percentage = float(input("Enter down payment percentage: ")) loan_term_years = float(input("Enter loan term (years): ")) interest_rate = float(input("Enter interest rate (%): ")) - fha_annual_mip_percentage = float(input("Enter FHA annual MIP percentage (%): ")) + fha_annual_mip_percentage = float( + input("Enter FHA annual MIP percentage (%): ")) # Calculate down payment and base loan amount down_payment = home_price * percent_to_decimal(down_payment_percentage) @@ -1344,7 +1374,8 @@ def calculate_pension( total_corpus = round(total_corpus, 2) annuity_pension = total_corpus * percent_to_decimal(annuity_purchased) lump_sum_pension = total_corpus - annuity_pension - monthly_pension = round(percent_to_decimal(annuity_pension * annuity_rates) * 12, 2) + monthly_pension = round(percent_to_decimal( + annuity_pension * annuity_rates) * 12, 2) return (total_corpus, lump_sum_pension, monthly_pension) @@ -1358,10 +1389,12 @@ def diluted_eps(net_income, weighted_avg_shares, dilutive_securities): def fixed_deposit_maturity( principle_amount: float, years: int, compounding: str, roi: float ): - types_of_componding = {"yearly": 1, "halfyearly": 2, "quaterly": 4, "monthly": 12} + types_of_componding = {"yearly": 1, + "halfyearly": 2, "quaterly": 4, "monthly": 12} if compounding in types_of_componding.keys(): n = types_of_componding[compounding] - A = principle_amount * (1 + (percent_to_decimal(roi) / n)) ** (n * years) + A = principle_amount * \ + (1 + (percent_to_decimal(roi) / n)) ** (n * years) return round(A, 2) @@ -1369,7 +1402,8 @@ def fixed_deposit_maturity( def recurring_deposit_maturity( principle_amount: float, years: int, compounding: str, roi: float ): - types_of_componding = {"yearly": 1, "halfyearly": 2, "quaterly": 4, "monthly": 12} + types_of_componding = {"yearly": 1, + "halfyearly": 2, "quaterly": 4, "monthly": 12} if compounding in types_of_componding.keys(): months = years * 12 n = types_of_componding[compounding] @@ -1400,7 +1434,8 @@ def calculate_retirement_goals( def student_loan(principal: int, tenure: int, interest_rate: float): monthly_interest_rate = percent_to_decimal(interest_rate) / 12 total_months = tenure * 12 - n = principal * monthly_interest_rate * pow(1 + monthly_interest_rate, total_months) + n = principal * monthly_interest_rate * \ + pow(1 + monthly_interest_rate, total_months) d = pow(1 + monthly_interest_rate, total_months) - 1 emi = n / d total_amount = emi * total_months @@ -1410,7 +1445,8 @@ def student_loan(principal: int, tenure: int, interest_rate: float): # Function to Calculate Return of Investment on some equity funds def calculate_roi_equity_funds(amount_invested, amount_returned, tenure): roi_equity_funds = (amount_returned - amount_invested) / amount_invested - annualized_roi = (1 + (amount_returned / amount_invested)) ** (1 / tenure) - 1 + annualized_roi = (1 + (amount_returned / amount_invested) + ) ** (1 / tenure) - 1 return (decimal_to_percent(roi_equity_funds), decimal_to_percent(annualized_roi)) @@ -1498,7 +1534,8 @@ def calculate_bvps(stockholders_equity, preferred_stock, average_outstanding_sha Returns: float: The book value per share. """ - book_value = (stockholders_equity - preferred_stock) / average_outstanding_shares + book_value = (stockholders_equity - preferred_stock) / \ + average_outstanding_shares return book_value @@ -1553,7 +1590,8 @@ def accrint( settlement_date = datetime.datetime.strptime(settlement_date, "%d-%m-%Y") # Validate basis value if basis not in range(5): - raise ValueError("Invalid basis value. Expected a value between 0 and 4.") + raise ValueError( + "Invalid basis value. Expected a value between 0 and 4.") # Calculate the number of interest periods based on the specified basis if basis == 0: # US (NASD) 30/360 basis @@ -1662,9 +1700,11 @@ def calculate_social_security(birth_date, earnings, retirement_age): # Calculate the reduction factor for claiming benefits before full retirement age if retirement_age < full_retirement_age: - reduction_factor = 1 - ((full_retirement_age - retirement_age) * 5 / 900) + reduction_factor = 1 - \ + ((full_retirement_age - retirement_age) * 5 / 900) else: - reduction_factor = 1.0 # No reduction if retirement age is at or after full retirement age + # No reduction if retirement age is at or after full retirement age + reduction_factor = 1.0 # Calculate the primary insurance amount (PIA) pia = earnings * reduction_factor @@ -1677,24 +1717,27 @@ def calculate_social_security(birth_date, earnings, retirement_age): future_benefits = monthly_benefits * (1 + 0.02) ** years_to_retirement return monthly_benefits, future_benefits - - + + # Function to calculate net profit margin def calculate_net_profit_margin( - revenue : float, - cost_of_goods_sold : float, - operating_expenses : float, - other_expenses : float, - interest : float, - taxes : float): - net_profit_margin = ((revenue-cost_of_goods_sold-operating_expenses-other_expenses-interest-taxes)/revenue)*100 + revenue: float, + cost_of_goods_sold: float, + operating_expenses: float, + other_expenses: float, + interest: float, + taxes: float): + net_profit_margin = ((revenue-cost_of_goods_sold - + operating_expenses-other_expenses-interest-taxes)/revenue)*100 return net_profit_margin # Function to calculate expected return of portfolio + + def calculate_expected_return_of_portfolio( - no_of_investments : int, - investment_amount : list, - rate_of_return : list): + no_of_investments: int, + investment_amount: list, + rate_of_return: list): total_value_of_portfolio = 0 for i in range(no_of_investments): total_value_of_portfolio += investment_amount[i] @@ -1705,44 +1748,49 @@ def calculate_expected_return_of_portfolio( expected_return_of_portfolio = 0 for i in range(no_of_investments): - expected_return_of_portfolio += weight_of_investment[i]*rate_of_return[i] - + expected_return_of_portfolio += weight_of_investment[i] * \ + rate_of_return[i] + return expected_return_of_portfolio -#Function to calculate net annual salary -def calculate_salary(base:int, - jb:int, - stock:int, - pb:int, - bonus:int, - ptax:int, - deduction:int): - total_amount=(base*12)+jb+stock+pb+bonus - tax=(ptax/100)*total_amount - ctc=total_amount-tax-deduction +# Function to calculate net annual salary + + +def calculate_salary(base: int, + jb: int, + stock: int, + pb: int, + bonus: int, + ptax: int, + deduction: int): + total_amount = (base*12)+jb+stock+pb+bonus + tax = (ptax/100)*total_amount + ctc = total_amount-tax-deduction return ctc -#function to calculate the Sharpe ratio in Python +# function to calculate the Sharpe ratio in Python + def sharpe_ratio(returns, risk_free_rate): """ Calculate the Sharpe ratio given a series of returns and the risk-free rate. - + Parameters: - returns (array-like): An array-like object containing the returns of an investment/portfolio. - risk_free_rate (float): The risk-free rate of return. - + Returns: - float: The calculated Sharpe ratio. """ avg_return = np.mean(returns) std_dev = np.std(returns) - + sharpe_ratio = (avg_return - risk_free_rate) / std_dev - + return sharpe_ratio -#You can use this function by passing your investment/portfolio returns and the risk-free rate to it. For example: +# You can use this function by passing your investment/portfolio returns and the risk-free rate to it. For example: + returns = [0.05, 0.03, 0.02, 0.04, 0.06] # Example returns risk_free_rate = 0.02 # Example risk-free rate @@ -1750,25 +1798,31 @@ def sharpe_ratio(returns, risk_free_rate): sharpe = sharpe_ratio(returns, risk_free_rate) print(f"The Sharpe ratio is: {sharpe}") -#Function to calculate Loan to Value Ratio +# Function to calculate Loan to Value Ratio + def loan_to_value_ratio( - loan_amount:float, - value_of_collateral:float): + loan_amount: float, + value_of_collateral: float): ratio = (loan_amount / value_of_collateral) * 100 return ratio # Function to calculate post tax return percentage -def calculate_post_tax_return_percentage(tax_rate_percentage : float, - annual_net_income : float, - initial_cost_of_investment : float - ): - rate_of_return_percentage = (annual_net_income / initial_cost_of_investment)*100 - post_tax_return_percentage = rate_of_return_percentage - (rate_of_return_percentage * tax_rate_percentage)/100 - return post_tax_return_percentage -#Function to calculate the Treynor Ratio in python +def calculate_post_tax_return_percentage(tax_rate_percentage: float, + annual_net_income: float, + initial_cost_of_investment: float + ): + rate_of_return_percentage = ( + annual_net_income / initial_cost_of_investment)*100 + post_tax_return_percentage = rate_of_return_percentage - \ + (rate_of_return_percentage * tax_rate_percentage)/100 + + return post_tax_return_percentage + +# Function to calculate the Treynor Ratio in python + def calculate_treynor_ratio(returns, risk_free_rate, beta): """ @@ -1786,7 +1840,8 @@ def calculate_treynor_ratio(returns, risk_free_rate, beta): """ if isinstance(returns, list): - returns = sum(returns) # Calculate the total return if periodic returns are provided + # Calculate the total return if periodic returns are provided + returns = sum(returns) treynor_ratio = (returns - risk_free_rate) / beta return treynor_ratio @@ -1800,19 +1855,20 @@ def calculate_treynor_ratio(returns, risk_free_rate, beta): treynor_ratio = calculate_treynor_ratio(returns, risk_free_rate, beta) print(f"Treynor Ratio: {treynor_ratio}") -#Function to Calculate Free Cash Flow to Equity +# Function to Calculate Free Cash Flow to Equity + def free_cash_flow_to_equity( - total_revenues:float, - total_expenses:float, - initial_cost_of_asset: float, - lifetime_of_asset: float, - change_in_PPE:float, - current_depreciation:float, - current_assets:float, - current_liabilities:float, - amount_a_company_borrows:float, - debt_it_repays:float): + total_revenues: float, + total_expenses: float, + initial_cost_of_asset: float, + lifetime_of_asset: float, + change_in_PPE: float, + current_depreciation: float, + current_assets: float, + current_liabilities: float, + amount_a_company_borrows: float, + debt_it_repays: float): net_income = total_revenues - total_expenses, depreciation_and_amortization = initial_cost_of_asset / lifetime_of_asset, @@ -1820,5 +1876,6 @@ def free_cash_flow_to_equity( change_in_working_capital = current_assets - current_liabilities, net_borrowing = amount_a_company_borrows - debt_it_repays, - fcfe = net_income + depreciation_and_amortization - capEx - change_in_working_capital + net_borrowing + fcfe = net_income + depreciation_and_amortization - \ + capEx - change_in_working_capital + net_borrowing return fcfe diff --git a/main.py b/main.py index e56452df..6ff7efed 100644 --- a/main.py +++ b/main.py @@ -142,7 +142,8 @@ def index(): ) def simple_interest_rate(amount_paid: float, principle_amount: float, months: int): try: - rate = functions.simple_interest_rate(amount_paid, principle_amount, months) + rate = functions.simple_interest_rate( + amount_paid, principle_amount, months) return { "Tag": "Simple Interest Rate", "Total amount paid": amount_paid, @@ -285,7 +286,8 @@ def certificate_of_deposit( @app.get("/inflation", tags=["inflated"], description="Calculate Inflated amount") def inflation(present_amount: float, inflation_rate: float, years: float): try: - future_amount = functions.inflation(present_amount, inflation_rate, years) + future_amount = functions.inflation( + present_amount, inflation_rate, years) return { "Tag": "Inflated Amount", "Present Amount": present_amount, @@ -308,7 +310,8 @@ def effective_annual_rate(annual_interest_rate: float, compounding_period: int): eff_annual_rate = functions.effective_annual_rate( annual_interest_rate, compounding_period ) - eff_annual_rate_percentage = functions.decimal_to_percent(eff_annual_rate) + eff_annual_rate_percentage = functions.decimal_to_percent( + eff_annual_rate) return { "Tag": "Effective Annual Rate", "Annual Intrest Rate": annual_interest_rate, @@ -486,7 +489,8 @@ def asset_portfolio( ) def put_call_parity(call_price: float, put_price: float, strike_price: float): try: - future_amount = functions.put_call_parity(call_price, put_price, strike_price) + future_amount = functions.put_call_parity( + call_price, put_price, strike_price) return { "Tag": "Pull Call Parity", "Future Price": f"{future_amount}", @@ -507,7 +511,8 @@ def put_call_parity(call_price: float, put_price: float, strike_price: float): def break_even_point(fixed_cost: float, selling_price: float, variable_cost: float): try: - bep = functions.break_even_point(fixed_cost, selling_price, variable_cost) + bep = functions.break_even_point( + fixed_cost, selling_price, variable_cost) return { "Tag": "Break Even Point (BEP)", "Fixed costs": fixed_cost, @@ -584,7 +589,8 @@ def price_to_earning_ratio(share_price: float, earnings_per_share: float): ) def dividend_yield_ratio(dividend_per_share: float, share_price: float): try: - dividend_yield = functions.dividend_yield_ratio(dividend_per_share, share_price) + dividend_yield = functions.dividend_yield_ratio( + dividend_per_share, share_price) return { "Tag": "Dividend yield ratio", "Dividend per share": dividend_per_share, @@ -624,7 +630,8 @@ def dividend_payout_ratio(dividend_per_share: float, earnings_per_share: float): ) def debt_to_income_ratio(annual_income: float, total_debt_per_month: float): try: - DTI = functions.debt_to_income_ratio(annual_income, total_debt_per_month) + DTI = functions.debt_to_income_ratio( + annual_income, total_debt_per_month) return { "Tag": "Debt to income ratio", "Annual income": annual_income, @@ -945,8 +952,10 @@ def inflation_adjusted_return( ending_cpi__level: float, ): try: - stock_return = (ending_price - beginning_price + dividends) / beginning_price - inflation = (ending_cpi__level - beginning_cpi_level) / beginning_cpi_level + stock_return = (ending_price - beginning_price + + dividends) / beginning_price + inflation = (ending_cpi__level - beginning_cpi_level) / \ + beginning_cpi_level inflation_adj_return = functions.inflation_adjusted_return( beginning_price, ending_price, @@ -1094,7 +1103,8 @@ def duration(rate, coupon_rate, frequency, face_value, settlement_date, maturity ) def current_ratio(total_current_assets: float, total_liabilities: float): try: - ratio = functions.current_ratio(total_current_assets, total_liabilities) + ratio = functions.current_ratio( + total_current_assets, total_liabilities) return { "Tag": "Current Ratio", "Total Current Assets": total_current_assets, @@ -1135,7 +1145,8 @@ def inventory_turnover_ratio( ) def inflation_rate(bigger_year: int, smaller_year: int, base_year: int): try: - inflation_rate = functions.inflation_rate(bigger_year, smaller_year, base_year) + inflation_rate = functions.inflation_rate( + bigger_year, smaller_year, base_year) return { "Tag": "Inflation Rate", "Bigger Year": bigger_year, @@ -1230,7 +1241,8 @@ def real_gdp(nominal_gdp: float, gdp_deflator: float): ) def excess_reserves(deposits: float, reserve_requirement: float): try: - excess_reserves = functions.excess_reserves(deposits, reserve_requirement) + excess_reserves = functions.excess_reserves( + deposits, reserve_requirement) return { "Tag": "Excess Reserves", "Deposits": deposits, @@ -1275,7 +1287,8 @@ def discounted_cash_flow( ) def gdp_growth_rate(current_year_gdp: float, last_year_gdp: float): try: - gdp_growth_rate = functions.gdp_growth_rate(current_year_gdp, last_year_gdp) + gdp_growth_rate = functions.gdp_growth_rate( + current_year_gdp, last_year_gdp) return { "Tag": "GDP Growth Rate", "Current Year GDP": current_year_gdp, @@ -1476,7 +1489,8 @@ def retention_ratio(net_income: float, dividends: float): ) def tax_equivalent_yield(tax_free_yield: float, tax_rate: float): try: - tax_equivalent_yield = functions.tax_equivalent_yield(tax_free_yield, tax_rate) + tax_equivalent_yield = functions.tax_equivalent_yield( + tax_free_yield, tax_rate) return { "Tag": "Tax Equivalent Yield", "Tax Free Yield": tax_free_yield, @@ -1495,7 +1509,8 @@ def tax_equivalent_yield(tax_free_yield: float, tax_rate: float): ) def year_over_year(later_period_value: float, earlier_period_value: float): try: - growth = functions.year_over_year(later_period_value, earlier_period_value) + growth = functions.year_over_year( + later_period_value, earlier_period_value) return { "Tag": "Year to Year Growth", "Year to Year growth": f"{growth}%", @@ -1898,7 +1913,8 @@ def time_period_required_for_growth(interest_rate: float, growth_factor: int): ) def preferred_stock_value(dividend: float, discount_rate: float): try: - preferred_stock_value = functions.preferred_stock_value(dividend, discount_rate) + preferred_stock_value = functions.preferred_stock_value( + dividend, discount_rate) return { "Tag": "Preferred stock value", "Dividend": dividend, @@ -2060,7 +2076,8 @@ def estimate_401k( "withdraw_tax_rate": withdraw_tax_rate, "estimated_401k": estimated_401k, "annual_withdraw_amount": round( - functions.percent_to_decimal(withdraw_tax_rate) * estimated_401k, 3 + functions.percent_to_decimal( + withdraw_tax_rate) * estimated_401k, 3 ), } except: @@ -2370,7 +2387,8 @@ def commission_calc( sales_price: float = None, commission_rate: float = None, commission: float = None ): try: - output = functions.commission_calc(sales_price, commission_rate, commission) + output = functions.commission_calc( + sales_price, commission_rate, commission) if sales_price == None and commission_rate != None and commission != None: return { @@ -2765,26 +2783,28 @@ def calculate_gratuity(last_salary: float, tenure_years: int, tenure_months: int except: return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + @app.get( "/personal_savings", tags=["personal_savings"], description="Calculate Simple Personal Savings", ) -def personal_savings(init:int, - monthly:int, - tenure:float): +def personal_savings(init: int, + monthly: int, + tenure: float): try: - personal_savings = functions.personal_savings(init,monthly,tenure) + personal_savings = functions.personal_savings(init, monthly, tenure) return { "Tag": "Simple Personal Savings", - "Initial Deposit":init, - "total number of years":tenure, - "Monthly Contribution":monthly, + "Initial Deposit": init, + "total number of years": tenure, + "Monthly Contribution": monthly, "Total Amount Saved": f"{total_amount}", - } + } except: return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + @app.get( "/accrint", tags=["accrint"], @@ -2814,13 +2834,12 @@ def accrued_interest( } except: return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) - -@app.get('/mortrages',tags=["mortrage"],description="Endpoint to calculate Mortrages") -def mortrage(princial:int,interest_rate:float,years:int,down_payment:int,property_tax_rate:float,insurance_rate:float): - - try: +@app.get('/mortrages', tags=["mortrage"], description="Endpoint to calculate Mortrages") +def mortrage(princial: int, interest_rate: float, years: int, down_payment: int, property_tax_rate: float, insurance_rate: float): + + try: mortrage = functions.calculate_mortgage( principal=princial, interest_rate=interest_rate, @@ -2840,19 +2859,21 @@ def mortrage(princial:int,interest_rate:float,years:int,down_payment:int,propert except: return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + @app.get( "/calculate_net_profit_margin", tags=["net_profit_margin"], description="Calculate net profit margin", - ) -def calculate_net_profit_margin(revenue : float, - cost_of_goods_sold : float, - operating_expenses : float, - other_expenses : float, - interest : float, - taxes : float): +) +def calculate_net_profit_margin(revenue: float, + cost_of_goods_sold: float, + operating_expenses: float, + other_expenses: float, + interest: float, + taxes: float): try: - net_profit_margin = functions.calulate_net_profit_margin(revenue, cost_of_goods_sold, operating_expenses, other_expenses, interest, taxes) + net_profit_margin = functions.calulate_net_profit_margin( + revenue, cost_of_goods_sold, operating_expenses, other_expenses, interest, taxes) return { "Tag": "Calculate net profit margin", "Revenue": revenue, @@ -2861,56 +2882,61 @@ def calculate_net_profit_margin(revenue : float, "Interest": interest, "Taxes": taxes, "Net Profit Margin": net_profit_margin, - - } + + } except: return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) - + + @app.get( "/calculate_expected_return_of_portfolio", tags=["expected_return_of_portfolio"], description="Calculate expected return of portfolio", - ) -def calculate_expected_return_of_portfolio(no_of_investments : int, - investment_amount : list, - rate_of_return : list): +) +def calculate_expected_return_of_portfolio(no_of_investments: int, + investment_amount: list, + rate_of_return: list): try: - expected_return_of_portfolio = functions.calculate_expected_return_of_portfolio(no_of_investments, investment_amount, rate_of_return) + expected_return_of_portfolio = functions.calculate_expected_return_of_portfolio( + no_of_investments, investment_amount, rate_of_return) return { "Tag": "Calculate expected return of portfolio", "No of investments": no_of_investments, "Investment Amount": investment_amount, "Rate of Return": rate_of_return - - } + + } except: return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) -#Endpoint to calculate Net annual salary of an employee +# Endpoint to calculate Net annual salary of an employee + + @app.get( "/calculate_salary", tags=["calculate_salary"], description="Calculate Net annual salary of an employee", - ) -def calculate_salary(base:int, - jb:int, - stock:int, - pb:int, - bonus:int, - ptax:int, - deduction:int): - try: - calculate_salary = functions.calculate_salary(base,jb,stock,pb,bonus,ptax,deduction): - return { - - "Tag":"Net Salary Calculator", - "Base Salary per month":base, - "joining bonus/retention bonus":jb, - "RSU/stock bonus":stock, - "performance bonus":pb, - "any additional bonus":bonus, - "tax percentage":ptax, - "any additional deduction":deduction, +) +def calculate_salary(base: int, + jb: int, + stock: int, + pb: int, + bonus: int, + ptax: int, + deduction: int): + try: + calculate_salary = functions.calculate_salary( + base, jb, stock, pb, bonus, ptax, deduction) + return { + + "Tag": "Net Salary Calculator", + "Base Salary per month": base, + "joining bonus/retention bonus": jb, + "RSU/stock bonus": stock, + "performance bonus": pb, + "any additional bonus": bonus, + "tax percentage": ptax, + "any additional deduction": deduction, "ctc calculated": f"{ctc}", } except: @@ -2922,7 +2948,7 @@ def calculate_salary(base:int, tags=['Social Security'], description="Endpoint to calculate Social securities" ) -def ss(birth_date:str,earnings:int,retirement_age:int): +def ss(birth_date: str, earnings: int, retirement_age: int): try: monthly_benefits, future_benefits = functions.calculate_social_security( @@ -2933,31 +2959,34 @@ def ss(birth_date:str,earnings:int,retirement_age:int): return { f"The monthly benefits are {monthly_benefits} and future benefits are {future_benefits}" } - + except: return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + @app.get( "/calculate_post_tax_return_percentage", tags=["post_tax_return_percentage"], description="Calculate post tax return percentage", - ) -def calculate_post_tax_return_percentage(tax_rate_percentage : float, - annual_net_income : float, - initial_cost_of_investment : float): +) +def calculate_post_tax_return_percentage(tax_rate_percentage: float, + annual_net_income: float, + initial_cost_of_investment: float): try: - post_tax_return_percentage = functions.calculate_post_tax_return_percentage(tax_rate_percentage, annual_net_income, initial_cost_of_investment) + post_tax_return_percentage = functions.calculate_post_tax_return_percentage( + tax_rate_percentage, annual_net_income, initial_cost_of_investment) return { "Tag": "Calculate post tax return percentage", "Tax Rate Percentage": tax_rate_percentage, "Annual net income": annual_net_income, "Initial cost of investment": initial_cost_of_investment, "Post tax return percentage": post_tax_return_percentage - } + } except: return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) -#Endpoint for function Sharpe ratio +# Endpoint for function Sharpe ratio + @app.get( "/sharpe_ratio", @@ -2977,10 +3006,11 @@ def sharpe_ratio( "Sharpe Ratio": ratio, } except Exception as e: - raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e)) - - -#Endpoint for function Treynor Ratio + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e)) + + +# Endpoint for function Treynor Ratio @app.get( "/treynor_ratio", @@ -2991,7 +3021,8 @@ def treynor_ratio( returns: list[float], risk_free_rate: float, beta: float ): try: - ratio = functions.calculate_treynor_ratio(returns, risk_free_rate, beta) + ratio = functions.calculate_treynor_ratio( + returns, risk_free_rate, beta) return { "Tag": "Treynor Ratio", "Returns": returns, @@ -3000,16 +3031,18 @@ def treynor_ratio( "Treynor Ratio": ratio, } except Exception as e: - raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e)) + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e)) + +# Endpoint for function Loan to Value Ratio -#Endpoint for function Loan to Value Ratio @app.get( "/loan_to_value_ratio", tags=["loan_to_value_ratio"], description="Calculate loan amount to value of collateral ratio", ) -def loan_to_value_ratio (loan_amount:float, value_of_collateral:float): +def loan_to_value_ratio(loan_amount: float, value_of_collateral: float): try: ratio = functions.loan_to_value_ratio(loan_amount, value_of_collateral) return { @@ -3021,7 +3054,8 @@ def loan_to_value_ratio (loan_amount:float, value_of_collateral:float): except: return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) -#Endpoint for function Free Cash Flow To Equity +# Endpoint for function Free Cash Flow To Equity + @app.get( "/free_cash_flow_to_equity", @@ -3029,17 +3063,17 @@ def loan_to_value_ratio (loan_amount:float, value_of_collateral:float): description="Calculate Free Cash Flow to Equity", ) def free_cash_flow_to_equity( - total_revenues:float, - total_expenses:float, - initial_cost_of_asset: float, - lifetime_of_asset: float, - change_in_PPE:float, - current_depreciation:float, - current_assets:float, - current_liabilities:float, - amount_a_company_borrows:float, - debt_it_repays:float): - try : + total_revenues: float, + total_expenses: float, + initial_cost_of_asset: float, + lifetime_of_asset: float, + change_in_PPE: float, + current_depreciation: float, + current_assets: float, + current_liabilities: float, + amount_a_company_borrows: float, + debt_it_repays: float): + try: fcfe = functions.free_cash_flow_to_equity( total_revenues, total_expenses, initial_cost_of_asset, lifetime_of_asset, change_in_PPE, current_depreciation, current_assets, current_liabilities, From cd077fbe87603c4ee51ff5a755108dc097247b6b Mon Sep 17 00:00:00 2001 From: ramya-kallam Date: Sat, 17 Jun 2023 11:02:44 +0530 Subject: [PATCH 08/66] Added endpoint for financial leverage --- ENDPOINTS.md | 14 ++++++++++++++ helpers/functions.py | 14 ++++++++++++++ main.py | 24 ++++++++++++++++++++++++ 3 files changed, 52 insertions(+) diff --git a/ENDPOINTS.md b/ENDPOINTS.md index d4272495..d6c0159d 100644 --- a/ENDPOINTS.md +++ b/ENDPOINTS.md @@ -1910,4 +1910,18 @@ Sample Output "Net Borrowing": 350000.0, "Free Cash Flow to Equity": 620000.0 } +``` +**GET** `/calculate_financial_leverage` +-Required parameters: `total_assets`, `total_liabilities`, `short_term_debt`, `long_term_debt` +-Sample Output +```py +{ + "Tag" : "Calculate financial leverage", + "total_assets" : 16645, + "total_liabilities" : 9906, + "short_term_debt" : 5000, + "long_term_debt" : 10000, + "financial_leverage" : 1.51 +} + ``` \ No newline at end of file diff --git a/helpers/functions.py b/helpers/functions.py index 031b83c8..917daa22 100644 --- a/helpers/functions.py +++ b/helpers/functions.py @@ -1879,3 +1879,17 @@ def free_cash_flow_to_equity( fcfe = net_income + depreciation_and_amortization - \ capEx - change_in_working_capital + net_borrowing return fcfe + +# Function to calculate Financial Leverage +def calculate_financial_leverage(total_assets : float, + total_liabilities : float, + short_term_debt : float, + long_term_debt : float + ): + debt = short_term_debt + long_term_debt + + shareholder_equity = total_assets - total_liabilities + + financial_leverage = debt / shareholder_equity + + return financial_leverage \ No newline at end of file diff --git a/main.py b/main.py index 6ff7efed..05fe72ae 100644 --- a/main.py +++ b/main.py @@ -3106,3 +3106,27 @@ def free_cash_flow_to_equity( } except: return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + +@app.get( + "/calculate_financial_leverage", + tags=["financial_leverage"], + description="Calculate financial leverage", +) +def calculate_financial_leverage(total_assets : float, + total_liabilities : float, + short_term_debt : float, + long_term_debt : float + ): + try: + financial_leverage = functions.calculate_financial_leverage( + total_assets, total_liabilities, short_term_debt, long_term_debt) + return { + "Tag": "Calculate financial leverage", + "Total Assets": total_assets, + "Total Liabilities": total_liabilities, + "Short term debt": short_term_debt, + "Long term debt": long_term_debt, + "Financial Leverage": financial_leverage + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file From 2f8b2d4b1ae02defa391feaf1ebe2ee53a162349 Mon Sep 17 00:00:00 2001 From: DyuthiVivek Date: Mon, 19 Jun 2023 20:40:30 +0530 Subject: [PATCH 09/66] added function to calculate macaulay duration --- ENDPOINTS.md | 30 +++++++++++++++++++++++++++++- helpers/functions.py | 28 ++++++++++++++++++++++++++++ main.py | 31 +++++++++++++++++++++++++++++++ 3 files changed, 88 insertions(+), 1 deletion(-) diff --git a/ENDPOINTS.md b/ENDPOINTS.md index d4272495..c7630233 100644 --- a/ENDPOINTS.md +++ b/ENDPOINTS.md @@ -1910,4 +1910,32 @@ Sample Output "Net Borrowing": 350000.0, "Free Cash Flow to Equity": 620000.0 } -``` \ No newline at end of file +``` + + +**GET** `/macaulay-duration` +- Required parameters : `face_value`, + `coupon_rate`, + `dt`, + `month`, + `year`, + `coupon_frequency`, + `discount_rate`, + +- Sample Request: `GET`, `http://localhost:8000/calculate_macaulay_duration?face_value=1000.0&coupon_rate=0.06&dt=19&month=6&year=2026&coupon_frequency=2&discount_rate=0.06`, +- Sample output +```py +{ + { + "Tag": "Macaulay_duration", + "Face-value of bond": 1000.0, + "Coupon Rate (in decimal)": 0.06, + "Date of maturity(DD)": 19, + "Month of maturity(MM)": 6, + "Year of maturity(YY)": 2026, + "Coupon frequency": 2, + "Discount frequency (int decimal)": 0.06, + "Macaulay duration": 2.77 + } +} +``` diff --git a/helpers/functions.py b/helpers/functions.py index 031b83c8..7bf43849 100644 --- a/helpers/functions.py +++ b/helpers/functions.py @@ -1879,3 +1879,31 @@ def free_cash_flow_to_equity( fcfe = net_income + depreciation_and_amortization - \ capEx - change_in_working_capital + net_borrowing return fcfe + +#function to calculate macaulay duration +def calculate_macaulay_duration(face_value : float, coupon_rate : float, dt : int, month : int, year : int, coupon_frequency : int, discount_rate : float): + cash_flows = [] + maturity_date = datetime.date(year, month, dt) + years_to_maturity = (maturity_date - datetime.date.today()).days / 365.25 + + # Calculate the coupon payment amount + coupon_payment = face_value * coupon_rate / coupon_frequency + + # Generate the cash flows + for i in range(1, int(years_to_maturity * coupon_frequency) + 1): + if i == int(years_to_maturity * coupon_frequency): + # Last period's cash flow includes the final coupon payment plus the face value + cash_flows.append(coupon_payment + face_value) + else: + cash_flows.append(coupon_payment) + + duration = 0.0 + present_value = 0.0 + + + for i, cash_flow in enumerate(cash_flows): + present_value += cash_flow / (1 + discount_rate) ** (i + 1) + duration += (i + 1) * (cash_flow / (1 + discount_rate) ** (i + 1)) + + return round((duration / present_value)/ coupon_frequency, 2) + diff --git a/main.py b/main.py index 6ff7efed..8a393596 100644 --- a/main.py +++ b/main.py @@ -3106,3 +3106,34 @@ def free_cash_flow_to_equity( } except: return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + +@app.get( + "/calculate_macaulay_duration", + tags=["Macaulay_duration"], + description="Calculate macaulay duration", +) +def calculate_macaulay_duration( + face_value : float, coupon_rate : float, dt : int, month : int, year : int, coupon_frequency : int, discount_rate : float +): + ''' + Macaulay duration is the weighted average term to maturity of the cash flows from a bond. + Inputs: face value of bond, coupon rate, dt, month, year of maturity, coupon frequency, discount rate + Ouput: Macaulay duration in years + ''' + try: + duration = functions.calculate_gratuity( + face_value, coupon_rate, dt, month, year, coupon_frequency, discount_rate + ) + return { + "Tag": "Macaulay_duration", + "Face-value of bond": face_value, + "Coupon Rate (in decimal)": coupon_rate, + "Date of maturity(DD)": dt, + "Month of maturity(MM)": month, + "Year of maturity(YY)": year, + "Coupon frequency": coupon_frequency, + "Discount frequency (int decimal)": discount_rate, + "Macaulay duration": f"{duration}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) From 4c4a9056cfaac37366d612640f761f95a13f54af Mon Sep 17 00:00:00 2001 From: Shivansh Date: Tue, 20 Jun 2023 15:23:36 +0530 Subject: [PATCH 10/66] Adding unit-tests for all end-points --- test_main.py | 1406 ++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 1362 insertions(+), 44 deletions(-) diff --git a/test_main.py b/test_main.py index 4862863c..d8531a11 100644 --- a/test_main.py +++ b/test_main.py @@ -1,5 +1,5 @@ from main import app -from fastapi import FastAPI +from fastapi import status from fastapi.testclient import TestClient import json @@ -54,68 +54,1386 @@ def test_certificate_of_deposit_invalid_type(): def test_simple_interest_rate_main(): response = client.get( - "/simple_interest_rate/?amount_paid=5000&principle_amount=4500&months=12" + "http://127.0.0.1:8000/simple_interest_rate?amount_paid=4500&principle_amount=453&months=3" ) assert response.status_code == 200 assert response.json() == { - "Tag": "Simple Interest Rate", - "Total amount paid": 5000, - "Principle amount": 4500, - "Interest Paid": 500, - "Interest Rate": f"11.11111111111111%", - } + "Tag": "Simple Interest Rate", + "Total amount paid": 4500, + "Principle amount": 453, + "Interest Paid": 4047, + "Interest Rate": "3573.5099337748343%" +} +# +# def test_roi_main(): +# response = client.get("/roi/?current_value_of_investment=100&cost_of_investment=80") +# assert response.status_code == 200 +# +# assert response.json() == { +# "Tag": "Return on Investment", +# "Current Value of Investment": 100, +# "Cost of Investment": 80, +# "Return on Investment": f"25.0%", +# } +# +# +# def test_calculate_enterprise_value_main(): +# response = client.get( +# "/enterprise-value/?share_price=10.00&fully_diluted_shares_outstanding=100&total_debt=500.00&preferred_stock=500.00&non_controlling_interest=1000.00&cash_and_cash_equivalents=1000.00" +# ) +# assert response.status_code == 200 +# +# assert response.json() == { +# "Tag": "Enterprise Value", +# "Equity Value": 1000, +# "Total Debt": 500, +# "Preferred Stock": 500, +# "Non-Controlling Interest": 1000, +# "Cash & Cash Equivalents": 1000, +# "Enterprise Value": 2000, +# } +# +# +# # def test_calculate_treynor_ratio(): +# # response = client.get("/calculate_treynor_ratio/?returns=0.1,0.05,0.08,0.12,0.09&risk_free_rate=0.03") +# # assert response.status_code == 200 +# # +# # assert response.json() == { +# # "Tag": "Treynor Ratio", +# # "returns": [0.1, 0.05, 0.08, 0.12, 0.09], +# # "risk_free_rate": 0.03, +# # "treynor_ratio": 1.6 +# # } +# +# +# +def test_future_sip(): + response = client.get( + "http://127.0.0.1:8000/future_sip?interval_investment=1257&rate_of_return=3&number_of_payments=7" + ) + assert response.status_code == status.HTTP_200_OK -def test_roi_main(): - response = client.get("/roi/?current_value_of_investment=100&cost_of_investment=80") - assert response.status_code == 200 + assert response.json() == { + "Tag": "Future Value of SIP", + "Investment at every Interval": 1257, + "Interest": 0.0025, + "Number of Payments": 7, + "Future Value": "8887.431327596654" +} + + +def test_calculate_pension(): + response = client.get( + "http://127.0.0.1:8000/calculate_pension?monthly_investment_amount=1239&no_of_years=5&annuity_rates=3&annuity_purchased=5&yearly_interest_rates=2" + ) + assert response.status_code == status.HTTP_200_OK assert response.json() == { - "Tag": "Return on Investment", - "Current Value of Investment": 100, - "Cost of Investment": 80, - "Return on Investment": f"25.0%", - } + "status_code": 500, + "detail": "Internal Server Error", + "headers": None +} -def test_calculate_enterprise_value_main(): +def test_payback_period_years(): response = client.get( - "/enterprise-value/?share_price=10.00&fully_diluted_shares_outstanding=100&total_debt=500.00&preferred_stock=500.00&non_controlling_interest=1000.00&cash_and_cash_equivalents=1000.00" + "http://127.0.0.1:8000/payback_period?years_before_recovery=2&unrecovered_cost=2456&cash_flow=21" ) - assert response.status_code == 200 + assert response.status_code == status.HTTP_200_OK assert response.json() == { - "Tag": "Enterprise Value", - "Equity Value": 1000, - "Total Debt": 500, - "Preferred Stock": 500, - "Non-Controlling Interest": 1000, - "Cash & Cash Equivalents": 1000, - "Enterprise Value": 2000, - } + "Tag": "Payback period", + "Years before full recovery": 2, + "Unrecovered cost at start of the year": 2456, + "Cash flow during the year": 21, + "Payback period": "118.95238095238095" +} -def test_calculate_treynor_ratio(): - response = client.get("/calculate_treynor_ratio/?returns=0.1,0.05,0.08,0.12,0.09&risk_free_rate=0.03") - assert response.status_code == 200 +def test_compound_interest_amount(): + response = client.get( + "http://127.0.0.1:8000/compound_interest?principal_amount=6464&interest_rate=6&years=4&compounding_period=4" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() =={ + "Tag": "Compound Interest Amount", + "Principle amount": 6464, + "Intrest Rate": 6, + "Time in Years": 4, + "Compounding Period": 4, + "Amount after interest": "15050172805.786133" +} + +def test_certificate_of_deposit(): + response = client.get( + "http://127.0.0.1:8000/certificate_of_deposit?principal_amount=4555&interest_rate=5&yrs=3&compounding_per_yr=5" + ) + assert response.status_code == status.HTTP_200_OK assert response.json() == { - "Tag": "Treynor Ratio", - "returns": [0.1, 0.05, 0.08, 0.12, 0.09], - "risk_free_rate": 0.03, - "treynor_ratio": 1.6 - } + "Tag": "Certificate of Deposit (CD)", + "Principal amount": 4555, + "Interest Rate": 5, + "Time in Years": 3, + "Number of Compounding per Year": 5, + "Certificate of Deposit (CD)": "5288.213591710344" +} + +def test_inflated(): + response = client.get( + "http://127.0.0.1:8000/inflation?present_amount=332&inflation_rate=4&years=3" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Inflated Amount", + "Present Amount": 332, + "Inflation Rate": 4, + "Time in Years": 3, + "Future Amount": "373.454848" +} + +def test_effective_annual_rate(): + response = client.get( + "http://127.0.0.1:8000/effective_annual_rate?annual_interest_rate=5&compounding_period=4" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Effective Annual Rate", + "Annual Intrest Rate": 5, + "Compounding Period": 4, + "Effective Annual Rate (in percentage)": "2462.890625%" +} + +def test_return_on_investment(): + response = client.get( + "http://127.0.0.1:8000/roi?current_value_of_investment=677&cost_of_investment=34" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Return on Investment", + "Current Value of Investment": 677, + "Cost of Investment": 34, + "Return on Investment": "1891.1764705882351%" +} + +def test_compounded_annual_growth_rate(): + response = client.get( + "http://127.0.0.1:8000/compounded_annual_growth_rate?end_investment_value=456&initial_investment_value=113&years=4" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Compounded Annual Growth Rate", + "End investment value": 456, + "Initial investment value": 113, + "Years": 4, + "Compounded Annual Growth Rate": "0.4173320235605005%" +} + +def test_jensens_alpha(): + response = client.get( + "http://127.0.0.1:8000/jensens_alpha?return_from_investment=4566&return_of_appropriate_market_index=32&risk_free_rate=3&beta=45" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Jensen's Alpha", + "Total return from investment": 4566, + "Return of appropriate market index": 32, + "Risk free rate": 3, + "Beta of the portfolio investment w.r.t chosen market index": 45, + "Alpha of the return ": "3258.0%" +} + +def test_wacc(): + response = client.get( + "http://127.0.0.1:8000/wacc?firm_equity=4553&firm_debt=3&cost_of_equity=55&cost_of_debt=33&corporate_tax_rate=5" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "status_code": 500, + "detail": "Internal Server Error", + "headers": None +} + +def test_load_emi(): + response = client.get( + "http://127.0.0.1:8000/loan_emi?principle_amount=5345&annual_rate=3&months=3" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Loan Emi", + "Principal amount borrowed": 5345, + "Annual Rate of interest": 3, + "Total number of monthly payments": 3, + "EMI": "1790.582", + "Total Amount Payble": "5371.747", + "Interest amount": "26.747" +} + +def test_asset_portfolio(): + response = client.get( + "http://127.0.0.1:8000/asset_portfolio?price_A=234&price_B=555&return_A=3232&return_B=4322&standard_dev_A=21&standard_dev_B=21&correlation=12" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Portfolio Variance", + "Expected Returns": "399873.0038022814%", + "Portfolio Variance": "2465.026081047868" +} +def test_put_call_parity(): + response = client.get( + "http://127.0.0.1:8000/put_call_parity?call_price=344&put_price=433&strike_price=221" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Pull Call Parity", + "Future Price": "132.0", + "Call Price": "344.0", + "Put Price": "433.0", + "Strike Price": "221.0" +} + +def test_dividend_payout_ratio(): + response = client.get( + "http://127.0.0.1:8000/dividend_payout_ratio?dividend_per_share=3535&earnings_per_share=533" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Dividend payout ratio", + "Dividend per share": 3535, + "Share price": 533, + "Dividend yield ratio": "6.0%" +} + +def test_bep(): + response = client.get( + "http://127.0.0.1:8000/bep?fixed_cost=434&selling_price=567&variable_cost=65" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Break Even Point (BEP)", + "Fixed costs": 434, + "Selling price per unit": 567, + "Variable cost per unit": 65, + "Break Even Point in units": "0.0", + "Break Even Point in Rupees": "490.0" +} + +def test_fcff(): + response = client.get( + "http://127.0.0.1:8000/fcff?sales=444&operating_cost=334&depreciation=44&interest=4&tax_rate=4&fcInv=2&wcInv=2" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Free Cash Flow to Firm (FCFF)", + "Earnings before interest, taxes, depreciation and amortization": "110.0", + "Earnings before interest and taxes : ": "66.0", + "Net Income": "59.52", + "Free Cash Flow to Firm": "103.36" +} + +def test_dividend_yield_ratio(): + response = client.get( + "http://127.0.0.1:8000/dividend_yield_ratio?dividend_per_share=456&share_price=443" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Dividend yield ratio", + "Dividend per share": 456, + "Share price": 443, + "Dividend yield ratio": "1.0%" +} + + +def test_debt_to_income_ratio(): + response = client.get( + "http://127.0.0.1:8000/debt_to_income_ratio?annual_income=455&total_debt_per_month=6" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Debt to income ratio", + "Annual income": 455, + "Total debt per month": 6, + "Debt to income ratio per month": "15.0%" +} + +def test_fixed_charges_coverage_ratio(): + response = client.get( + "http://127.0.0.1:8000/fixed_charges_coverage_ratio?earnings_before_interest_taxes=6446&fixed_charge_before_tax=444&interest=4" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "fixed charges coverage ratio", + "Earnings before interest taxes": 6446, + "Fixed charge before tax": 444, + "Interest": 4, + "Fixed charge coverage ratio": "15.0%" +} + +def test_inventory_shrinkage_rate(): + response = client.get( + "http://127.0.0.1:8000/inventory_shrinkage_rate?recorded_inventory=544&actual_inventory=434" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Inventory shrinkage rate", + "Recorded Inventory": 544, + "Actual Inventory": 434, + "Inventory Shrinkage Rate": 0.20220588235294118, + "Inventory Shrinkage Rate (%)": 20.22058823529412 +} + +def test_markup_percentage(): + response = client.get( + "http://127.0.0.1:8000/markup_percentage?price=455&cost=33" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Markup Percentage", + "Price": 455, + "Cost": 33, + "Markup Percentage": 1278.7878787878788 +} + +def test_purchasing_power(): + response = client.get( + "http://127.0.0.1:8000/purchasing_power?initial_amount=554&annual_inflation_rate=3&time=3" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Purchasing Power", + "Initial Amount": 554, + "Annual Inflation Rate": 3, + "Time in years": 3, + "Purchasing Power": "506.9884792816504" +} + + +def test_monthly_emi(): + response = client.get( + "http://127.0.0.1:8000/monthly_emi?loan_amt=466&interest_rate=6&number_of_installments=5" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Monthly EMI", + "Loan Amount": 466, + "Interest Rate": 6, + "Number of Installments": 5, + "Total EMI": "2796.166369153874" +} + +def test_doubling_time(): + response = client.get( + "http://127.0.0.1:8000/doubling_time?r=56" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Doubling Time", + "Rate of Interest": 56, + "Time in years to double the money": "1.5587346108623077" +} + +def test_capital_Asset_Pricing_Model(): + response = client.get( + "http://127.0.0.1:8000/capital_Asset_Pricing_Model?risk_free_interest_rate=4&beta_of_security=2&expected_market_return=44" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Capital Asset Pricing Model", + "Risk free interest rate": 4, + "Beta of security": 2, + "Expected market return": 44, + "Capital asset expected return": "84.0" +} + +def test_cost_of_equity(): + response = client.get( + "http://127.0.0.1:8000/cost_of_equity?risk_free_rate_of_return=455&Beta=4&market_rate_of_return=3" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Cost of Equity", + "Risk free rate of return": 455, + "Beta": 4, + "Market rate of return ": 3, + "Cost of equity": "-1353.0%" +} + +def test_cogs(): + response = client.get( + "http://127.0.0.1:8000/cogs?beginning_inventory=4566&purchases=5&ending_inventory=8755" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Cost of Goods Sold", + "Beginning Inventory": 4566, + "Purchases during the period": 5, + "Ending Inventory": 8755, + "Cost of Goods Sold(In Rupees)": "-4184.0" +} + +def test_ruleof72(): + response = client.get( + "http://127.0.0.1:8000/ruleof72?rate_of_roi=56" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Rule of 72", + "Rate of ROI": 56, + "Time period in which investment get double(in years)": "1.2857142857142858" +} + +def test_acid_test_ratio(): + response = client.get( + "http://127.0.0.1:8000/acid_test_ratio?cash=555&marketable_securities=43&accounts_receivable=32¤t_liabilities=34" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Acid Test Ratio", + "Cash and Cash Equivalents": 555, + "Marketable Securities": 43, + "Accounts Receivable": 32, + "Current Liabilities": 34, + "Acid Test Ratio (Quick Ratio)": "18.53" +} + +def test_cogr(): + response = client.get( + "http://127.0.0.1:8000/cogr?beginning_value=4445&ending_value=6785&years=4" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Compound Annual Growth Rate", + "Beginning Value": 4445, + "Ending Value": 6785, + "Compound Annual Growth Rate": "-10.0%" +} + +def test_current_liability_coverage_ratio(): + response = client.get( + "http://127.0.0.1:8000/current_liability_coverage_ratio?net_cash_from_operating_activities=4556&total_current_liabilities=55&number_of_liabilities=3" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "current liability coverage ratio", + "net cash from operating activities": 4556, + "total current liabilities": 55, + "number of liabilities": 3, + "current liability coverage ratio": "248.50909090909093" +} + +def test_levered_beta(): + response = client.get( + "http://127.0.0.1:8000/levered_beta?unlevered_beta=5587&tax_rate=4&debt=56&equity=33" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() =={ + "Tag": "Levered Beta", + "Unlevered Beta": 5587, + "Tax rate": 4, + "debt": 56, + "Equity": 33, + "Levered Beta": "-11174.0%" +} + +def test_monthly_payment(): + response = client.get( + "http://127.0.0.1:8000/monthly_payment?principal=5555&interest_rate=4&number_of_periods=4&payments_per_period=6" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "status_code": 500, + "detail": "Internal Server Error", + "headers": None +} +def test_current_ratio(): + response = client.get( + "http://127.0.0.1:8000/current_ratio?total_current_assets=455&total_liabilities=54" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Current Ratio", + "Total Current Assets": 455, + "Total Liabilities": 54, + "Current Ratio": "8.426" +} -def test_main(): - # Define test parameters - order_type = "buy" - symbol = "AAPL" - quantity = 10 +def test_inventory_turnover_ratio(): + response = client.get( + "http://127.0.0.1:8000/inventory_turnover_ratio?cost_of_goods_sold=4455&beginning_inventory=2233&ending_inventory=23345" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Inventory Turnover Ratio", + "Cost of Goods Sold": 4455, + "Inventory Turnover Ratio": "0.35" +} + +def test_herfindahl_Indexn_rate(): + response = client.get( + "http://127.0.0.1:8000/herfindahl_Index?Firms_market_shares=455" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Herfindahl Index", + "Firms market shares": "455", + "Herfindahl Index": "3025" +} + + +def test_discount_opex(): + response = client.get( + "http://127.0.0.1:8000/discount_opex?annual_opex=33&wacc=3&project_lifetime=2" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Discount OPEX", + "Annual OPEX": 33, + "WACC": 3, + "project lifetime": 2, + "Discount opex": "11.0%" +} - # Call the execute_market_order function - execute_market_order(order_type, symbol, quantity) -# Call the test_main function -test_main() +def test_project_efficiency(): + response = client.get( + "http://127.0.0.1:8000/project_efficiency?annual_production=335&collector_surface=33&dni=4" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Project efficiency", + "Annual production": 335, + "collector surface": 33, + "dni": 4, + "Discount opex": "2.0%" +} + +def test_real_gdp(): + response = client.get( + "http://127.0.0.1:8000/real_gdp?nominal_gdp=456&gdp_deflator=44" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Real GDP", + "Nominal GDP": 456, + "GDP Deflator": 44, + "Real GDP": 1036.3636363636363 +} + + +def test_excess_reserves(): + response = client.get( + "http://127.0.0.1:8000/excess_reserves?deposits=456&reserve_requirement=44" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Excess Reserves", + "Deposits": 456, + "Reserve Requirement": 44, + "Excess Reserves": -19608 +} + +def test_discounted_cash_flow(): + response = client.get( + "http://127.0.0.1:8000/discounted_cash_flow?real_feed_in_tariff=43&annual_production=533&wacc=4&project_lifetime=3" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Discounted cash flow", + "Real feed in teriff": 43, + "annual production": 533, + "wacc": 4, + "project lifetime": 3, + "discounted cash flow": "5729.0%" +} + +def test_gdp_growth_rate(): + response = client.get( + "http://127.0.0.1:8000/gdp_growth_rate?current_year_gdp=34&last_year_gdp=33" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "GDP Growth Rate", + "Current Year GDP": 34, + "Last Year GDP": 33, + "GDP Growth Rate": 3.0303030303030303 +} + +def test_credit_card_equation(): + response = client.get( + "http://127.0.0.1:8000/credit_card_equation?balance=2334&monthly_payment=33&daily_interest_rate=3" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Credit card equation", + "Balance": 2334, + "Monthly Payment": 33, + "daily interest rate": 3, + "credit card equation": "nan%" +} + +def test_future_value_of_ordinary_due(): + response = client.get( + "http://127.0.0.1:8000/future_value_of_ordinary_due?periodic_payment=455&number_of_periods=23&effective_interest_rate=23" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Future value of the ordinary annuity", + "Periodic payment": 455, + "Number of periods": "1.0993655407008683e+33", + "Effective interest rate": 23 +} + +def test_future_value_of_annuity_due(): + response = client.get( + "http://127.0.0.1:8000/future_value_of_annuity_due?periodic_payment=3455&number_of_periods=3&effective_interest_rate=2" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Future value of the ordinary annuity", + "Periodic payment": 3455, + "Number of periods": "134745.0", + "Effective interest rate": 2 +} + +def test_present_value_of_annuity_due(): + response = client.get( + "http://127.0.0.1:8000/present_value_of_annuity_due?periodic_payment=4566&number_of_periods=9&rate_per_period=6" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Present value of annuity due", + "Periodic payment": 4566, + "Number of periods": 9, + "Rate Per Period": 6, + "PV of Annuity Due": "5326.999867991974" +} + +def test_compound_annual_growth_rate(): + response = client.get( + "http://127.0.0.1:8000/compound_annual_growth_rate?ending_value=345&beginning_value=223&number_of_periods=3" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "compound annual growth rate 1", + "ending_value": 345, + "beginning value": 223, + "Number of periods": 3, + "compound annual growth rate": "0.0%" +} + +def test_loan_to_value(): + response = client.get( + "http://127.0.0.1:8000/loan_to_value?mortgage_value=444&appraised_value=334" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Loan to Value (LTV) ratio", + "Mortgage Value": 444, + "Appraised Property Value": 334, + "Loan to Value ratio": "132.93413173652695%" +} + +def test_retention_ratio(): + response = client.get( + "http://127.0.0.1:8000/retention_ratio?net_income=445÷nds=2" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Retention Ratio", + "Net Income": 445, + "Dividends": 2, + "Retention Ratio": 0.9955056179775281 +} + +def test_tax_equivalent_yield(): + response = client.get( + "http://127.0.0.1:8000/tax_equivalent_yield?tax_free_yield=55663&tax_rate=3" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Tax Equivalent Yield", + "Tax Free Yield": 55663, + "Tax Rate": 3, + "Tax Equivalent Yield": -27831.5 +} + +def test_perpetuity_payment(): + response = client.get( + "http://127.0.0.1:8000/perpetuity_payment?present_value=34&rate=2" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Perpetuity Payment", + "Present Value": 34, + "Perpetuity Payment": "0.68" +} + +def test_year_to_year(): + response = client.get( + "http://127.0.0.1:8000/year_to_year?later_period_value=455&earlier_period_value=332" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Year to Year Growth", + "Year to Year growth": "37.04819277108434%" +} + +def test_future_value_of_annuity(): + response = client.get( + "http://127.0.0.1:8000/future_value_of_annuity?payments_per_period=345&interest_rate=44&number_of_periods=4 " + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Future value of annuity", + "Payments per periods": 345, + "interest rate": 44, + "number of periods": 4, + "future value of annuity": "32152620.0%" +} + +def test_yield_to_maturity(): + response = client.get( + "http://127.0.0.1:8000/yield_to_maturity?bond_price=345&face_value=2233&coupon_rate=2&years_to_maturity=4" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Yield To Maturity", + "Face Value": 2233, + "Years to maturity": 4, + "Yield to Maturity": "40.08%" +} + +def test_balloon_balance(): + response = client.get( + "http://127.0.0.1:8000/balloon_balance?present_value=4553&payment=3344&rate_per_payment=32&number_of_payments=3" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Balloon Balance of a Loan", + "Present Value (Original Balance)": 4553, + "Payment": 3344, + "Rate per Payment": 32, + "Number of Payments": 3, + "Future Value (Balloon Balance)": 159865849 +} + +def test_periodic_lease_payment(): + response = client.get( + "http://127.0.0.1:8000/periodic_lease_payment?Asset_value=3554&monthly_lease_interest_rate=3&number_of_lease_payments=2" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Periodic Lease Payment", + "Asset value": 3554, + "Monthly lease interest rate": 3, + "Number of lease payments": 2, + "Periodic Lease Payment": "11372.8" +} +def test_zero_coupon_bond_value(): + response = client.get( + "http://127.0.0.1:8000/zero_coupon_bond_value?face_value=4456&rate_of_yield=3&time_of_maturity=4" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Zero Coupon Bond Value", + "Face Value": 4456, + "Rate of yield": "3.0%", + "Zero Coupon Bond Value": 3959.1 +} + + +def test_zero_coupon_bond_yield(): + response = client.get( + "http://127.0.0.1:8000/zero_coupon_bond_yield?face_value=444&present_value=3333&time_of_maturity=4" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Zero Coupon Bond Effective Yield", + "Face Value": 444, + "Present Value": 3333, + "Time to maturity": 4, + "Zero Coupon Bond Effective Yield": "-39.6%" +} + + +def test_profitability_index(): + response = client.get( + "http://127.0.0.1:8000/profitability_index?initial_investment=3445&pv_of_future_cash_flows=33" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Profitability Index", + "Initial Investment": 3445, + "PV of Future Cash Flows": 33, + "Profitability Index": 0.009579100145137881 +} + + +def test_receivables_turnover_ratio(): + response = client.get( + "http://127.0.0.1:8000/receivables_turnover_ratio?sales_revenue=4656&avg_accounts_receivable=33" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Receivables Turnover Ratio", + "Sales Revenue": 4656, + "Avg Accounts Receivables": 33, + "Receivables Turnover Ratio": 141.0909090909091 +} + + +def test_remaining_balance(): + response = client.get( + "http://127.0.0.1:8000/remaining_balance?regular_payment=456&interest_rate_per_period=3&number_of_payments=23&number_of_payments_done=21" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Remaining balance", + "regular_payment": 456, + "interest rate per period": 3, + "number of payments": 23, + "number of payments done": 21, + "remaining balance": 0 +} + + +def test_net_present_value(): + response = client.get( + "http://127.0.0.1:8000/net_present_value?cash_flows=5445&discount_rate=44&initial_investment=555" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Net present value", + "cash flows": "5445", + "discount rate": 44, + "initial investment": 555, + "Net present value": 3226.25 +} + +def test_leverage_ratio_income(): + response = client.get( + "http://127.0.0.1:8000/leverage_ratio_income?debt_payments=456&income=32" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Leverage Ratio By Income", + "Debt ": 456, + "Income": 32, + "Leverage Ratio": "14.25" +} + + +def test_leverage_ratio_equity(): + response = client.get( + "http://127.0.0.1:8000/leverage_ratio_equity?debt_payments=334&equity=3" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Leverage Ratio By Equity", + "Debt ": 334, + "Equity": 3, + "Leverage Ratio": "111.33333333333333" +} + + +def test_time_period_required_for_growth(): + response = client.get( + "http://127.0.0.1:8000/time_period_required_for_growth?interest_rate=12&growth_factor=33" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Time period required for exponential growth", + "interest rate": 12, + "growth factor": 33 +} + + +def test_preferred_stock_value(): + response = client.get( + "http://127.0.0.1:8000/preferred-stock-value?dividend=64&discount_rate=24" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Preferred stock value", + "Dividend": 64, + "Discount Rate": 24, + "Preferred Stock Value": 2.6666666666666665 +} + + +def test_asset_turnover_ratio(): + response = client.get( + "http://127.0.0.1:8000/asset_turnover_ratio?net_sales=4556&total_asset_beginning=343&total_asset_ending=234" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Asset Turnover Ratio", + "Net Sales": 4556, + "Total beginning asset": 343, + "Total ending asset": 234, + "Total average asset": 288.5, + "Asset Turnover Ratio": "15.792027729636049" +} + + +def test_bid_ask_spread(): + response = client.get( + "http://127.0.0.1:8000/bid-ask-spread?ask_price=445&bid_price=1234" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Bid Ask Spread", + "Ask Price": 445, + "Bid Price": 1234, + "Bid Ask Spread": -789 +} + + +def test_calculate_period_FV_PV_rate(): + response = client.get( + "http://127.0.0.1:8000/calculate-period-FV-PV-rate?present_val=4255&future_val=6345&rate=4" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Period in years ", + "Present Value": 4255, + "Future Value": 6345, + "Periods": 10.187788722235 +} + + +def test_Balloon_loan_payment(): + response = client.get( + "http://127.0.0.1:8000/balloon-loan-payment?principal=345&interest_rate=2&term_years=1&balloon_payment_year=3" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Balloon Loan Payment", + "Principal": 345, + "Interest Rate": 2, + "Term Years": 1, + "Balloon Payment Year": 3, + "Balloon Loan Payment": -711.0313639642766 +} + + +def test_monthly_lease_payment(): + response = client.get( + "http://127.0.0.1:8000/monthly_lease_payment?Asset_value=424&monthly_lease_interest_rate=4&number_of_lease_payments=4" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Monthly Lease Payment", + "Asset value": 424, + "Monthly lease interest rate": 4, + "Number of lease payments": 4, + "Monthly Lease Payment": "424.6794871794872" +} + + +def test_401k(): + response = client.get( + "http://127.0.0.1:8000/401k?income=4563&contribution_percentage=23¤t_age=23&age_at_retirement=36&rate_of_return=3&salary_increase_rate=2&withdraw_tax_rate=3" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Estimated 401(k)", + "income": 4563, + "contribution_percentage": 23, + "current_age": 23, + "age_at_retirement": 36, + "rate_of_return": 3, + "withdraw_tax_rate": 3, + "estimated_401k": 18909.175, + "annual_withdraw_amount": 567.275 +} + + +def test_roth_ira(): + response = client.get( + "http://127.0.0.1:8000/roth-ira?principal=4355&interest_rate=3&years=3&tax_rate=2&annual_contribution=32" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Roth-IRA", + "Principal": 4355, + "Interest Rate": 3, + "Years": 3, + "Tax Rates": 2, + "Annual Contributions": 32, + "Roth Ira Balance": 4861, + "Taxable saving Balance": 4853 +} + + +def test_mortgage_amortization(): + response = client.get( + "http://127.0.0.1:8000/mortgage-amortization?mortgage_amount=4556&mortgage_deposit=3232&annual_interest_rate=4&loan_term=5" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "TAG": "Mortgage monthly payments", + "mortgage_amount": 4556, + "mortgage_deposit": 3232, + "annual_interest_rate": 4, + "loan_term": 5, + "monthly_payment": -2671.077, + "annual_payment": -32052.923 +} + + +def test_enterprise_value(): + response = client.get( + "http://127.0.0.1:8000/enterprise-value?share_price=345&fully_diluted_shares_outstanding=33&total_debt=43&preferred_stock=3&non_controlling_interest=2&cash_and_cash_equivalents=43" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Enterprise Value", + "Equity Value": 11385, + "Total Debt": 43, + "Preferred Stock": 3, + "Non-Controlling Interest": 2, + "Cash & Cash Equivalents": 43, + "Enterprise Value": 11390 +} + + +def test_refinance_calculator(): + response = client.get( + "http://127.0.0.1:8000/refinance?current_loan_amount=4453¤t_interest_rate=3¤t_loan_term_years=3&time_remaining_years=2&new_interest_rate=2&new_loan_term_years=6&cash_out_amount=2" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Refinance", + "Current loan amount": 4453, + "Balance left on loan": 3012.91, + "New loan amount": 3010.91, + "Current monthly payment": 129.5, + "New monthly payment": 44.41, + "Monthly savings": 85.09, + "Current interest paid left": 95.05, + "New total interest paid": 186.77, + "Total interest saving": -91.72, + "Current total cost left": 3107.97, + "New total cost loan": 3197.68, + "Total cost saving": -89.72 +} + + +def test_salary_calculate(): + response = client.get( + "http://127.0.0.1:8000/salary-calculate?salary_amount=3554&payment_frequency=3&hours_worked_per_day=2&days_worked_per_week=3" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Calculate Salary", + "Salary Amount": 3554, + "Payment frequency": "3", + "Salary": { + "error": "Invalid payment frequency." + } +} + + +def test_commission_calc(): + response = client.get( + "http://127.0.0.1:8000/commission_calc?sales_price=3555&commission_rate=3&commission=224" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "status_code": 500, + "detail": "Internal Server Error", + "headers": None +} + + +def test_college_cost(): + response = client.get( + "http://127.0.0.1:8000/college_cost?book_cost=4566&college_tuition=34&Devices=33&travel_expenses=44&hostel_charges=55&mess_fee=33&miscellaneous=45" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "College Cost", + "Books cost of one year": 4566, + "College tuition fee per year": 34, + "Electronic devices cost": 33, + "Monthly Travel expenses": 44, + "Monthly Hostel charges": 55, + "Monthly mess fee": 33, + "monthly miscellaneous expenses": 45, + "Total cost of one year": 6757 +} + + +def test_diluted_earnings_per_share(): + response = client.get( + "http://127.0.0.1:8000/diluted-earnings-per-share?net_income=4455&weighted_avg_shares=23&dilutive_securities=22" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Diluted Earnings Per Share (EPS)", + "Net Income": 4455, + "Weighted Average Shares Outstanding": 23, + "Number of Dilutive Securities": 22, + "Diluted EPS": "99.0" +} + + +def test_roi_equity_funds(): + response = client.get( + "http://127.0.0.1:8000/roi_equity_funds?amount_invested=4563&amount_returned=32&tenure=3" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Calculate return of investments on equity funds", + "Amount Invested": 4563, + "Amount Returned": 32, + "Duration of investment": 3, + "Return of Investment": "-99.29870699101468%", + "Annualized Return": "0.23321999781458214%" +} + + +def test_student_loan(): + response = client.get( + "http://127.0.0.1:8000/student_loan?principal=5663&tenure=33&interest_rate=3" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Student Loan", + "Total amount to borrow": 5663, + "total number of years to pay loan": 33, + "interest rate percentage annual": 3, + "total monthly cost": "22", + "Total Amount of loan": "8927" +} + + +def test_calculate_gst(): + response = client.get( + "http://127.0.0.1:8000/calculate_gst?price=545&gst_rate=5" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "status_code": 500, + "detail": "Internal Server Error", + "headers": None +} + + +def test_calculate_retirement_goals(): + response = client.get( + "http://127.0.0.1:8000/calculate_retirement_goals?retirement_age=34&annual_retirement_expenses=344&inflation_rate=5&annual_retirement_income=45567¤t_age=5" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Retirement Goals", + "Retirement age": 34, + "Annual retirement expenses": 344, + "inflation rate": 5, + "Annual Retirement Income": 45567, + "Current Age": 5, + "Retirement Goals": "-1.666270978588454e+27" +} + + +def test_calculate_market_cap(): + response = client.get( + "http://127.0.0.1:8000/calculate_market_cap?current_market_share_price=5545&total_number_of_shares_outstanding=434" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Market capitalization value", + "Current market share price": 5545, + "Total number of shares outstanding": 434, + "Marketcap value": "2406530" +} + + +def test_annual_debt_service_coverage_ratio(): + response = client.get( + "http://127.0.0.1:8000/asdcr?net_operating_cost=322&depreciation=3&non_cash_expenses=33&annual_debt_service=4" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Annual Debt Service Coverage Ratio", + "Annual Debt Ratio": 89.5, + "Net Operating Income": 322, + "Depreciation": 3, + "Non Cash Expenses": 33, + "Annual Debt": 4 +} + + +def test_calculate_vat(): + response = client.get( + "http://127.0.0.1:8000/calculate_vat?price=4343&vat_rate=5" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Price (excluding VAT)": 4136.190476190476, + "Price (including VAT)": 4343, + "VAT Amount": 206.80952380952385 +} + + +def test_bond_equivalent_yield(): + response = client.get( + "http://127.0.0.1:8000/bond_equivalent_yield?face_value=5353&purchase_price=5&days_to_maturity=5" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Bond Equivalent Yield", + "Face value": 5353, + "Purchase Price": 5, + "Days to maturity": 5, + "Bond Equivalent Yield (BEY)": "7808079.999999999%" +} + + +def test_calculate_gratuity(): + response = client.get( + "http://127.0.0.1:8000/calculate_gratuity?last_salary=3535&tenure_years=5&tenure_months=4" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Gratuity", + "Last salary (basic + dearness allowance)": 3535, + "Tenure in years (excluding last partial year)": 5, + "Last partial year in months": 4, + "Gratuity Amount": "10197" +} + + +def test_mortrage(): + response = client.get( + "http://127.0.0.1:8000/mortrages?princial=4344&interest_rate=4&years=4&down_payment=223&property_tax_rate=2&insurance_rate=2" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Monthly Payment": 93.04828417840245, + "Total Payment": 4466.317640563318, + "Total Property Tax": 347.52, + "Total insurance cost": 347.52, + "Total Cost": 5161.357640563318, + "Loan to value ratio": 94.86648250460405 +} + + +def test_post_tax_return_percentage(): + response = client.get( + "http://127.0.0.1:8000/calculate_post_tax_return_percentage?tax_rate_percentage=3537&annual_net_income=2244&initial_cost_of_investment=444" ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Calculate post tax return percentage", + "Tax Rate Percentage": 3537, + "Annual net income": 2244, + "Initial cost of investment": 444, + "Post tax return percentage": -17370.783783783783 +} + + +def test_loan_to_value_ratio(): + response = client.get( + "http://127.0.0.1:8000/loan_to_value_ratio?loan_amount=5464&value_of_collateral=6" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "Tag": "Loan to Value Ratio", + "Loan Amount": 5464, + "Value Of Collateral": 6, + "Loan to Value Ratio": "91066.66666666666%" +} + From d52abe49dacb2b4dd276c589b7ae8f8eee9e1895 Mon Sep 17 00:00:00 2001 From: Robera Negussie <47657043+roberanegussie@users.noreply.github.com> Date: Tue, 20 Jun 2023 19:51:09 +0300 Subject: [PATCH 11/66] Endpoint for Capital Gains Yield Added the function to calculate Capital Gains Yield. --- ENDPOINTS.md | 14 ++++++++++++++ helpers/functions.py | 14 ++++++++++++++ main.py | 20 ++++++++++++++++++++ 3 files changed, 48 insertions(+) diff --git a/ENDPOINTS.md b/ENDPOINTS.md index d4272495..6184f231 100644 --- a/ENDPOINTS.md +++ b/ENDPOINTS.md @@ -1910,4 +1910,18 @@ Sample Output "Net Borrowing": 350000.0, "Free Cash Flow to Equity": 620000.0 } +``` + +**GET** `/capital_gains_yield` + +- Required parameters : `inital_price`, `price_after_first_period` +- Sample output + +```py +{ + "Tag": "Capital Gains Yield", + "Inital Price of Stock": 200.0, + "Price of Stock After First Period": 220.0, + "Capital Gains Yield": 10%, +} ``` \ No newline at end of file diff --git a/helpers/functions.py b/helpers/functions.py index 031b83c8..c97388e5 100644 --- a/helpers/functions.py +++ b/helpers/functions.py @@ -1879,3 +1879,17 @@ def free_cash_flow_to_equity( fcfe = net_income + depreciation_and_amortization - \ capEx - change_in_working_capital + net_borrowing return fcfe + +#Function to Calculate Capital Gains Yield + +def capital_gains_yield( + inital_price : float, + price_after_first_period : float): + ''' + Capital Gains Yield used to calculate a company's total stock return + if a company does not pay dividends. + inital_price indicates Inital Stock Price, + price_after_first_period indicates Stock Price after first period + ''' + gains_yield = ((price_after_first_period - inital_price) / inital_price) * 100 + return gains_yield diff --git a/main.py b/main.py index 6ff7efed..07cca5a0 100644 --- a/main.py +++ b/main.py @@ -3106,3 +3106,23 @@ def free_cash_flow_to_equity( } except: return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + + +## Endpoint for function Capital Gains Yield + +app.get( + "/capital_gains_yield", + tags=["capital_gains_yield"], + description="Calculate Capital Gains Yield of a Stock", +) +def capital_gains_yield(inital_price: float, price_after_first_period: float): + try: + gains_yield = functions.capital_gains_yield(inital_price, price_after_first_period) + return { + "Tag": "Capital Gains Yield", + "Inital Price of Stock": inital_price, + "Price of Stock After First Period": price_after_first_period, + "Capital Gains Yield": f"{gains_yield}%", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file From bf8be29588ddca7d1e4379640d611bd1b5ec5096 Mon Sep 17 00:00:00 2001 From: alwen1928 Date: Tue, 20 Jun 2023 23:40:33 +0530 Subject: [PATCH 12/66] Added an endpoint for networth calculation --- main.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/main.py b/main.py index 6ff7efed..16a6d626 100644 --- a/main.py +++ b/main.py @@ -3106,3 +3106,20 @@ def free_cash_flow_to_equity( } except: return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) +@app.get( + "/net_worth", + tags=["net_worth"], + description="Calculate net worth", +) +def net_worth_calculation(assets: float, liabilities: float, loans: float, mortgages: float): + try: + total_liabilities = liabilities + loans + mortgages + net_worth = assets - total_liabilities + return { + "Tag": "Net Worth", + "Assets": assets, + "Liabilities": total_liabilities, + "Net Worth": net_worth, + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) From 7f230643a765130aaecbd6981fbe44019704453a Mon Sep 17 00:00:00 2001 From: alwen1928 Date: Tue, 20 Jun 2023 23:52:28 +0530 Subject: [PATCH 13/66] net_worth endpoint updated in ENDPOINT.md --- ENDPOINTS.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/ENDPOINTS.md b/ENDPOINTS.md index d4272495..2255521a 100644 --- a/ENDPOINTS.md +++ b/ENDPOINTS.md @@ -1910,4 +1910,21 @@ Sample Output "Net Borrowing": 350000.0, "Free Cash Flow to Equity": 620000.0 } +``` + + +**GET** `/net_worth` + +- Required parameters : `assets`, `liabilities`,'loans','mortgage' +- Sample output + +```py +{ + "Tag": "Net Worth", + "Assets": 100000.0, + "Liabilities": 50000.0, + "Loans": 20000.0, + "Mortgage": 10000.0, + "Net Worth": 50000.0 +} ``` \ No newline at end of file From 60fe1d6c2dc2ccf6924a3349cd83fe85cb979779 Mon Sep 17 00:00:00 2001 From: alwen1928 Date: Wed, 21 Jun 2023 20:06:38 +0530 Subject: [PATCH 14/66] net worth function added in helpers/functions.py --- helpers/functions.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/helpers/functions.py b/helpers/functions.py index 515a03a7..399e7357 100644 --- a/helpers/functions.py +++ b/helpers/functions.py @@ -1934,3 +1934,15 @@ def calculate_financial_leverage(total_assets : float, financial_leverage = debt / shareholder_equity return financial_leverage + +#Function to calculate net worth +def net_worth_calculation(assets: float, liabilities: float, loans: float, mortgages: float): + + total_liabilities = liabilities + loans + mortgages + net_worth = assets - total_liabilities + return { + "Tag": "Net Worth", + "Assets": assets, + "Liabilities": total_liabilities, + "Net Worth": net_worth, + } \ No newline at end of file From b7daed5b768603db5258700d23b8bf0e8d2a10e2 Mon Sep 17 00:00:00 2001 From: Subho Ghosh <93722719+ighoshsubho@users.noreply.github.com> Date: Wed, 21 Jun 2023 21:16:46 +0530 Subject: [PATCH 15/66] Delete .hypothesis/unicode_data/13.0.0 directory --- .hypothesis/unicode_data/13.0.0/charmap.json.gz | Bin 20988 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 .hypothesis/unicode_data/13.0.0/charmap.json.gz diff --git a/.hypothesis/unicode_data/13.0.0/charmap.json.gz b/.hypothesis/unicode_data/13.0.0/charmap.json.gz deleted file mode 100644 index 30309b5be700c1ea9dda4f6456cf1c1f32beb6fc..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 20988 zcmbUIV{|25`0fkGcGBtCM#r|@vDvZFvD2|_t=P7$PC7PMY?~`5&))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qkf!3VkPYKF=egm6 zZaBHYHr$NE+6X26xpbx0T%iL6+0=y)pYu6*!4k@FY!+ z@PO;&l0C2J%VCVT+6RD7LD|0_aJycQcT87_l(E}`yDxoW*gVM#+A)lyf5Hm3H}0=4 zDd*ew0PstYco*{!|7?F@)!GYvk`GY2R7i6@gKx^s-gduZNK|)Q zU$aVvx_Ws{3&hjLafy)pG(m*l_|z1Vb~qLPqb3a}EM#nzB=P@BO&ob%36rDJB%kM| zqkDKhgYPslt30efY5b?BS*<)G&O0X1s2l`NN{{gF2*P~2fig$MR*uQ2Yme9S+_`7+ zS)5lS^9cBS?5yj85Z=~_7+l=Yx*!Y7z~0srcxUVEVW-%km#{n{vVUP7}@RP008@@#a;ja From a33fc7f469f7d4a8d9f27c6987d0467bfc6990d5 Mon Sep 17 00:00:00 2001 From: Robera Negussie <47657043+roberanegussie@users.noreply.github.com> Date: Wed, 21 Jun 2023 22:12:25 +0300 Subject: [PATCH 16/66] Endpoint for Capitalization Rate I have added endpoint for calculating the Capitalization Rate for a property. I have added additional parameters based on your feedback such as rental_income, amenities, propertyManagement, propertyTaxes and insurance. --- ENDPOINTS.md | 21 +++++++++++++++++++++ helpers/functions.py | 15 +++++++++++++++ main.py | 38 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 74 insertions(+) diff --git a/ENDPOINTS.md b/ENDPOINTS.md index b4cd0515..e947ae1a 100644 --- a/ENDPOINTS.md +++ b/ENDPOINTS.md @@ -1967,3 +1967,24 @@ Sample Output } ``` + +**GET** `/capitalization_rate` + +-Required parameters: `rental_income`, `amenities`, `propertyManagement`, `propertyTaxes`, `insurance`, `current_market_value` +-Sample Output + +```py +{ + "Tag": "Capitalization Rate", + "Rental Income": 70000.0, + "Amenities": 30000.0, + "Property Management": 2000.0, + "Property Taxes": 3000.0, + "Insurance": 2500.0, + "Annual Income": 100000.0, + "Expenses": 7500.0, + "Net Operating Income": 92500.0, + "Current Market Value": 1500000.0 + "Capitalization Rate": 6.16% +} +``` diff --git a/helpers/functions.py b/helpers/functions.py index 515a03a7..768fd0f8 100644 --- a/helpers/functions.py +++ b/helpers/functions.py @@ -1934,3 +1934,18 @@ def calculate_financial_leverage(total_assets : float, financial_leverage = debt / shareholder_equity return financial_leverage + +# Function to Calculate Capitalization Rate + +def capitalization_rate( + rental_income: float, + amenities: float, + propertyManagement: float, + propertyTaxes:float, + insurance: float, + current_market_value: float): + annual_income = rental_income + amenities + expenses = propertyManagement + propertyTaxes + insurance + net_operating_income = annual_income - expenses + rate = (net_operating_income / current_market_value) * 100 + return rate diff --git a/main.py b/main.py index eec383ba..570e8627 100644 --- a/main.py +++ b/main.py @@ -3181,3 +3181,41 @@ def calculate_financial_leverage(total_assets : float, } except: return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + +#Endpoint for function Capitalization Rate + +@app.get( + "/capitalization_rate", + tags=["capitalization_rate"], + description="Calculate capitalization rate for a given property.", +) +def capitalization_rate( + rental_income: float, + amenities: float, + propertyManagement: float, + propertyTaxes:float, + insurance: float, + current_market_value: float): + try: + rate = functions.capitalization_rate(rental_income, amenities, propertyManagement, + propertyTaxes, insurance, current_market_value + ) + annual_income = rental_income + amenities, + expenses = propertyManagement + propertyTaxes + insurance, + net_operating_income = annual_income - expenses, + + return { + "Tag": "Capitalization Rate", + "Rental Income": rental_income, + "Amenities": amenities, + "Property Management": propertyManagement, + "Property Taxes": propertyTaxes, + "Insurance": insurance, + "Annual Income": annual_income, + "Expenses": expenses, + "Net Operating Income": net_operating_income, + "Current Market Value": current_market_value, + "Capitalization Rate": f"{rate}%" + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) From 70d8b0bd28c85d5c0d9212e509f4b50123308418 Mon Sep 17 00:00:00 2001 From: Vaibhav Sangwan Date: Thu, 22 Jun 2023 13:23:44 +0530 Subject: [PATCH 17/66] Add endpoint: Accounts Payable Turnover Ratio --- ENDPOINTS.md | 14 ++++++++++++++ helpers/functions.py | 10 ++++++++++ main.py | 22 ++++++++++++++++++++++ 3 files changed, 46 insertions(+) diff --git a/ENDPOINTS.md b/ENDPOINTS.md index b4cd0515..7120bcb9 100644 --- a/ENDPOINTS.md +++ b/ENDPOINTS.md @@ -1967,3 +1967,17 @@ Sample Output } ``` + +**GET** `/accounts_payable_turnover_ratio` + +- Required parameters : `total_supply_purchases`, `beginning_accounts_payable` and `ending_accounts_payable` +- Sample output + +```py +{ + "Tag": "Accounts Payable Turnover Ratio", + "Total Supply Purchases": 1000, + "Beginning Accounts Payable": 200, + "Ending Accounts Payable": 300, + "Accounts Payable Turnover Ratio": 4 +} \ No newline at end of file diff --git a/helpers/functions.py b/helpers/functions.py index 515a03a7..c263c2b0 100644 --- a/helpers/functions.py +++ b/helpers/functions.py @@ -1934,3 +1934,13 @@ def calculate_financial_leverage(total_assets : float, financial_leverage = debt / shareholder_equity return financial_leverage + +# Function to calculate Accounts Payable Turnover Ratio +def accounts_payable_turnover_ratio(total_supply_purchases: float, + beginning_accounts_payable: float, + ending_accounts_payable: float): + + average_accounts_payable = (beginning_accounts_payable + ending_accounts_payable)/2 + ap_turnover_ratio = total_supply_purchases/average_accounts_payable + + return ap_turnover_ratio \ No newline at end of file diff --git a/main.py b/main.py index eec383ba..1381b1f1 100644 --- a/main.py +++ b/main.py @@ -3181,3 +3181,25 @@ def calculate_financial_leverage(total_assets : float, } except: return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + +@app.get( + "/accounts_payable_turnover_ratio", + tags=["accounts_payable_turnover_ratio"], + description="Calculates the Accounts Payable Turnover Ratio", +) +def accounts_payable_turnover_ratio(total_supply_purchases: float, + beginning_accounts_payable: float, + ending_accounts_payable: float): + try: + ap_turnover_ratio = functions.accounts_payable_turnover_ratio(total_supply_purchases, + beginning_accounts_payable, + ending_accounts_payable) + return { + "Tag": "Accounts Payable Turnover Ratio", + "Total Supply Purchases": total_supply_purchases, + "Beginning Accounts Payable": beginning_accounts_payable, + "Ending Accounts Payable": ending_accounts_payable, + "Accounts Payable Turnover Ratio": ap_turnover_ratio + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file From 19974346f62fbbdcdf08819c464ef93ea5d421a5 Mon Sep 17 00:00:00 2001 From: Divyanshi Date: Thu, 22 Jun 2023 13:32:32 +0530 Subject: [PATCH 18/66] Added dependabot.yml file --- .github/dependabot.yml | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 .github/dependabot.yml diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 00000000..24ddada6 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,6 @@ +version: 2 +updates: + - package-ecosystem: 'npm' + directory: '/' + schedule: + interval: 'daily' \ No newline at end of file From 057c1dfe443af02ec2b9cc9218d03b51682728a4 Mon Sep 17 00:00:00 2001 From: Anantashayana Date: Fri, 23 Jun 2023 12:45:52 +0530 Subject: [PATCH 19/66] Added monte carlo functionality on portfolio --- ENDPOINTS.md | 29 +++++++++++++++++++++++++++++ helpers/functions.py | 26 ++++++++++++++++++++++++++ main.py | 25 +++++++++++++++++++++++++ 3 files changed, 80 insertions(+) diff --git a/ENDPOINTS.md b/ENDPOINTS.md index b4cd0515..6b9bd3aa 100644 --- a/ENDPOINTS.md +++ b/ENDPOINTS.md @@ -1967,3 +1967,32 @@ Sample Output } ``` + +**GET** `/portfolio_return_monte_carlo` +-Required parameters: `principal`, `expected_return_range_start`,`expected_return_range_end`, `volatility_range_start`,`volatility_range_end`, `num_simulations` +-Sample Output +```py +{ + 'Tag': 'Portfolio Return Monte Carlo', + 'Principal': 100000.0, + 'Number of Simulations': 100.0, + 'Portfolio Returns': { + 'Portfolio Returns': [ + 0.1508024611892416, + 0.09317653795670179, + 0.5116882858279181, + .................. + -0.129317612028336, + 0.3255694082529636, + 0.11115286872158307 + ], + 'Average Return': 0.08973870952953042, + 'Standard Deviation': 0.15306996560080827, + 'Min Return': -0.3923187345080281, + 'Max Return': 0.5116882858279181, + 'Positive Returns': 75, + 'Negative Returns': 25 + } +} + +``` \ No newline at end of file diff --git a/helpers/functions.py b/helpers/functions.py index 515a03a7..03327690 100644 --- a/helpers/functions.py +++ b/helpers/functions.py @@ -1934,3 +1934,29 @@ def calculate_financial_leverage(total_assets : float, financial_leverage = debt / shareholder_equity return financial_leverage + +# Function to estimate the portfolio return using Monte Carlo simulation. +def portfolio_return_monte_carlo(principal, expected_return_range_start,expected_return_range_end, volatility_range_start,volatility_range_end, num_simulations): + portfolio_returns = np.zeros(int(num_simulations)) + + min_return, max_return = expected_return_range_start, expected_return_range_end + min_volatility, max_volatility = volatility_range_start, volatility_range_end + + for i in range(int(num_simulations)): + random_return = np.random.uniform(min_return, max_return) + random_volatility = np.random.uniform(min_volatility, max_volatility) + random_returns = np.random.normal(random_return, random_volatility) + portfolio_value = principal * np.prod(1 + random_returns) + portfolio_returns[i] = (portfolio_value - principal) / principal + + portfolio_stats = { + "Portfolio Returns": portfolio_returns.tolist(), + "Average Return": np.mean(portfolio_returns), + "Standard Deviation": np.std(portfolio_returns), + "Min Return": np.min(portfolio_returns), + "Max Return": np.max(portfolio_returns), + "Positive Returns": len(portfolio_returns[portfolio_returns > 0]), + "Negative Returns": len(portfolio_returns[portfolio_returns < 0]) + } + + return portfolio_stats \ No newline at end of file diff --git a/main.py b/main.py index eec383ba..0930d1ce 100644 --- a/main.py +++ b/main.py @@ -130,6 +130,8 @@ def index(): "/college_cost": "calculate total college fee of one year assuming full tuition fee is being paid.", "/diluted-earnings-per-share": "Calculate Diluted Earnings Per Share (EPS).", "/asdcr": "Calculate Annual Debt Service Coverage Ratio", + "/portfolio_return_monte_carlo":"Calculates Portfolio returns based on Monte Carlo Simulation", + }, } @@ -3181,3 +3183,26 @@ def calculate_financial_leverage(total_assets : float, } except: return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + +@app.get( + "/portfolio_return_monte_carlo", + tags=["portfolio_return"], + description="Estimate portfolio return using Monte Carlo simulation" +) +def portfolio_return_monte_carlo(principal: float, + expected_return_range_start: float, + expected_return_range_end: float, + volatility_range_start: float, + volatility_range_end: float, + num_simulations: float): + try: + portfolio_returns = functions.portfolio_return_monte_carlo(principal, expected_return_range_start,expected_return_range_end, volatility_range_start,volatility_range_end, num_simulations) + + return { + "Tag": "Portfolio Return Monte Carlo", + "Principal": principal, + "Number of Simulations": num_simulations, + "Portfolio Returns": f"{portfolio_returns}%", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file From 563f1e29f06b009c826ad6e6bc3a383885f5d2d2 Mon Sep 17 00:00:00 2001 From: Harmeet Singh <130365071+harmeetsingh11@users.noreply.github.com> Date: Fri, 23 Jun 2023 12:51:59 +0000 Subject: [PATCH 20/66] feat: add codeql workflow --- .github/workflows/codeql.yml | 77 ++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 .github/workflows/codeql.yml diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 00000000..7611fe96 --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,77 @@ +# For most projects, this workflow file will not need changing; you simply need +# to commit it to your repository. +# +# You may wish to alter this file to override the set of languages analyzed, +# or to provide custom queries or build logic. +# +# ******** NOTE ******** +# We have attempted to detect the languages in your repository. Please check +# the `language` matrix defined below to confirm you have the correct set of +# supported CodeQL languages. +# +name: "CodeQL" + +on: + push: + branches: [ "main" ] + pull_request: + # The branches below must be a subset of the branches above + branches: [ "main" ] + schedule: + - cron: '43 3 * * 6' + +jobs: + analyze: + name: Analyze + runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }} + timeout-minutes: ${{ (matrix.language == 'swift' && 120) || 360 }} + permissions: + actions: read + contents: read + security-events: write + + strategy: + fail-fast: false + matrix: + language: [ 'python' ] + # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby', 'swift' ] + # Use only 'java' to analyze code written in Java, Kotlin or both + # Use only 'javascript' to analyze code written in JavaScript, TypeScript or both + # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support + + steps: + - name: Checkout repository + uses: actions/checkout@v3 + + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@v2 + with: + languages: ${{ matrix.language }} + # If you wish to specify custom queries, you can do so here or in a config file. + # By default, queries listed here will override any specified in a config file. + # Prefix the list here with "+" to use these queries and those in the config file. + + # For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs + # queries: security-extended,security-and-quality + + + # Autobuild attempts to build any compiled languages (C/C++, C#, Go, Java, or Swift). + # If this step fails, then you should remove it and run the build manually (see below) + - name: Autobuild + uses: github/codeql-action/autobuild@v2 + + # ℹ️ Command-line programs to run using the OS shell. + # πŸ“š See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun + + # If the Autobuild fails above, remove it and uncomment the following three lines. + # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. + + # - run: | + # echo "Run, Build Application using script" + # ./location_of_script_within_repo/buildscript.sh + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v2 + with: + category: "/language:${{matrix.language}}" \ No newline at end of file From 60a57e1d06912be7d7fe20eb5c8fe689d01c85cf Mon Sep 17 00:00:00 2001 From: Ritik Raj Date: Mon, 26 Jun 2023 22:55:57 +0530 Subject: [PATCH 21/66] removed redundant sharpe ratio endpoint --- main.py | 25 ------------------------- 1 file changed, 25 deletions(-) diff --git a/main.py b/main.py index eec383ba..58a8cb22 100644 --- a/main.py +++ b/main.py @@ -2985,31 +2985,6 @@ def calculate_post_tax_return_percentage(tax_rate_percentage: float, except: return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) -# Endpoint for function Sharpe ratio - - -@app.get( - "/sharpe_ratio", - tags=["sharpe_ratio"], - description="Calculate Sharpe ratio", -) -def sharpe_ratio( - prices: list[float], risk_free_rate: float -): - try: - returns = functions.calculate_returns(prices) - ratio = functions.calculate_sharpe_ratio(returns, risk_free_rate) - return { - "Tag": "Sharpe Ratio", - "Prices": prices, - "Risk-free Rate": risk_free_rate, - "Sharpe Ratio": ratio, - } - except Exception as e: - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e)) - - # Endpoint for function Treynor Ratio @app.get( From be8440adbceb726968ba062bcc0645233e19f7cc Mon Sep 17 00:00:00 2001 From: ighoshsubho Date: Thu, 29 Jun 2023 17:41:49 +0530 Subject: [PATCH 22/66] V2:Modular and Request Validation --- .vscode/settings.json | 5 +- Dockerfile | 1 - main.py | 2137 +++-------------- tasks/accounts_payable_turnover_ratio.py | 19 + tasks/accrint.py | 27 + tasks/acid_test_ratio.py | 23 + tasks/asdcr.py | 23 + tasks/asset_portfolio.py | 31 + tasks/asset_turnover_ratio.py | 20 + tasks/balloon_balance.py | 23 + tasks/balloon_loan_payment.py | 23 + tasks/bep.py | 18 + tasks/bid_ask_spread.py | 14 + tasks/bond_equivalent_yield.py | 19 + tasks/calculate_bvps.py | 17 + .../calculate_expected_return_of_portfolio.py | 18 + tasks/calculate_financial_leverage.py | 21 + tasks/calculate_gratuity.py | 26 + tasks/calculate_gst.py | 15 + tasks/calculate_macaulay_duration.py | 28 + tasks/calculate_market_cap.py | 18 + tasks/calculate_net_profit_margin.py | 24 + tasks/calculate_pension.py | 26 + tasks/calculate_period_FV_PV_rate.py | 14 + tasks/calculate_post_tax_return_percentage.py | 18 + tasks/calculate_retirement_goals.py | 29 + tasks/calculate_retirement_goalspy | 29 + tasks/calculate_salary.py | 27 + tasks/calculate_vat.py | 19 + tasks/capital_Asset_Pricing_Model.py | 21 + tasks/capital_gains_yield.py | 14 + tasks/capitalization_rate.py | 33 + tasks/certificate_of_deposit.py | 20 + tasks/cogr.py | 18 + tasks/cogs.py | 19 + tasks/college_cost.py | 35 + tasks/commission_calc.py | 33 + tasks/compound_annual_growth_rate.py | 19 + tasks/compound_interest.py | 20 + tasks/compounded_annual_growth_rate.py | 20 + tasks/convexity_duration.py | 20 + tasks/cost_of_equity.py | 19 + tasks/credit_card_equation.py | 19 + tasks/credit_card_payoff.py | 22 + tasks/current_liability_coverage_ratio.py | 23 + tasks/current_ratio.py | 15 + tasks/debt_to_income_ratio.py | 15 + tasks/diluted_earnings_per_share.py | 21 + tasks/discount_opex.py | 15 + tasks/discounted_cash_flow.py | 23 + tasks/discounted_payback_period.py | 17 + tasks/dividend_payout_ratio.py | 16 + tasks/dividend_yield_ratio.py | 15 + tasks/doubling_time.py | 13 + tasks/effective_annual_rate..py | 18 + tasks/effective_annual_rate.py | 18 + tasks/enterprise_value.py | 31 + tasks/excess_reserves.py | 15 + tasks/fcff.py | 30 + tasks/fha_loan.py | 30 + tasks/fixed_charges_coverage_ratio.py | 21 + tasks/free_cash_flow_to_equity.py | 47 + tasks/future_sip.py | 19 + tasks/future_value_of_annuity.py | 19 + tasks/future_value_of_annuity_due.py | 19 + tasks/future_value_of_ordinary_due.py | 19 + tasks/gdp_growth_rate.py | 15 + tasks/herfindahl_Index.py | 13 + tasks/inflation.py | 16 + tasks/inflation_adjusted_return.py | 30 + tasks/inflation_rate.py | 16 + tasks/inventory_shrinkage_rate.py | 19 + tasks/inventory_turnover_ratio.py | 17 + tasks/jensens_alpha.py | 26 + tasks/k401.py | 37 + tasks/leverage_ratio_equity.py | 15 + tasks/leverage_ratio_income.py | 15 + tasks/levered_beta.py | 16 + tasks/loan_affordability.py | 43 + tasks/loan_emi.py | 18 + tasks/loan_to_value.py | 14 + tasks/loan_to_value_ratio.py | 14 + tasks/lumpsum.py | 16 + tasks/markup_percentage.py | 14 + tasks/monthly_emi.py | 17 + tasks/monthly_lease_payment.py | 21 + tasks/monthly_payment.py | 23 + tasks/mortgage_amortization.py | 24 + tasks/mortrages.py | 24 + tasks/net_present_value.py | 17 + tasks/net_worth.py | 15 + tasks/payback_period.py | 19 + tasks/periodic_lease_payment.py | 21 + tasks/perpetuity_payment.py | 13 + tasks/personal_loan.py | 20 + tasks/personal_savings.py | 17 + tasks/portfolio_return_monte_carlo.py | 20 + tasks/preferred_stock_value.py | 15 + tasks/present_value_of_annuity_due.py | 19 + tasks/price_to_earning_ratio.py | 14 + tasks/profitability_index.py | 16 + tasks/profitability_index2.py | 19 + tasks/project_efficiency.py | 17 + tasks/purchasing_power.py | 17 + tasks/put_call_parity.py | 16 + tasks/real_gdp.py | 14 + tasks/receivables_turnover_ratio.py | 16 + tasks/refinance.py | 41 + tasks/remaining_balance.py | 26 + tasks/retention_ratio.py | 14 + tasks/roi.py | 17 + tasks/roi_equity_funds.py | 22 + tasks/roth_ira.py | 26 + tasks/ruleof72.py | 13 + tasks/salary_calculate.py | 22 + tasks/sharpe_ratio.py | 21 + tasks/simple_interest_rate.py | 16 + tasks/social_securities.py | 17 + tasks/student_loan.py | 16 + tasks/tax_equivalent_yield.py | 15 + tasks/time_period_required_for_growth.py | 15 + tasks/treynor_ratio.py | 19 + tasks/wacc.py | 21 + tasks/weighted_average.py | 14 + tasks/weighted_average_of_values.py | 16 + tasks/year_to_year.py | 13 + tasks/yield_to_maturity.py | 18 + tasks/zero_coupoun_bond_value.py | 18 + tasks/zero_coupoun_bond_yield.py | 19 + test_main.py => tests/test_main.py | 0 tests/test_tasks.py | 0 validators/request_validators.py | 858 +++++++ 132 files changed, 3757 insertions(+), 1791 deletions(-) create mode 100644 tasks/accounts_payable_turnover_ratio.py create mode 100644 tasks/accrint.py create mode 100644 tasks/acid_test_ratio.py create mode 100644 tasks/asdcr.py create mode 100644 tasks/asset_portfolio.py create mode 100644 tasks/asset_turnover_ratio.py create mode 100644 tasks/balloon_balance.py create mode 100644 tasks/balloon_loan_payment.py create mode 100644 tasks/bep.py create mode 100644 tasks/bid_ask_spread.py create mode 100644 tasks/bond_equivalent_yield.py create mode 100644 tasks/calculate_bvps.py create mode 100644 tasks/calculate_expected_return_of_portfolio.py create mode 100644 tasks/calculate_financial_leverage.py create mode 100644 tasks/calculate_gratuity.py create mode 100644 tasks/calculate_gst.py create mode 100644 tasks/calculate_macaulay_duration.py create mode 100644 tasks/calculate_market_cap.py create mode 100644 tasks/calculate_net_profit_margin.py create mode 100644 tasks/calculate_pension.py create mode 100644 tasks/calculate_period_FV_PV_rate.py create mode 100644 tasks/calculate_post_tax_return_percentage.py create mode 100644 tasks/calculate_retirement_goals.py create mode 100644 tasks/calculate_retirement_goalspy create mode 100644 tasks/calculate_salary.py create mode 100644 tasks/calculate_vat.py create mode 100644 tasks/capital_Asset_Pricing_Model.py create mode 100644 tasks/capital_gains_yield.py create mode 100644 tasks/capitalization_rate.py create mode 100644 tasks/certificate_of_deposit.py create mode 100644 tasks/cogr.py create mode 100644 tasks/cogs.py create mode 100644 tasks/college_cost.py create mode 100644 tasks/commission_calc.py create mode 100644 tasks/compound_annual_growth_rate.py create mode 100644 tasks/compound_interest.py create mode 100644 tasks/compounded_annual_growth_rate.py create mode 100644 tasks/convexity_duration.py create mode 100644 tasks/cost_of_equity.py create mode 100644 tasks/credit_card_equation.py create mode 100644 tasks/credit_card_payoff.py create mode 100644 tasks/current_liability_coverage_ratio.py create mode 100644 tasks/current_ratio.py create mode 100644 tasks/debt_to_income_ratio.py create mode 100644 tasks/diluted_earnings_per_share.py create mode 100644 tasks/discount_opex.py create mode 100644 tasks/discounted_cash_flow.py create mode 100644 tasks/discounted_payback_period.py create mode 100644 tasks/dividend_payout_ratio.py create mode 100644 tasks/dividend_yield_ratio.py create mode 100644 tasks/doubling_time.py create mode 100644 tasks/effective_annual_rate..py create mode 100644 tasks/effective_annual_rate.py create mode 100644 tasks/enterprise_value.py create mode 100644 tasks/excess_reserves.py create mode 100644 tasks/fcff.py create mode 100644 tasks/fha_loan.py create mode 100644 tasks/fixed_charges_coverage_ratio.py create mode 100644 tasks/free_cash_flow_to_equity.py create mode 100644 tasks/future_sip.py create mode 100644 tasks/future_value_of_annuity.py create mode 100644 tasks/future_value_of_annuity_due.py create mode 100644 tasks/future_value_of_ordinary_due.py create mode 100644 tasks/gdp_growth_rate.py create mode 100644 tasks/herfindahl_Index.py create mode 100644 tasks/inflation.py create mode 100644 tasks/inflation_adjusted_return.py create mode 100644 tasks/inflation_rate.py create mode 100644 tasks/inventory_shrinkage_rate.py create mode 100644 tasks/inventory_turnover_ratio.py create mode 100644 tasks/jensens_alpha.py create mode 100644 tasks/k401.py create mode 100644 tasks/leverage_ratio_equity.py create mode 100644 tasks/leverage_ratio_income.py create mode 100644 tasks/levered_beta.py create mode 100644 tasks/loan_affordability.py create mode 100644 tasks/loan_emi.py create mode 100644 tasks/loan_to_value.py create mode 100644 tasks/loan_to_value_ratio.py create mode 100644 tasks/lumpsum.py create mode 100644 tasks/markup_percentage.py create mode 100644 tasks/monthly_emi.py create mode 100644 tasks/monthly_lease_payment.py create mode 100644 tasks/monthly_payment.py create mode 100644 tasks/mortgage_amortization.py create mode 100644 tasks/mortrages.py create mode 100644 tasks/net_present_value.py create mode 100644 tasks/net_worth.py create mode 100644 tasks/payback_period.py create mode 100644 tasks/periodic_lease_payment.py create mode 100644 tasks/perpetuity_payment.py create mode 100644 tasks/personal_loan.py create mode 100644 tasks/personal_savings.py create mode 100644 tasks/portfolio_return_monte_carlo.py create mode 100644 tasks/preferred_stock_value.py create mode 100644 tasks/present_value_of_annuity_due.py create mode 100644 tasks/price_to_earning_ratio.py create mode 100644 tasks/profitability_index.py create mode 100644 tasks/profitability_index2.py create mode 100644 tasks/project_efficiency.py create mode 100644 tasks/purchasing_power.py create mode 100644 tasks/put_call_parity.py create mode 100644 tasks/real_gdp.py create mode 100644 tasks/receivables_turnover_ratio.py create mode 100644 tasks/refinance.py create mode 100644 tasks/remaining_balance.py create mode 100644 tasks/retention_ratio.py create mode 100644 tasks/roi.py create mode 100644 tasks/roi_equity_funds.py create mode 100644 tasks/roth_ira.py create mode 100644 tasks/ruleof72.py create mode 100644 tasks/salary_calculate.py create mode 100644 tasks/sharpe_ratio.py create mode 100644 tasks/simple_interest_rate.py create mode 100644 tasks/social_securities.py create mode 100644 tasks/student_loan.py create mode 100644 tasks/tax_equivalent_yield.py create mode 100644 tasks/time_period_required_for_growth.py create mode 100644 tasks/treynor_ratio.py create mode 100644 tasks/wacc.py create mode 100644 tasks/weighted_average.py create mode 100644 tasks/weighted_average_of_values.py create mode 100644 tasks/year_to_year.py create mode 100644 tasks/yield_to_maturity.py create mode 100644 tasks/zero_coupoun_bond_value.py create mode 100644 tasks/zero_coupoun_bond_yield.py rename test_main.py => tests/test_main.py (100%) create mode 100644 tests/test_tasks.py create mode 100644 validators/request_validators.py diff --git a/.vscode/settings.json b/.vscode/settings.json index de288e1e..f21c79ab 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,3 +1,6 @@ { - "python.formatting.provider": "black" + "python.formatting.provider": "black", + "python.analysis.extraPaths": [ + "./validators" + ] } \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index 2f09842f..8530749e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,6 +1,5 @@ FROM python:3.9 - WORKDIR /usr/src/application COPY requirements.txt ./ diff --git a/main.py b/main.py index e9089a8a..ce5232c6 100644 --- a/main.py +++ b/main.py @@ -1,15 +1,140 @@ -from fastapi import FastAPI, HTTPException, status -from helpers import functions - - +from fastapi import FastAPI + +# Importing all the tasks +from tasks.simple_interest_rate import simple_interest_rate_task +from tasks.future_sip import future_sip_task +from tasks.calculate_pension import calculate_pension_task +from tasks.payback_period import payback_period_task +from tasks.compound_interest import compound_interest_task +from tasks.certificate_of_deposit import certificate_of_deposit_task +from tasks.inflation import inflation_task +from tasks.roi import return_on_investment_task +from tasks.compounded_annual_growth_rate import compounded_annual_growth_rate_task +from tasks.jensens_alpha import jensens_alpha_task +from tasks.social_securities import ss_task +from tasks.tax_equivalent_yield import tax_equivalent_yield_task +from tasks.time_period_required_for_growth import time_period_required_for_growth_task +from tasks.treynor_ratio import treynor_ratio_task +from tasks.wacc import weighted_average_cost_of_capital_task +from tasks.loan_emi import loan_emi_task +from tasks.asset_portfolio import asset_portfolio_task +from tasks.put_call_parity import put_call_parity_task +from tasks.bep import break_even_point_task +from tasks.fcff import free_cash_flow_to_firm_task +from tasks.price_to_earning_ratio import price_to_earning_ratio_task +from tasks.dividend_yield_ratio import dividend_yield_ratio_task +from tasks.dividend_payout_ratio import dividend_payout_ratio_task +from tasks.debt_to_income_ratio import debt_to_income_ratio_task +from tasks.fixed_charges_coverage_ratio import fixed_charge_coverage_ratio_task +from tasks.inventory_shrinkage_rate import inventory_shrinkage_rate_task +from tasks.markup_percentage import markup_percentage_task +from tasks.sharpe_ratio import sharpe_ratio_task +from tasks.purchasing_power import purchasing_power_task +from tasks.monthly_emi import monthly_emi_task +from tasks.doubling_time import doubling_time_task +from tasks.weighted_average import weighted_average_task +from tasks.capital_Asset_Pricing_Model import Capital_Asset_Pricing_Model_task +from tasks.cost_of_equity import cost_of_equity_task +from tasks.cogs import cost_of_goods_sold_task +from tasks.ruleof72 import rule_of_72_task +from tasks.acid_test_ratio import acid_test_ratio_task +from tasks.inflation_adjusted_return import inflation_adjusted_return_task +from tasks.cogr import compound_annual_growth_rate_task +from tasks.current_liability_coverage_ratio import current_liability_coverage_ratio_task +from tasks.levered_beta import levered_beta_task +from tasks.monthly_payment import monthly_payment_task +from tasks.convexity_duration import duration_task +from tasks.current_ratio import current_ratio_task +from tasks.compound_annual_growth_rate import compound_annual_growth_rate_1_task +from tasks.credit_card_equation import credit_card_equation_task +from tasks.credit_card_payoff import credit_card_payoff_task +from tasks.discount_opex import discount_opex_task +from tasks.discounted_cash_flow import discounted_cash_flow_task +from tasks.effective_annual_rate import effective_annual_rate_task +from tasks.excess_reserves import excess_reserves_task +from tasks.future_value_of_annuity_due import future_value_of_annuity_due_task +from tasks.future_value_of_ordinary_due import future_value_of_ordinary_due_task +from tasks.gdp_growth_rate import gdp_growth_rate_task +from tasks.herfindahl_Index import herfindahl_Index_task +from tasks.inflation_rate import inflation_rate_task +from tasks.inventory_turnover_ratio import inventory_turnover_ratio_task +from tasks.loan_to_value import loan_to_value_task +from tasks.present_value_of_annuity_due import present_value_of_annuity_due_task +from tasks.project_efficiency import project_efficiency_task +from tasks.real_gdp import real_gdp_task +from tasks.weighted_average_of_values import weighted_average_of_values_task +from tasks.year_to_year import year_over_year_task +from tasks.yield_to_maturity import yield_to_maturity_task +from tasks.zero_coupoun_bond_value import zero_coupon_bond_value_task +from tasks.zero_coupoun_bond_yield import zero_coupon_bond_yield_task +from tasks.balloon_balance import balloon_balance_task +from tasks.discounted_payback_period import discounted_payback_period_task +from tasks.future_value_of_annuity import future_value_of_annuity_task +from tasks.leverage_ratio_equity import leverage_equity_task +from tasks.leverage_ratio_income import leverage_income_task +from tasks.net_present_value import net_present_value_task +from tasks.periodic_lease_payment import periodic_lease_payment_task +from tasks.perpetuity_payment import perpetuity_payment_task +from tasks.profitability_index import profitability_index_task +from tasks.profitability_index2 import profitability_index2_task +from tasks.receivables_turnover_ratio import receivables_turnover_ratio_task +from tasks.remaining_balance import remaining_balance_task +from tasks.retention_ratio import retention_ratio_task +from tasks.roi_equity_funds import calculate_roi_equity_funds_task +from tasks.student_loan import student_loan_task +from tasks.commission_calc import commission_calc_task +from tasks.lumpsum import calculate_lumpsum_task +from tasks.personal_loan import personal_loan_task +from tasks.refinance import refinance_task +from tasks.asdcr import asdcr_task +from tasks.calculate_gst import calculate_gst_task +from tasks.calculate_market_cap import calculate_market_cap_task +from tasks.calculate_retirement_goals import calculate_retirement_goals_task +from tasks.college_cost import college_cost_task +from tasks.diluted_earnings_per_share import calculate_diluted_eps_task +from tasks.salary_calculate import salary_calculate_task +from tasks.enterprise_value import calculate_enterprise_value_task +from tasks.fha_loan import fha_loan_task +from tasks.mortgage_amortization import mortgage_amortization_task +from tasks.roth_ira import roth_ira_task +from tasks.k401 import estimate_401k_task +from tasks.monthly_lease_payment import monthly_lease_payment_task +from tasks.calculate_period_FV_PV_rate import CalculatePeriods_task +from tasks.bid_ask_spread import bid_ask_spread_task +from tasks.asset_turnover_ratio import asset_turnover_ratio_task +from tasks.preferred_stock_value import preferred_stock_value_task +from tasks.accounts_payable_turnover_ratio import accounts_payable_turnover_ratio_task +from tasks.accrint import accrued_interest_task +from tasks.balloon_loan_payment import balloon_loan_payment_task +from tasks.calculate_bvps import calculate_bvps_task +from tasks.calculate_expected_return_of_portfolio import calculate_expected_return_of_portfolio_task +from tasks.calculate_financial_leverage import calculate_financial_leverage_task +from tasks.calculate_gratuity import calculate_gratuity_task +from tasks.calculate_macaulay_duration import calculate_macaulay_duration_task +from tasks.calculate_net_profit_margin import calculate_net_profit_margin_task +from tasks.calculate_post_tax_return_percentage import calculate_post_tax_return_percentage_task +from tasks.calculate_salary import calculate_salary_task +from tasks.capital_gains_yield import capital_gains_yield_task +from tasks.capitalization_rate import capitalization_rate_task +from tasks.free_cash_flow_to_equity import free_cash_flow_to_equity_task +from tasks.loan_affordability import calculate_loan_affordability_task +from tasks.bond_equivalent_yield import bond_equivalent_yield_task +from tasks.calculate_vat import calculate_vat_task +from tasks.loan_to_value_ratio import loan_to_value_ratio_task +from tasks.mortrages import mortrage_task +from tasks.net_worth import net_worth_calculation_task +from tasks.personal_savings import personal_savings_task +from tasks.portfolio_return_monte_carlo import portfolio_return_monte_carlo_task +from validators.request_validators import SimpleInterestRateRequest, calculatePension, compoundInterest, futureSip, paybackPeriod + +# Creating the app app = FastAPI( title="FinTech API", description="An API that helps you to deal with your financial calculations.", - version="1", + version="2", contact={ "name": "Clueless Community", "url": "https://www.clueless.tech/", - "email": "https://www.clueless.tech/contact-us", }, license_info={ "name": " MIT license", @@ -17,6 +142,7 @@ }, ) +# Adding the routes @app.get("/") def index(): @@ -27,7 +153,6 @@ def index(): "contact": { "name": "Clueless Community", "url": "https://www.clueless.tech/", - "email": "https://www.clueless.tech/contact-us", }, "license_info": { "name": " MIT license", @@ -137,25 +262,16 @@ def index(): # Endpoints to calculate simple interest. + @app.get( "/simple_interest_rate", tags=["simple_interest_rate"], description="Calculate simple interest rates", ) -def simple_interest_rate(amount_paid: float, principle_amount: float, months: int): - try: - rate = functions.simple_interest_rate( - amount_paid, principle_amount, months) - return { - "Tag": "Simple Interest Rate", - "Total amount paid": amount_paid, - "Principle amount": principle_amount, - "Interest Paid": amount_paid - principle_amount, - "Interest Rate": f"{rate}%", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) +def simple_interest_rate(request: SimpleInterestRateRequest): + return simple_interest_rate_task(request.amount_paid, request.principle_amount, request.months) +# Endpoints to calculate Future sip @app.get( "/future_sip", @@ -163,22 +279,11 @@ def simple_interest_rate(amount_paid: float, principle_amount: float, months: in description="Calculate Future Value of SIP", ) def future_sip( - interval_investment: float, rate_of_return: float, number_of_payments: int + request: futureSip, ): - try: - value = functions.future_sip( - interval_investment, rate_of_return, number_of_payments - ) - return { - "Tag": "Future Value of SIP", - "Investment at every Interval": interval_investment, - "Interest": functions.percent_to_decimal(rate_of_return) / 12, - "Number of Payments": number_of_payments, - "Future Value": f"{value}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return future_sip_task(request.interval_investment, request.rate_of_return, request.number_of_payments) +# Endpoints to calculate Future value @app.get( "/calculate_pension", @@ -186,28 +291,9 @@ def future_sip( description="Calculate pension", ) def calculate_pension( - monthly_investment_amount, - no_of_years, - annuity_rates, - annuity_purchased, - yearly_interest_rates, + request: calculatePension ): - try: - (total_corpus, lump_sum_pension, monthly_pension) = functions.calculate_pension( - monthly_investment_amount, - no_of_years, - annuity_rates, - annuity_purchased, - yearly_interest_rates, - ) - return { - "Tag": "Calculate pension", - "Total Corpus": total_corpus, - "Lump sum pension": lump_sum_pension, - "Monthly pension": monthly_pension, - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return calculate_pension_task(request.current_age, request.retirement_age, request.current_salary, request.percentage_saved, request.employer_match, request.expected_annual_raise, request.savings_goal) # endpoint for payback period @@ -217,21 +303,9 @@ def calculate_pension( description="Calculate payback period", ) def payback_period( - years_before_recovery: int, unrecovered_cost: float, cash_flow: float + request: paybackPeriod, ): - try: - period = functions.payback_period( - years_before_recovery, unrecovered_cost, cash_flow - ) - return { - "Tag": "Payback period", - "Years before full recovery": years_before_recovery, - "Unrecovered cost at start of the year": unrecovered_cost, - "Cash flow during the year": cash_flow, - "Payback period": f"{period}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return payback_period_task(request.initial_investment, request.cashflow) # Endpoints to calculate Compound Interest. @@ -241,22 +315,9 @@ def payback_period( description="Calculate compound interest amount", ) def compound_interest( - principal_amount: float, interest_rate: float, years: int, compounding_period: int + request: compoundInterest, ): - try: - amount = functions.compound_interest( - principal_amount, interest_rate, years, compounding_period - ) - return { - "Tag": "Compound Interest Amount", - "Principle amount": principal_amount, - "Intrest Rate": interest_rate, - "Time in Years": years, - "Compounding Period": compounding_period, - "Amount after interest": f"{amount}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return compound_interest_task(request.principal_amount, request.interest_rate, request.time) # Endpoints to calculate certificate of deposit (CD) @@ -268,37 +329,13 @@ def compound_interest( def certificate_of_deposit( principal_amount: float, interest_rate: float, yrs: int, compounding_per_yr: int ): - try: - cd = functions.certificate_of_deposit( - principal_amount, interest_rate, yrs, compounding_per_yr - ) - return { - "Tag": "Certificate of Deposit (CD)", - "Principal amount": principal_amount, - "Interest Rate": interest_rate, - "Time in Years": yrs, - "Number of Compounding per Year": compounding_per_yr, - "Certificate of Deposit (CD)": f"{cd}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return certificate_of_deposit_task(principal_amount, interest_rate, yrs, compounding_per_yr) # EndPoint to calculate Inflation @app.get("/inflation", tags=["inflated"], description="Calculate Inflated amount") def inflation(present_amount: float, inflation_rate: float, years: float): - try: - future_amount = functions.inflation( - present_amount, inflation_rate, years) - return { - "Tag": "Inflated Amount", - "Present Amount": present_amount, - "Inflation Rate": inflation_rate, - "Time in Years": years, - "Future Amount": f"{future_amount}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return inflation_task(present_amount, inflation_rate, years) # Endpoint to Calculate Effective Annual Rate @@ -308,39 +345,13 @@ def inflation(present_amount: float, inflation_rate: float, years: float): description="Calculate Effective Annual Rate", ) def effective_annual_rate(annual_interest_rate: float, compounding_period: int): - try: - eff_annual_rate = functions.effective_annual_rate( - annual_interest_rate, compounding_period - ) - eff_annual_rate_percentage = functions.decimal_to_percent( - eff_annual_rate) - return { - "Tag": "Effective Annual Rate", - "Annual Intrest Rate": annual_interest_rate, - "Compounding Period": compounding_period, - "Effective Annual Rate (in percentage)": f"{eff_annual_rate_percentage}%", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) - + return effective_annual_rate_task(annual_interest_rate, compounding_period) @app.get( "/roi", tags=["return_on_investment"], description="Calculate return on investment" ) def return_on_investment(current_value_of_investment: float, cost_of_investment: float): - try: - roi = functions.return_on_investment( - current_value_of_investment, cost_of_investment - ) - - return { - "Tag": "Return on Investment", - "Current Value of Investment": current_value_of_investment, - "Cost of Investment": cost_of_investment, - "Return on Investment": f"{roi}%", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return return_on_investment_task(current_value_of_investment, cost_of_investment) # Endpoint to calculate Compounded Annual Growth Rate. @@ -352,20 +363,7 @@ def return_on_investment(current_value_of_investment: float, cost_of_investment: def compounded_annual_growth_rate( end_investment_value: float, initial_investment_value: float, years: int ): - try: - cagr = functions.compounded_annual_growth_rate( - end_investment_value, initial_investment_value, years - ) - - return { - "Tag": "Compounded Annual Growth Rate", - "End investment value": end_investment_value, - "Initial investment value": initial_investment_value, - "Years": years, - "Compounded Annual Growth Rate": f"{cagr}%", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return compounded_annual_growth_rate_task( end_investment_value, initial_investment_value, years) # Endpoint to calculate Jensen's Alpha @@ -380,23 +378,7 @@ def jensens_alpha( risk_free_rate: float, beta: float, ): - try: - alpha = functions.jensens_alpha( - return_from_investment, - return_of_appropriate_market_index, - risk_free_rate, - beta, - ) - return { - "Tag": "Jensen's Alpha", - "Total return from investment": return_from_investment, - "Return of appropriate market index": return_of_appropriate_market_index, - "Risk free rate": risk_free_rate, - "Beta of the portfolio investment w.r.t chosen market index": beta, - "Alpha of the return ": f"{alpha}%", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return jensens_alpha_task( return_from_investment, return_of_appropriate_market_index, risk_free_rate, beta) # Endpoint to calculate WACC @@ -408,21 +390,7 @@ def jensens_alpha( def weighted_average_cost_of_capital( firm_equity, firm_debt, cost_of_equity, cost_of_debt, corporate_tax_rate ): - try: - wacc = functions.wacc( - firm_equity, firm_debt, cost_of_equity, cost_of_debt, corporate_tax_rate - ) - return { - "Tag": "Weighted Average Cost of Capital (WACC)", - "Market value of firm's equity": firm_equity, - "Market value of firm's debt": firm_debt, - "Cost of equity": cost_of_equity, - "Cost of debt": cost_of_debt, - "Corporate tax rate": corporate_tax_rate, - "WACC": f"{wacc}%", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return weighted_average_cost_of_capital_task( firm_equity, firm_debt, cost_of_equity, cost_of_debt, corporate_tax_rate) @app.get( @@ -431,20 +399,7 @@ def weighted_average_cost_of_capital( description="Calculate Loan EMI", ) def loan_emi(principle_amount: float, annual_rate: float, months: int): - try: - emi = functions.loan_emi(principle_amount, annual_rate, months) - return { - "Tag": "Loan Emi", - "Principal amount borrowed": principle_amount, - "Annual Rate of interest": annual_rate, - "Total number of monthly payments": months, - "EMI": f"{round(emi,3)}", - "Total Amount Payble": f"{round(emi*months,3)}", - "Interest amount": f"{round(emi*months-principle_amount,3)}", - } - except Exception as e: - print(e) - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return loan_emi_task(principle_amount, annual_rate, months) # Endpoint to calculate Variance of a Two Asset Portfolio @@ -462,25 +417,9 @@ def asset_portfolio( standard_dev_B: float, correlation: float, ): - try: - weight_A = price_A / (price_A + price_B) - weight_B = price_B / (price_A + price_B) - cov = 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 - ) - expected_return = functions.decimal_to_percent( - weight_A * return_A + weight_B * return_B - ) - return { - "Tag": "Portfolio Variance", - "Expected Returns": f"{expected_return}%", - "Portfolio Variance": f"{portfolio_variance}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return asset_portfolio_task( + price_A, price_B, return_A, return_B, standard_dev_A, standard_dev_B, correlation + ) # Endpoint to Calculate Future Price in Put-Call Parity @@ -490,18 +429,7 @@ def asset_portfolio( description="Calculate Future Price in Pull-Call Parity", ) def put_call_parity(call_price: float, put_price: float, strike_price: float): - try: - future_amount = functions.put_call_parity( - call_price, put_price, strike_price) - return { - "Tag": "Pull Call Parity", - "Future Price": f"{future_amount}", - "Call Price": f"{call_price}", - "Put Price": f"{put_price}", - "Strike Price": f"{strike_price}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return put_call_parity_task(call_price, put_price, strike_price) # Endpoint to calculate break even point @@ -511,20 +439,7 @@ def put_call_parity(call_price: float, put_price: float, strike_price: float): description="Calculate Break Even Point", ) def break_even_point(fixed_cost: float, selling_price: float, variable_cost: float): - try: - - bep = functions.break_even_point( - fixed_cost, selling_price, variable_cost) - return { - "Tag": "Break Even Point (BEP)", - "Fixed costs": fixed_cost, - "Selling price per unit": selling_price, - "Variable cost per unit": variable_cost, - "Break Even Point in units": f"{bep[0]}", - "Break Even Point in Rupees": f"{bep[1]}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return break_even_point_task(fixed_cost, selling_price, variable_cost) # Endpoint to calculate free cash flow to firm @@ -542,24 +457,9 @@ def free_cash_flow_to_firm( fcInv: float, wcInv: float, ): - try: - ebitda = sales - operating_cost - ebit = ebitda - depreciation - ebt = ebit - interest - - eat = ebt - ebt * (tax_rate * 0.01) - fcff = functions.free_cash_flow_to_firm( - sales, operating_cost, depreciation, interest, tax_rate, fcInv, wcInv - ) - return { - "Tag": "Free Cash Flow to Firm (FCFF)", - "Earnings before interest, taxes, depreciation and amortization": f"{ebitda}", - "Earnings before interest and taxes : ": f"{ebit}", - "Net Income": f"{eat}", - "Free Cash Flow to Firm": f"{fcff}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return free_cash_flow_to_firm_task( + sales, operating_cost, depreciation, interest, tax_rate, fcInv, wcInv + ) # Endpoint to calculate Price-to-earning ratio @@ -569,16 +469,7 @@ def free_cash_flow_to_firm( description="Calculate price to earning ratio", ) def price_to_earning_ratio(share_price: float, earnings_per_share: float): - try: - p_e_ratio = functions.price_to_earning(share_price, earnings_per_share) - return { - "Tag": "Price to Earning ratio", - "Share price": share_price, - "Earning per share": earnings_per_share, - "Price to Earning ratio": f"{p_e_ratio}%", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return price_to_earning_ratio_task(share_price, earnings_per_share) # Endpoint to calculate Dividend yield ratio @@ -590,18 +481,7 @@ def price_to_earning_ratio(share_price: float, earnings_per_share: float): description="Calculate dividend yield ratio", ) def dividend_yield_ratio(dividend_per_share: float, share_price: float): - try: - dividend_yield = functions.dividend_yield_ratio( - dividend_per_share, share_price) - return { - "Tag": "Dividend yield ratio", - "Dividend per share": dividend_per_share, - "Share price": share_price, - "Dividend yield ratio": f"{dividend_yield}%", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) - + return dividend_yield_ratio_task(dividend_per_share, share_price) # Endpoint to calculate Dividend payout ratio @app.get( @@ -610,18 +490,7 @@ def dividend_yield_ratio(dividend_per_share: float, share_price: float): description="Calculate dividend payout ratio", ) def dividend_payout_ratio(dividend_per_share: float, earnings_per_share: float): - try: - dividend_payout = functions.dividend_payout_ratio( - dividend_per_share, earnings_per_share - ) - return { - "Tag": "Dividend payout ratio", - "Dividend per share": dividend_per_share, - "Share price": earnings_per_share, - "Dividend yield ratio": f"{dividend_payout}%", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return dividend_payout_ratio_task(dividend_per_share, earnings_per_share) # Endpoint to calculate DTI @@ -631,17 +500,7 @@ def dividend_payout_ratio(dividend_per_share: float, earnings_per_share: float): description="Calculate debt to income ratio per month", ) def debt_to_income_ratio(annual_income: float, total_debt_per_month: float): - try: - DTI = functions.debt_to_income_ratio( - annual_income, total_debt_per_month) - return { - "Tag": "Debt to income ratio", - "Annual income": annual_income, - "Total debt per month": total_debt_per_month, - "Debt to income ratio per month": f"{DTI}%", - } - except: - raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE) + return debt_to_income_ratio_task(annual_income, total_debt_per_month) # Endpoint to calculate fixed charge coverage ratio: @@ -655,19 +514,9 @@ def fixed_charge_coverage_ratio( fixed_charge_before_tax: float, interest: float, ): - try: - fccr = functions.fixed_charge_coverage_ratio( - earnings_before_interest_taxes, fixed_charge_before_tax, interest - ) - return { - "Tag": "fixed charges coverage ratio", - "Earnings before interest taxes": earnings_before_interest_taxes, - "Fixed charge before tax": fixed_charge_before_tax, - "Interest": interest, - "Fixed charge coverage ratio": f"{fccr}%", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return fixed_charge_coverage_ratio_task( + earnings_before_interest_taxes, fixed_charge_before_tax, interest + ) # Endpoint to calculate Inventory Shrinkage Rate @@ -677,21 +526,7 @@ def fixed_charge_coverage_ratio( description="Calculate inventory shrinkage rate", ) def inventory_shrinkage_rate(recorded_inventory: float, actual_inventory: float): - try: - inventory_shrinkage_rate = functions.inventory_shrinkage_rate( - recorded_inventory, actual_inventory - ) - return { - "Tag": "Inventory shrinkage rate", - "Recorded Inventory": recorded_inventory, - "Actual Inventory": actual_inventory, - "Inventory Shrinkage Rate": inventory_shrinkage_rate, - "Inventory Shrinkage Rate (%)": functions.decimal_to_percent( - inventory_shrinkage_rate - ), - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return inventory_shrinkage_rate_task(recorded_inventory, actual_inventory) # Endpoint to calculate Markup Percentage @@ -701,16 +536,7 @@ def inventory_shrinkage_rate(recorded_inventory: float, actual_inventory: float) description="Calculate markup percentage", ) def markup_percentage(price: float, cost: float): - try: - markup_percentage = functions.markup_percentage(price, cost) - return { - "Tag": "Markup Percentage", - "Price": price, - "Cost": cost, - "Markup Percentage": markup_percentage, - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return markup_percentage_task(price, cost) # Endpoint to calculate Sharpe ratio @@ -724,19 +550,7 @@ def sharpe_ratio( risk_free_rate: float, standard_deviation_of_portfolio: float, ): - try: - sharpe_ratio = functions.sharpe_ratio( - portfolio_return, risk_free_rate, standard_deviation_of_portfolio - ) - return { - "Tag": "Sharpe Ratio", - "Portfolio Return": portfolio_return, - "Risk Free Rate": risk_free_rate, - "Standard Deviation of Portfolio": standard_deviation_of_portfolio, - "Sharpe Ratio": f"{sharpe_ratio}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return sharpe_ratio_task(portfolio_return, risk_free_rate, standard_deviation_of_portfolio) # Endpoint to calculate purchase power @@ -746,19 +560,7 @@ def sharpe_ratio( description="Calculate Purchasing Power", ) def purchasing_power(initial_amount: float, annual_inflation_rate: float, time: float): - try: - purchasing_power = functions.purchasing_power( - initial_amount, annual_inflation_rate, time - ) - return { - "Tag": "Purchasing Power", - "Initial Amount": initial_amount, - "Annual Inflation Rate": annual_inflation_rate, - "Time in years": time, - "Purchasing Power": f"{purchasing_power}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return purchasing_power_task(initial_amount, annual_inflation_rate, time) # Endpoint to calculate Monthly EMI @@ -768,19 +570,7 @@ def purchasing_power(initial_amount: float, annual_inflation_rate: float, time: description="Monthly EMI", ) def monthly_emi(loan_amt: float, interest_rate: float, number_of_installments: float): - try: - monthly_emi = functions.monthly_emi( - loan_amt, interest_rate, number_of_installments - ) - return { - "Tag": "Monthly EMI", - "Loan Amount": loan_amt, - "Interest Rate": interest_rate, - "Number of Installments": number_of_installments, - "Total EMI": f"{monthly_emi}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return monthly_emi_task(loan_amt, interest_rate, number_of_installments) # Endpoint to calculate doubling time @@ -790,15 +580,7 @@ def monthly_emi(loan_amt: float, interest_rate: float, number_of_installments: f description="Doubling Time", ) def doubling_time(r: float): - try: - doubling_time = functions.doubling_time(r) - return { - "Tag": "Doubling Time", - "Rate of Interest": r, - "Time in years to double the money": f"{doubling_time}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return doubling_time_task(r) # Endpoint to calculate weighted average @@ -808,16 +590,7 @@ def doubling_time(r: float): description="Weighted Average", ) def weighted_average(ratio: list, rates: list): - try: - weighted_average = functions.weighted_average(ratio, rates) - return { - "Tag": "Weighted Average", - "Ratio of each investment principal": ratio, - "Rates": rates, - "Weighted average : ": f"{weighted_average}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return weighted_average_task(ratio, rates) # Endpoint to calculate Capital Asset Pricing Model @@ -831,20 +604,9 @@ def Capital_Asset_Pricing_Model( beta_of_security: float, expected_market_return: float, ): - try: - Capital_Asset_Pricing_Model = functions.Capital_Asset_Pricing_Model( - risk_free_interest_rate, beta_of_security, expected_market_return - ) - return { - "Tag": "Capital Asset Pricing Model", - "Risk free interest rate": risk_free_interest_rate, - "Beta of security": beta_of_security, - "Expected market return": expected_market_return, - "Capital asset expected return": f"{Capital_Asset_Pricing_Model}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) - + return Capital_Asset_Pricing_Model_task( + risk_free_interest_rate, beta_of_security, expected_market_return + ) # Endpoint to calculate cost of equity @app.get( @@ -855,19 +617,7 @@ def Capital_Asset_Pricing_Model( def cost_of_equity( risk_free_rate_of_return: float, Beta: float, market_rate_of_return: float ): - try: - costOfEquity = functions.cost_of_equity( - risk_free_rate_of_return, Beta, market_rate_of_return - ) - return { - "Tag": "Cost of Equity", - "Risk free rate of return": risk_free_rate_of_return, - "Beta": Beta, - "Market rate of return ": market_rate_of_return, - "Cost of equity": f"{costOfEquity}%", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return cost_of_equity_task(risk_free_rate_of_return, Beta, market_rate_of_return) # Endpoint to calculate cost of goods sold @@ -879,19 +629,7 @@ def cost_of_equity( def cost_of_goods_sold( beginning_inventory: float, purchases: float, ending_inventory: float ): - try: - cogs = functions.cost_of_goods_sold( - beginning_inventory, purchases, ending_inventory - ) - return { - "Tag": "Cost of Goods Sold", - "Beginning Inventory": beginning_inventory, - "Purchases during the period": purchases, - "Ending Inventory": ending_inventory, - "Cost of Goods Sold(In Rupees)": f"{cogs}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return cost_of_goods_sold_task(beginning_inventory, purchases, ending_inventory) # Endpoint to calculate rule of 72 @@ -901,15 +639,7 @@ def cost_of_goods_sold( description="Calculate Rule of 72", ) def rule_of_72(rate_of_roi: float): - try: - time_period = functions.rule_of_72(rate_of_roi) - return { - "Tag": "Rule of 72", - "Rate of ROI": rate_of_roi, - "Time period in which investment get double(in years)": f"{time_period}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return rule_of_72_task(rate_of_roi) # Endpoint to calculate acid test ratio @@ -924,20 +654,9 @@ def acid_test_ratio( accounts_receivable: float, current_liabilities: float, ): - try: - ratio = functions.acid_test_ratio( - cash, marketable_securities, accounts_receivable, current_liabilities - ) - return { - "Tag": "Acid Test Ratio", - "Cash and Cash Equivalents": cash, - "Marketable Securities": marketable_securities, - "Accounts Receivable": accounts_receivable, - "Current Liabilities": current_liabilities, - "Acid Test Ratio (Quick Ratio)": f"{ratio}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return acid_test_ratio_task( + cash, marketable_securities, accounts_receivable, current_liabilities + ) # Endpoint to calculate inflation adjusted return @@ -953,26 +672,13 @@ def inflation_adjusted_return( beginning_cpi_level: float, ending_cpi__level: float, ): - try: - stock_return = (ending_price - beginning_price + - dividends) / beginning_price - inflation = (ending_cpi__level - beginning_cpi_level) / \ - beginning_cpi_level - inflation_adj_return = functions.inflation_adjusted_return( - beginning_price, - ending_price, - dividends, - beginning_cpi_level, - ending_cpi__level, - ) - return { - "Tag": "Inflation Adjusted Return", - "Stock Return": f"{stock_return}%", - "Inflation Rate": f"{inflation}%", - "Inflation Adjusted Return": f"{inflation_adj_return}%", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return inflation_adjusted_return_task( + beginning_price, + ending_price, + dividends, + beginning_cpi_level, + ending_cpi__level, + ) # Endpoint to calculate compound annual growth rate @@ -984,18 +690,7 @@ def inflation_adjusted_return( def compound_annual_growth_rate( beginning_value: float, ending_value: float, years: int ): - try: - rate = functions.compound_annual_growth_rate( - beginning_value, ending_value, years - ) - return { - "Tag": "Compound Annual Growth Rate", - "Beginning Value": beginning_value, - "Ending Value": ending_value, - "Compound Annual Growth Rate": f"{rate}%", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return compound_annual_growth_rate_task(beginning_value, ending_value, years) # Endpoint to calculate current liability coverage ratio @@ -1009,21 +704,9 @@ def current_liability_coverage_ratio( total_current_liabilities: float, number_of_liabilities: int, ): - try: - current_liability_coverage_ratio = functions.current_liability_coverage_ratio( - net_cash_from_operating_activities, - total_current_liabilities, - number_of_liabilities, - ) - return { - "Tag": "current liability coverage ratio", - "net cash from operating activities": net_cash_from_operating_activities, - "total current liabilities": total_current_liabilities, - "number of liabilities": number_of_liabilities, - "current liability coverage ratio": f"{current_liability_coverage_ratio}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return current_liability_coverage_ratio_task( + net_cash_from_operating_activities, total_current_liabilities, number_of_liabilities + ) @app.get( @@ -1032,18 +715,7 @@ def current_liability_coverage_ratio( description="Levered Beta", ) def levered_beta(unlevered_beta: float, tax_rate: float, debt: float, equity: float): - try: - l_beta = functions.levered_beta(unlevered_beta, tax_rate, debt, equity) - return { - "Tag": "Levered Beta", - "Unlevered Beta": unlevered_beta, - "Tax rate": tax_rate, - "debt": debt, - "Equity": equity, - "Levered Beta": f"{l_beta}%", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return levered_beta_task(unlevered_beta, tax_rate, debt, equity) @app.get( @@ -1057,20 +729,7 @@ def monthly_payment( number_of_periods: float, payments_per_period: float, ): - try: - monthly_pay = functions.monthly_payment( - principal, interest_rate, number_of_periods, payments_per_period - ) - return { - "Tag": "Monthly Payment", - "Principal": principal, - "Interest Rate": interest_rate, - "Number of Periods": number_of_periods, - "Payments per period": payments_per_period, - "Levered Beta": f"{monthly_pay}%", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return monthly_payment_task(principal, interest_rate, number_of_periods, payments_per_period) @app.get( @@ -1079,22 +738,7 @@ def monthly_payment( description="Convexity Adjusted Duration", ) def duration(rate, coupon_rate, frequency, face_value, settlement_date, maturity_date): - try: - duration = functions.duration( - rate, coupon_rate, frequency, face_value, settlement_date, maturity_date - ) - return { - "Tag": "Convexity Adjusted Duration", - "Market Rate": rate, - "Coupon rate": coupon_rate, - "Frequency": frequency, - "Face Value": face_value, - "Settlement Date": settlement_date, - "Maturity Date": maturity_date, - "Convexity Adjusted Duration": f"{duration}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return duration_task(rate, coupon_rate, frequency, face_value, settlement_date, maturity_date) # Endpoint to calculate current ratio @@ -1104,17 +748,7 @@ def duration(rate, coupon_rate, frequency, face_value, settlement_date, maturity description="Current Ratio", ) def current_ratio(total_current_assets: float, total_liabilities: float): - try: - ratio = functions.current_ratio( - total_current_assets, total_liabilities) - return { - "Tag": "Current Ratio", - "Total Current Assets": total_current_assets, - "Total Liabilities": total_liabilities, - "Current Ratio": f"{ratio}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return current_ratio_task(total_current_assets, total_liabilities) # Endpoint to calculate inventory turnover ratio @@ -1126,17 +760,9 @@ def current_ratio(total_current_assets: float, total_liabilities: float): def inventory_turnover_ratio( cost_of_goods_sold: float, beginning_inventory: float, ending_inventory: float ): - try: - ratio = functions.inventory_turnover_ratio( - cost_of_goods_sold, beginning_inventory, ending_inventory - ) - return { - "Tag": "Inventory Turnover Ratio", - "Cost of Goods Sold": cost_of_goods_sold, - "Inventory Turnover Ratio": f"{ratio}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return inventory_turnover_ratio_task( + cost_of_goods_sold, beginning_inventory, ending_inventory + ) # Endpoint to calculate inflation rate @@ -1146,18 +772,7 @@ def inventory_turnover_ratio( description="Inflation Rate", ) def inflation_rate(bigger_year: int, smaller_year: int, base_year: int): - try: - inflation_rate = functions.inflation_rate( - bigger_year, smaller_year, base_year) - return { - "Tag": "Inflation Rate", - "Bigger Year": bigger_year, - "Smaller Year": smaller_year, - "Base Year": base_year, - "Inflation Rate": inflation_rate, - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return inflation_rate_task(bigger_year, smaller_year, base_year) # Endpoint to calculate Herfindahl index @@ -1167,15 +782,7 @@ def inflation_rate(bigger_year: int, smaller_year: int, base_year: int): description="Calculating herfindahl Index", ) def herfindahl_Index(Firms_market_shares: str): - try: - herfindahl_Index = functions.herfindal_Index(Firms_market_shares) - return { - "Tag": "Herfindahl Index", - "Firms market shares": Firms_market_shares, - "Herfindahl Index": f"{herfindahl_Index}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return herfindahl_Index_task(Firms_market_shares) @app.get( @@ -1184,17 +791,7 @@ def herfindahl_Index(Firms_market_shares: str): description="Discount OPEX", ) def discount_opex(annual_opex: float, wacc: float, project_lifetime: float): - try: - dis_opex = functions.discount_opex(annual_opex, wacc, project_lifetime) - return { - "Tag": "Discount OPEX", - "Annual OPEX": annual_opex, - "WACC": wacc, - "project lifetime": project_lifetime, - "Discount opex": f"{dis_opex}%", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return discount_opex_task(annual_opex, wacc, project_lifetime) @app.get( @@ -1203,19 +800,7 @@ def discount_opex(annual_opex: float, wacc: float, project_lifetime: float): description="Project Efficiency", ) def project_efficiency(annual_production: float, collector_surface: float, dni: float): - try: - project_eff = functions.project_efficiency( - annual_production, collector_surface, dni - ) - return { - "Tag": "Project efficiency", - "Annual production": annual_production, - "collector surface": collector_surface, - "dni": dni, - "Discount opex": f"{project_eff}%", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return project_efficiency_task(annual_production, collector_surface, dni) @app.get( @@ -1224,16 +809,7 @@ def project_efficiency(annual_production: float, collector_surface: float, dni: description="Real GDP", ) def real_gdp(nominal_gdp: float, gdp_deflator: float): - try: - real_gdp = functions.real_gdp(nominal_gdp, gdp_deflator) - return { - "Tag": "Real GDP", - "Nominal GDP": nominal_gdp, - "GDP Deflator": gdp_deflator, - "Real GDP": real_gdp, - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return real_gdp_task(nominal_gdp, gdp_deflator) @app.get( @@ -1242,17 +818,7 @@ def real_gdp(nominal_gdp: float, gdp_deflator: float): description="Excess Reserves", ) def excess_reserves(deposits: float, reserve_requirement: float): - try: - excess_reserves = functions.excess_reserves( - deposits, reserve_requirement) - return { - "Tag": "Excess Reserves", - "Deposits": deposits, - "Reserve Requirement": reserve_requirement, - "Excess Reserves": excess_reserves, - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return excess_reserves_task(deposits, reserve_requirement) @app.get( @@ -1266,20 +832,9 @@ def discounted_cash_flow( wacc: float, project_lifetime: float, ): - try: - d_cash_flow = functions.discounted_cash_flow( - real_feed_in_tariff, annual_production, wacc, project_lifetime - ) - return { - "Tag": "Discounted cash flow", - "Real feed in teriff": real_feed_in_tariff, - "annual production": annual_production, - "wacc": wacc, - "project lifetime": project_lifetime, - "discounted cash flow": f"{d_cash_flow}%", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return discounted_cash_flow_task( + real_feed_in_tariff, annual_production, wacc, project_lifetime + ) @app.get( @@ -1288,17 +843,7 @@ def discounted_cash_flow( description="GDP Growth Rate", ) def gdp_growth_rate(current_year_gdp: float, last_year_gdp: float): - try: - gdp_growth_rate = functions.gdp_growth_rate( - current_year_gdp, last_year_gdp) - return { - "Tag": "GDP Growth Rate", - "Current Year GDP": current_year_gdp, - "Last Year GDP": last_year_gdp, - "GDP Growth Rate": gdp_growth_rate, - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return gdp_growth_rate_task(current_year_gdp, last_year_gdp) @app.get( @@ -1309,19 +854,7 @@ def gdp_growth_rate(current_year_gdp: float, last_year_gdp: float): def credit_card_equation( balance: float, monthly_payment: float, daily_interest_rate: float ): - try: - N = functions.credit_card_equation( - balance, monthly_payment, daily_interest_rate - ) - return { - "Tag": "Credit card equation", - "Balance": balance, - "Monthly Payment": monthly_payment, - "daily interest rate": daily_interest_rate, - "credit card equation": f"{N}%", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return credit_card_equation_task(balance, monthly_payment, daily_interest_rate) @app.get( @@ -1332,22 +865,9 @@ def credit_card_equation( def credit_card_payoff( debts: list, interest_rates: list, minimum_payments: list, monthly_payment: int ): - try: - result = functions.credit_card_payoff( - debts, interest_rates, minimum_payments, monthly_payment - ) - return { - "Tag": "Credit card payoff", - "debts": debts, - "interest rates": interest_rates, - "minimum payments": minimum_payments, - "Monthly payment": monthly_payment, - "Months": [r["month"] for r in result], - "Interest paid": [r["interest_paid"] for r in result], - "Total Payment": [r["total_payment"] for r in result], - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return credit_card_payoff_task( + debts, interest_rates, minimum_payments, monthly_payment + ) # Endpoint to calculate future value of the ordinary annuity @@ -1359,19 +879,7 @@ def credit_card_payoff( def future_value_of_ordinary_due( periodic_payment: float, number_of_periods: int, effective_interest_rate: float ): - try: - future_value_of_ordinary_due = functions.future_value_of_ordinary_due( - periodic_payment, number_of_periods, effective_interest_rate - ) - return { - "Tag": "Future value of the ordinary annuity", - "Periodic payment": periodic_payment, - "Number of periods": number_of_periods, - "Effective interest rate": effective_interest_rate, - "Number of periods": f"{future_value_of_ordinary_due}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return future_value_of_ordinary_due_task( periodic_payment, number_of_periods, effective_interest_rate) # Endpoint to calculate future value of the annuity due @@ -1383,19 +891,7 @@ def future_value_of_ordinary_due( def future_value_of_annuity_due( periodic_payment: float, number_of_periods: int, effective_interest_rate: float ): - try: - future_value_of_annuity_due = functions.future_value_of_annuity_due( - periodic_payment, number_of_periods, effective_interest_rate - ) - return { - "Tag": "Future value of the ordinary annuity", - "Periodic payment": periodic_payment, - "Number of periods": number_of_periods, - "Effective interest rate": effective_interest_rate, - "Number of periods": f"{future_value_of_annuity_due}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return future_value_of_annuity_due_task( periodic_payment, number_of_periods, effective_interest_rate) # Endpoint to calculate present value of the annuity due @@ -1407,19 +903,7 @@ def future_value_of_annuity_due( def present_value_of_annuity_due( periodic_payment: float, number_of_periods: int, rate_per_period: float ): - try: - present_value_of_annuity_due = functions.present_value_of_annuity_due( - periodic_payment, number_of_periods, rate_per_period - ) - return { - "Tag": "Present value of annuity due", - "Periodic payment": periodic_payment, - "Number of periods": number_of_periods, - "Rate Per Period": rate_per_period, - "PV of Annuity Due": f"{present_value_of_annuity_due}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return present_value_of_annuity_due_task( periodic_payment, number_of_periods, rate_per_period) @app.get( @@ -1430,19 +914,9 @@ def present_value_of_annuity_due( def compound_annual_growth_rate_1( ending_value: float, beginning_value: float, number_of_periods: float ): - try: - cagr = functions.compound_annual_growth_rate_1( - ending_value, beginning_value, number_of_periods - ) - return { - "Tag": "compound annual growth rate 1", - "ending_value": ending_value, - "beginning value": beginning_value, - "Number of periods": number_of_periods, - "compound annual growth rate": f"{cagr}%", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return compound_annual_growth_rate_1_task( + ending_value, beginning_value, number_of_periods + ) # Endpoint to calculate loan to value @@ -1452,16 +926,7 @@ def compound_annual_growth_rate_1( description="Calculating loan to value ratio", ) def loan_to_value(mortgage_value: float, appraised_value: float): - try: - ratio = functions.loan_to_value(mortgage_value, appraised_value) - return { - "Tag": "Loan to Value (LTV) ratio", - "Mortgage Value": mortgage_value, - "Appraised Property Value": appraised_value, - "Loan to Value ratio": f"{ratio}%", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return loan_to_value_task(mortgage_value, appraised_value) # Endpoint to calculate retention ratio @@ -1471,16 +936,7 @@ def loan_to_value(mortgage_value: float, appraised_value: float): description="Calculating retention ratio", ) def retention_ratio(net_income: float, dividends: float): - try: - retention_ratio = functions.retention_ratio(net_income, dividends) - return { - "Tag": "Retention Ratio", - "Net Income": net_income, - "Dividends": dividends, - "Retention Ratio": retention_ratio, - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return retention_ratio_task(net_income, dividends) # Endpoint to calculate tax equivalent yield @@ -1490,17 +946,7 @@ def retention_ratio(net_income: float, dividends: float): description="Calculating tax equivalent yield", ) def tax_equivalent_yield(tax_free_yield: float, tax_rate: float): - try: - tax_equivalent_yield = functions.tax_equivalent_yield( - tax_free_yield, tax_rate) - return { - "Tag": "Tax Equivalent Yield", - "Tax Free Yield": tax_free_yield, - "Tax Rate": tax_rate, - "Tax Equivalent Yield": tax_equivalent_yield, - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return tax_equivalent_yield_task(tax_free_yield, tax_rate) # endpoint to calculate year over year growth @@ -1510,15 +956,7 @@ def tax_equivalent_yield(tax_free_yield: float, tax_rate: float): description="Calculating Year to Year Growth", ) def year_over_year(later_period_value: float, earlier_period_value: float): - try: - growth = functions.year_over_year( - later_period_value, earlier_period_value) - return { - "Tag": "Year to Year Growth", - "Year to Year growth": f"{growth}%", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return year_over_year_task(later_period_value, earlier_period_value) @app.get( @@ -1529,19 +967,9 @@ def year_over_year(later_period_value: float, earlier_period_value: float): def future_value_of_annuity( payments_per_period: float, interest_rate: float, number_of_periods: float ): - try: - fva = functions.future_value_of_annuity( - payments_per_period, interest_rate, number_of_periods - ) - return { - "Tag": "Future value of annuity", - "Payments per periods": payments_per_period, - "interest rate": interest_rate, - "number of periods": number_of_periods, - "future value of annuity": f"{fva}%", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return future_value_of_annuity_task( + payments_per_period, interest_rate, number_of_periods + ) # endpoint to calculate Balloon Balance of a Loan @@ -1556,20 +984,9 @@ def balloon_balance( rate_per_payment: float, number_of_payments: float, ): - try: - balloon_balance = functions.balloon_balance_of_loan( - present_value, payment, rate_per_payment, number_of_payments - ) - return { - "Tag": "Balloon Balance of a Loan", - "Present Value (Original Balance)": present_value, - "Payment": payment, - "Rate per Payment": rate_per_payment, - "Number of Payments": number_of_payments, - "Future Value (Balloon Balance)": balloon_balance, - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return balloon_balance_task( + present_value, payment, rate_per_payment, number_of_payments + ) # Endpoint to calculate Periodic lease payment @@ -1583,19 +1000,9 @@ def periodic_lease_payment( monthly_lease_interest_rate: float, number_of_lease_payments: float, ): - try: - pmt = functions.periodic_lease_payment( - Asset_value, monthly_lease_interest_rate, number_of_lease_payments - ) - return { - "Tag": "Periodic Lease Payment", - "Asset value": Asset_value, - "Monthly lease interest rate": monthly_lease_interest_rate, - "Number of lease payments": number_of_lease_payments, - "Periodic Lease Payment": f"{pmt}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return periodic_lease_payment_task( + Asset_value, monthly_lease_interest_rate, number_of_lease_payments + ) # Endpoint to calculate Weighted average @@ -1605,18 +1012,7 @@ def periodic_lease_payment( description="Calculating weighted average", ) def weighted_average_of_values(Assigned_weight_values: str, data_point_values: str): - try: - weighted_average = functions.weighted_average_of_values( - Assigned_weight_values, data_point_values - ) - return { - "Tag": "weighted_average", - "Assigned weight values": Assigned_weight_values, - "Data point values": data_point_values, - "Weighted average": f"{weighted_average}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return weighted_average_of_values_task(Assigned_weight_values, data_point_values) # endpoint to calculate discounted payback period @@ -1626,19 +1022,7 @@ def weighted_average_of_values(Assigned_weight_values: str, data_point_values: s description="Calculating discounted payback period", ) def discounted_payback_period(outflow: float, rate: float, periodic_cash_flow: float): - try: - discounted_payback_period = functions.discounted_payback_period( - outflow, rate, periodic_cash_flow - ) - return { - "Tag": "Discounted Payback Period", - "Initial Investment (Outflow)": outflow, - "Rate": rate, - "Periodic Cash Flow": periodic_cash_flow, - "Discounted Payback Period": discounted_payback_period, - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return discounted_payback_period_task(outflow, rate, periodic_cash_flow) # endpoint to calculate yield to maturity @@ -1650,18 +1034,9 @@ def discounted_payback_period(outflow: float, rate: float, periodic_cash_flow: f def yield_to_maturity( bond_price: float, face_value: float, coupon_rate: float, years_to_maturity: float ): - try: - yield_cal = functions.yield_to_maturity( - bond_price, face_value, coupon_rate, years_to_maturity - ) - return { - "Tag": "Yield To Maturity", - "Face Value": face_value, - "Years to maturity": years_to_maturity, - "Yield to Maturity": f"{yield_cal}%", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return yield_to_maturity_task( + bond_price, face_value, coupon_rate, years_to_maturity + ) # endpoint to calculate perpetuity payment @@ -1671,15 +1046,7 @@ def yield_to_maturity( description="Calculating perpetuity payment", ) def perpetuity_payment(present_value: float, rate: float): - try: - payment = functions.perpetuity_payment(present_value, rate) - return { - "Tag": "Perpetuity Payment", - "Present Value": present_value, - "Perpetuity Payment": f"{payment}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return perpetuity_payment_task(present_value, rate) # endpoint to calculate Zero Coupon Bond value @@ -1691,18 +1058,9 @@ def perpetuity_payment(present_value: float, rate: float): def zero_coupon_bond_value( face_value: float, rate_of_yield: float, time_of_maturity: float ): - try: - zcbv = functions.zero_coupon_bond_value( - face_value, rate_of_yield, time_of_maturity - ) - return { - "Tag": "Zero Coupon Bond Value", - "Face Value": face_value, - "Rate of yield": f"{rate_of_yield}%", - "Zero Coupon Bond Value": zcbv, - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return zero_coupon_bond_value_task( + face_value, rate_of_yield, time_of_maturity + ) # endpoint to calculate Zero Coupon Bond Effective Yield @@ -1714,19 +1072,7 @@ def zero_coupon_bond_value( def zero_coupon_bond_yield( face_value: float, present_value: float, time_of_maturity: float ): - try: - zcby = functions.zero_coupon_bond_yield( - face_value, present_value, time_of_maturity - ) - return { - "Tag": "Zero Coupon Bond Effective Yield", - "Face Value": face_value, - "Present Value": present_value, - "Time to maturity": time_of_maturity, - "Zero Coupon Bond Effective Yield": f"{zcby}%", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return zero_coupon_bond_yield_task(face_value, present_value, time_of_maturity) # Endpoint to calculate Profitability Index @@ -1736,18 +1082,7 @@ def zero_coupon_bond_yield( description="Calculating profitability index", ) def profitability_index(initial_investment: float, pv_of_future_cash_flows: float): - try: - profitability_index = functions.profitability_index( - initial_investment, pv_of_future_cash_flows - ) - return { - "Tag": "Profitability Index", - "Initial Investment": initial_investment, - "PV of Future Cash Flows": pv_of_future_cash_flows, - "Profitability Index": profitability_index, - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return profitability_index_task(initial_investment, pv_of_future_cash_flows) # Endpoint to calculate Profitability index using annual cash flows @@ -1759,19 +1094,7 @@ def profitability_index(initial_investment: float, pv_of_future_cash_flows: floa def profitability_index2( initial_investment: float, annual_cash_flows: str, discount_rate: float ): - try: - profitability_index = functions.profitability_index2( - initial_investment, annual_cash_flows, discount_rate - ) - return { - "Tag": "profitability_index", - "initial_investment": initial_investment, - "annual_cash_flows": annual_cash_flows, - "discount_rate": discount_rate, - "profitability index": f"{profitability_index}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return profitability_index2_task(initial_investment, annual_cash_flows, discount_rate) # Endpoint to calculate Receivables Turnover Ratio @@ -1781,18 +1104,7 @@ def profitability_index2( description="Calculating receivables turnover ratio", ) def receivables_turnover_ratio(sales_revenue: float, avg_accounts_receivable: float): - try: - receivables_turnover_ratio = functions.receivables_turnover_ratio( - sales_revenue, avg_accounts_receivable - ) - return { - "Tag": "Receivables Turnover Ratio", - "Sales Revenue": sales_revenue, - "Avg Accounts Receivables": avg_accounts_receivable, - "Receivables Turnover Ratio": receivables_turnover_ratio, - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return receivables_turnover_ratio_task(sales_revenue, avg_accounts_receivable) @app.get( @@ -1806,23 +1118,12 @@ def remaining_balance( number_of_payments: float, number_of_payments_done: float, ): - try: - B = functions.remaining_balance( - regular_payment, - interest_rate_per_period, - number_of_payments, - number_of_payments_done, - ) - return { - "Tag": "Remaining balance", - "regular_payment": regular_payment, - "interest rate per period": interest_rate_per_period, - "number of payments": number_of_payments, - "number of payments done": number_of_payments_done, - "remaining balance": B, - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return remaining_balance_task( + regular_payment, + interest_rate_per_period, + number_of_payments, + number_of_payments_done, + ) # Endpoint to calculate net present value @@ -1832,19 +1133,7 @@ def remaining_balance( description="Calculating net present value", ) def net_present_value(cash_flows: str, discount_rate: float, initial_investment: float): - try: - net_present_value = functions.net_present_value( - cash_flows, discount_rate, initial_investment - ) - return { - "Tag": "Net present value", - "cash flows": cash_flows, - "discount rate": discount_rate, - "initial investment": initial_investment, - "Net present value": net_present_value, - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return net_present_value_task(cash_flows, discount_rate, initial_investment) # Endpoint to Calculate Leverage Ratio By Income @@ -1854,17 +1143,7 @@ def net_present_value(cash_flows: str, discount_rate: float, initial_investment: description="Calculate Leverage Ratio", ) def leverage_income(debt_payments: int, income: int): - try: - leverage_ratio = functions.leverage_income(debt_payments, income) - - return { - "Tag": "Leverage Ratio By Income", - "Debt ": debt_payments, - "Income": income, - "Leverage Ratio": f"{leverage_ratio}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return leverage_income_task(debt_payments, income) # Endpoint to Calculate Leverage Ratio By equity @@ -1874,17 +1153,7 @@ def leverage_income(debt_payments: int, income: int): description="Calculate Leverage Ratio", ) def leverage_equity(debt_payments: int, equity: int): - try: - leverage_ratio = functions.leverage_equity(debt_payments, equity) - - return { - "Tag": "Leverage Ratio By Equity", - "Debt ": debt_payments, - "Equity": equity, - "Leverage Ratio": f"{leverage_ratio}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return leverage_equity_task(debt_payments, equity) # Endpoint to calculate the time period required for exponential growth @@ -1894,42 +1163,20 @@ def leverage_equity(debt_payments: int, equity: int): description="Calculating the time period required for exponential growth", ) def time_period_required_for_growth(interest_rate: float, growth_factor: int): - try: - time_period_required_for_growth = functions.time_period_required_for_growth( - interest_rate, growth_factor - ) - return { - "Tag": "Time period required for exponential growth", - "interest rate": interest_rate, - "growth factor": growth_factor, - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return time_period_required_for_growth_task(interest_rate, growth_factor) # Endpoint to calculate preferred stock value @app.get( - "/preferred-stock-value", + "/preferred_stock_value", tags=["preferred_stock_value"], description="Calculating the preferred stock value", ) def preferred_stock_value(dividend: float, discount_rate: float): - try: - preferred_stock_value = functions.preferred_stock_value( - dividend, discount_rate) - return { - "Tag": "Preferred stock value", - "Dividend": dividend, - "Discount Rate": discount_rate, - "Preferred Stock Value": preferred_stock_value, - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) - - # Endpoint to calculate asset turnover ratio + return preferred_stock_value_task(dividend, discount_rate) -# Indentation error corrected +# Endpoint to calculate asset turnover ratio @app.get( "/asset_turnover_ratio", tags=["asset_turnover_ratio"], @@ -1938,20 +1185,7 @@ def preferred_stock_value(dividend: float, discount_rate: float): def asset_turnover_ratio( net_sales: float, total_asset_beginning: float, total_asset_ending: float ): - try: - asset_turnover_ratio = functions.asset_turnover_ratio( - net_sales, total_asset_beginning, total_asset_ending - ) - return { - "Tag": "Asset Turnover Ratio", - "Net Sales": net_sales, - "Total beginning asset": total_asset_beginning, - "Total ending asset": total_asset_ending, - "Total average asset": (total_asset_beginning + total_asset_ending) / 2, - "Asset Turnover Ratio": f"{asset_turnover_ratio}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return asset_turnover_ratio_task(net_sales, total_asset_beginning, total_asset_ending) # Endpoint to calculate Bid Ask Spread @@ -1961,16 +1195,7 @@ def asset_turnover_ratio( description="Calculating the Bid Ask Spread", ) def bid_ask_spread(ask_price: float, bid_price: float): - try: - bid_ask_spread = functions.bid_ask_spread(ask_price, bid_price) - return { - "Tag": "Bid Ask Spread", - "Ask Price": ask_price, - "Bid Price": bid_price, - "Bid Ask Spread": bid_ask_spread, - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return bid_ask_spread_task(ask_price, bid_price) @app.get( @@ -1979,16 +1204,7 @@ def bid_ask_spread(ask_price: float, bid_price: float): description="Calculating 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): - try: - period = functions.CalculatePeriods(present_val, future_val, rate) - return { - "Tag": "Period in years ", - "Present Value": present_val, - "Future Value": future_val, - "Periods": period, - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return CalculatePeriods_task(present_val, future_val, rate) @app.get( @@ -2002,21 +1218,9 @@ def balloon_loan_payment( term_years: float, balloon_payment_year: float, ): - try: - balloon_loan_payment = functions.balloon_loan_payment( - principal, interest_rate, term_years, balloon_payment_year - ) - return { - "Tag": "Balloon Loan Payment", - "Principal": principal, - "Interest Rate": interest_rate, - "Term Years": term_years, - "Balloon Payment Year": balloon_payment_year, - "Balloon Loan Payment": balloon_loan_payment, - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) - + return balloon_loan_payment_task( + principal, interest_rate, term_years, balloon_payment_year + ) # Endpoint to calculate monthly lease payment @app.get( @@ -2029,19 +1233,9 @@ def monthly_lease_payment( monthly_lease_interest_rate: float, number_of_lease_payments: float, ): - try: - pmt = functions.monthly_lease_payment( - Asset_value, monthly_lease_interest_rate, number_of_lease_payments - ) - return { - "Tag": "Monthly Lease Payment", - "Asset value": Asset_value, - "Monthly lease interest rate": monthly_lease_interest_rate, - "Number of lease payments": number_of_lease_payments, - "Monthly Lease Payment": f"{pmt}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return monthly_lease_payment_task( + Asset_value, monthly_lease_interest_rate, number_of_lease_payments + ) # End point to calculate 401k @@ -2059,31 +1253,7 @@ def estimate_401k( salary_increase_rate: float, withdraw_tax_rate: float, ): - try: - estimated_401k = functions.calculate_401k( - income, - contribution_percentage, - current_age, - age_at_retirement, - rate_of_return, - salary_increase_rate, - ) - return { - "Tag": "Estimated 401(k)", - "income": income, - "contribution_percentage": contribution_percentage, - "current_age": current_age, - "age_at_retirement": age_at_retirement, - "rate_of_return": rate_of_return, - "withdraw_tax_rate": withdraw_tax_rate, - "estimated_401k": estimated_401k, - "annual_withdraw_amount": round( - functions.percent_to_decimal( - withdraw_tax_rate) * estimated_401k, 3 - ), - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return estimate_401k_task( income, contribution_percentage, current_age, age_at_retirement, rate_of_return, salary_increase_rate, withdraw_tax_rate) @app.get( @@ -2098,22 +1268,7 @@ def roth_ira( tax_rate: float, annual_contribution: float, ): - try: - roth_ira_balance, taxable_saving_balance = functions.roth_ira( - principal, interest_rate, years, tax_rate, annual_contribution - ) - return { - "Tag": "Roth-IRA", - "Principal": principal, - "Interest Rate": interest_rate, - "Years": years, - "Tax Rates": tax_rate, - "Annual Contributions": annual_contribution, - "Roth Ira Balance": roth_ira_balance, - "Taxable saving Balance": taxable_saving_balance, - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return roth_ira_task(principal, interest_rate, years, tax_rate, annual_contribution) # Endpoint to calculate Mortgage Amortization @@ -2128,21 +1283,7 @@ def mortgage_amortization( annual_interest_rate: float, loan_term: int, ): - try: - annual_payment = functions.calculate_mortgage_interest( - mortgage_amount, mortgage_deposit, annual_interest_rate, loan_term - ) - return { - "TAG": "Mortgage monthly payments", - "mortgage_amount": mortgage_amount, - "mortgage_deposit": mortgage_deposit, - "annual_interest_rate": annual_interest_rate, - "loan_term": loan_term, - "monthly_payment": round(annual_payment / 12, 3), - "annual_payment": round(annual_payment, 3), - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return mortgage_amortization_task(mortgage_amount, mortgage_deposit, annual_interest_rate, loan_term) # Endpoint to calculate FHA loans @@ -2158,44 +1299,7 @@ def fha_loan( fha_annual_interest_rate: float, loan_term: int, ): - try: - ( - upfront_mip, - monthly_payment, - monthly_mip, - total_fha_loan_payment, - total_monthly_payment, - total_loan_cost, - ) = functions.calculate_fha_mortgage_interest( - mortgage_amount, - mortgage_deposit_percentage, - annual_interest_rate, - fha_annual_interest_rate, - loan_term, - ) - return { - "TAG": "FHA Mortgage monthly payments", - "mortgage_amount": mortgage_amount, - "mortgage_deposit": functions.percent_to_decimal( - mortgage_deposit_percentage - ) - * mortgage_amount - * 0.1, - "FHA base loan amount": mortgage_amount - - ( - functions.percent_to_decimal(mortgage_deposit_percentage) - * mortgage_amount - * 0.1 - ), - "FHA upfront MIP": upfront_mip, - "FHA monthly mortgage payments": monthly_payment, - "FHA Monthly MIP": monthly_mip, - "Total FHA loan amount": total_fha_loan_payment, - "Total monthly payments": total_monthly_payment, - "Total loan costs": total_loan_cost, - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return fha_loan_task(mortgage_amount, mortgage_deposit_percentage, annual_interest_rate, fha_annual_interest_rate, loan_term) # Endpoint to calculate Enterprise Value @@ -2212,26 +1316,7 @@ def calculate_enterprise_value( non_controlling_interest: float, cash_and_cash_equivalents: float, ): - try: - enterprise_value = functions.calculate_enterprise_value( - share_price, - fully_diluted_shares_outstanding, - total_debt, - preferred_stock, - non_controlling_interest, - cash_and_cash_equivalents, - ) - return { - "Tag": "Enterprise Value", - "Equity Value": share_price * fully_diluted_shares_outstanding, - "Total Debt": total_debt, - "Preferred Stock": preferred_stock, - "Non-Controlling Interest": non_controlling_interest, - "Cash & Cash Equivalents": cash_and_cash_equivalents, - "Enterprise Value": enterprise_value, - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return calculate_enterprise_value_task(share_price, fully_diluted_shares_outstanding, total_debt, preferred_stock, non_controlling_interest, cash_and_cash_equivalents) # Endpoint to calculate Salary @@ -2246,19 +1331,7 @@ def salary_calculate( hours_worked_per_day: int, days_worked_per_week: int, ): - try: - salary = functions.salary_calculate( - salary_amount, payment_frequency, hours_worked_per_day, days_worked_per_week - ) - - return { - "Tag": "Calculate Salary", - "Salary Amount": salary_amount, - "Payment frequency": payment_frequency, - "Salary": salary, - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return salary_calculate_task(salary_amount, payment_frequency, hours_worked_per_day, days_worked_per_week) @app.get( @@ -2269,37 +1342,14 @@ def salary_calculate( def personal_loan( loan_amount: float, interest_rate: float, loan_term_years: int, loan_start_date: str ): - try: - result = functions.personal_loan( - loan_amount, interest_rate, loan_term_years, loan_start_date - ) - return { - "Tag": "Personal Loan", - "Loan amount": loan_amount, - "Monthly payment": round(result["Monthly payment"], 2), - "Total interest paid": round(result["Total interest paid"], 2), - "Total cost loan": round(result["Total cost loan"], 2), - "Schedule": result["Schedule"], - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return personal_loan_task(loan_amount, interest_rate, loan_term_years, loan_start_date) # Endpoint to calculate lump-sum mutual fund investment @app.get("/lumpsum") async def calculate_lumpsum(principal: float, interest_rate: float, years: int): - try: - total_amount = principal * ( - (1 + functions.percent_to_decimal(interest_rate)) ** years - ) - interest_earned = total_amount - principal - return { - "total_amount": round(total_amount, 2), - "interest_earned": round(interest_earned, 2), - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return calculate_lumpsum_task(principal, interest_rate, years) # Endpoint to calculate FHA loan @@ -2311,26 +1361,13 @@ async def fha_loan( interest_rate: float, fha_annual_mip_percentage: float, ): - try: - result = functions.calculate_fha_loan( - home_price, - down_payment_percentage, - loan_term_years, - interest_rate, - fha_annual_mip_percentage, - ) - return { - "down_payment": result["down_payment"], - "fha_base_loan_amount": result["fha_base_loan_amount"], - "fha_upfront_mip": result["fha_upfront_mip"], - "monthly_mortgage_payment": result["monthly_mortgage_payment"], - "monthly_mip": result["monthly_mip"], - "total_fha_loan_amount": result["total_fha_loan_amount"], - "total_monthly_payment": result["total_monthly_payment"], - "total_cost_of_loan": result["total_cost_of_loan"], - } - except Exception as e: - raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return fha_loan_task( + home_price, + down_payment_percentage, + loan_term_years, + interest_rate, + fha_annual_mip_percentage, + ) # Endpoint to calculate refinance @@ -2348,35 +1385,15 @@ def refinance( new_loan_term_years: int, cash_out_amount: float, ): - try: - result = functions.refinance_calculator( - current_loan_amount, - current_interest_rate, - current_loan_term_years, - time_remaining_years, - new_interest_rate, - new_loan_term_years, - cash_out_amount, - ) - return { - "Tag": "Refinance", - "Current loan amount": current_loan_amount, - "Balance left on loan": round(result["Balance left on loan"], 2), - "New loan amount": round(result["New loan amount"], 2), - "Current monthly payment": round(result["Current monthly payment"], 2), - "New monthly payment": round(result["New monthly payment"], 2), - "Monthly savings": round(result["Monthly savings"], 2), - "Current interest paid left": round( - result["Current left interest paid"], 2 - ), - "New total interest paid": round(result["New total interest paid"], 2), - "Total interest saving": round(result["Total interest saving"], 2), - "Current total cost left": round(result["Current total cost left"], 2), - "New total cost loan": round(result["New total cost loan"], 2), - "Total cost saving": round(result["Total cost saving"], 2), - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return refinance_task( + current_loan_amount, + current_interest_rate, + current_loan_term_years, + time_remaining_years, + new_interest_rate, + new_loan_term_years, + cash_out_amount, + ) # Endpoint to compute any one of the following, given inputs for the remaining two: sales price, commission rate, or commission. @@ -2388,33 +1405,7 @@ def refinance( def commission_calc( sales_price: float = None, commission_rate: float = None, commission: float = None ): - try: - output = functions.commission_calc( - sales_price, commission_rate, commission) - - if sales_price == None and commission_rate != None and commission != None: - return { - "Tag": "Sales Price", - "Sales Price": output, - "Commission Rate": f"{commission_rate}%", - "Commission": commission, - } - elif sales_price != None and commission_rate == None and commission != None: - return { - "Tag": "Commission Rate", - "Sales Price": sales_price, - "Commission Rate": f"{output}%", - "Commission": commission, - } - elif sales_price != None and commission_rate != None and commission == None: - return { - "Tag": "Commission", - "Sales Price": sales_price, - "Commission Rate": f"{commission_rate}%", - "Commission": output, - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return commission_calc_task(sales_price, commission_rate, commission) # Endpoint to compute Total college expenses @@ -2434,29 +1425,15 @@ def college_cost( mess_fee: float, miscellaneous: float, ): - try: - cost = functions.college_cost( - book_cost, - college_tuition, - Devices, - travel_expenses, - hostel_charges, - mess_fee, - miscellaneous, - ) - return { - "Tag": "College Cost", - "Books cost of one year": book_cost, - "College tuition fee per year": college_tuition, - "Electronic devices cost": Devices, - "Monthly Travel expenses": travel_expenses, - "Monthly Hostel charges": hostel_charges, - "Monthly mess fee": mess_fee, - "monthly miscellaneous expenses": miscellaneous, - "Total cost of one year": cost, - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return college_cost_task( + book_cost, + college_tuition, + Devices, + travel_expenses, + hostel_charges, + mess_fee, + miscellaneous, + ) # Endpoint to calculate Diluted EPS @@ -2470,19 +1447,7 @@ def calculate_diluted_eps( weighted_avg_shares: float, dilutive_securities: float, ): - try: - result = functions.diluted_eps( - net_income, weighted_avg_shares, dilutive_securities - ) - return { - "Tag": "Diluted Earnings Per Share (EPS)", - "Net Income": net_income, - "Weighted Average Shares Outstanding": weighted_avg_shares, - "Number of Dilutive Securities": dilutive_securities, - "Diluted EPS": f"{result}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return calculate_diluted_eps_task( net_income, weighted_avg_shares, dilutive_securities) # Endpoint to calculate maturity value for fixed deposit with intrest compounded. @@ -2500,20 +1465,11 @@ def calculate_roi_equity_funds( amount_returned: float, tenure: float, ): - try: - roi, annualized_roi = functions.calculate_roi_equity_funds( - amount_invested, amount_returned, tenure - ) - return { - "Tag": "Calculate return of investments on equity funds", - "Amount Invested": amount_invested, - "Amount Returned": amount_returned, - "Duration of investment": tenure, - "Return of Investment": f"{roi}%", - "Annualized Return": f"{annualized_roi}%", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return calculate_roi_equity_funds_task( + amount_invested, + amount_returned, + tenure, + ) # Endpoint to compute Student loan and monthly emi for the same @@ -2525,19 +1481,7 @@ def calculate_roi_equity_funds( description="Calculate Student loan", ) def student_loan(principal: int, tenure: int, interest_rate: float): - try: - student_loan = functions.student_loan(principal, tenure, interest_rate) - return { - "Tag": "Student Loan", - "Total amount to borrow": principal, - "total number of years to pay loan": tenure, - "interest rate percentage annual": interest_rate, - "total monthly cost": f"{student_loan[0]}", - "Total Amount of loan": f"{student_loan[1]}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) - + return student_loan_task(principal, tenure, interest_rate) @app.get( "/calculate_gst", @@ -2545,17 +1489,7 @@ def student_loan(principal: int, tenure: int, interest_rate: float): description="Calculate GST (Goods and Service Tax)", ) def calculate_gst(price, gst_rate): - try: - gst_amount, total_price = functions.calulate_gst(price, gst_rate) - return { - "Tag": "Calculate GST and Total Price", - "Original Price": price, - "GST rate": gst_rate, - "Amount of GST": f"{gst_amount}", - "Total price after GST": f"{total_price}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return calculate_gst_task(price, gst_rate) # Endpoint For calculated annual income needed during retiremnet period @@ -2571,25 +1505,13 @@ def calculate_retirement_goals( annual_retirement_income: int, current_age: int, ): - try: - amount = functions.calculate_retirement_goals( - retirement_age, - annual_retirement_expenses, - inflation_rate, - annual_retirement_income, - current_age, - ) - return { - "Tag": "Retirement Goals", - "Retirement age": retirement_age, - "Annual retirement expenses": annual_retirement_expenses, - "inflation rate": inflation_rate, - "Annual Retirement Income": annual_retirement_income, - "Current Age": current_age, - "Retirement Goals": f"{amount}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return calculate_retirement_goals_task( + retirement_age, + annual_retirement_expenses, + inflation_rate, + annual_retirement_income, + current_age, + ) # Endpoint for calculating marketcap value @@ -2602,18 +1524,7 @@ def calculate_retirement_goals( def calculate_market_cap( current_market_share_price: int, total_number_of_shares_outstanding: int ): - try: - calculate = functions.calculate_market_cap( - current_market_share_price, total_number_of_shares_outstanding - ) - return { - "Tag": "Market capitalization value", - "Current market share price": current_market_share_price, - "Total number of shares outstanding": total_number_of_shares_outstanding, - "Marketcap value": f"{calculate}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return calculate_market_cap_task( current_market_share_price, total_number_of_shares_outstanding) # Endpoint to calculate Annual Debt Service Coverage Ratio (ADSCR) @@ -2628,21 +1539,7 @@ def asdcr( non_cash_expenses: float, annual_debt_service: float, ): - try: - asdcr_debt = functions.annual_debt_service_coverage_ratio( - net_operating_cost, depreciation, non_cash_expenses, annual_debt_service - ) - return { - "Tag": "Annual Debt Service Coverage Ratio", - "Annual Debt Ratio": asdcr_debt, - "Net Operating Income": net_operating_cost, - "Depreciation": depreciation, - "Non Cash Expenses": non_cash_expenses, - "Annual Debt": annual_debt_service, - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) - + return asdcr_task( net_operating_cost, depreciation, non_cash_expenses, annual_debt_service) # Endpoint to calculate Value Added Tax (VAT) @app.get( @@ -2651,21 +1548,7 @@ def asdcr( description="Calculate VAT for both excluding and including amounts", ) async def calculate_vat(price: float, vat_rate: float): - try: - excluding_vat = price / (1 + functions.percent_to_decimal(vat_rate)) - including_vat = price - vat_amount = price - excluding_vat - - return { - "Price (excluding VAT)": excluding_vat, - "Price (including VAT)": including_vat, - "VAT Amount": vat_amount, - } - except Exception as e: - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail="An error occurred during VAT calculation", - ) + return calculate_vat_task(price, vat_rate) # Endpoint For calculating bond equivalent yield @@ -2677,19 +1560,7 @@ async def calculate_vat(price: float, vat_rate: float): def bond_equivalent_yield( face_value: float, purchase_price: float, days_to_maturity: int ): - try: - bey = functions.calculate_bond_equivalent_yield( - face_value, purchase_price, days_to_maturity - ) - return { - "Tag": "Bond Equivalent Yield", - "Face value": face_value, - "Purchase Price": purchase_price, - "Days to maturity": days_to_maturity, - "Bond Equivalent Yield (BEY)": f"{functions.decimal_to_percent(bey)}%", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return bond_equivalent_yield_task( face_value, purchase_price, days_to_maturity) @app.get("/loan-affordability") @@ -2699,40 +1570,9 @@ def calculate_loan_affordability( loan_term: int, # loan term period interest_rate: float, # annual interest rate ): - """ - This endpoint is use to check your ability to take any particular Loan on the Basis on - your income,expenses,loan_term,intrest_rate, This is basically loan affordability function - - eg url :- http://127.0.0.1:8000/loan-affordability?income=5000&expenses=2000&loan_term=12&interest_rate=5 - - explanation for calculating max_loan_amount :- - (1 + utils.percent_to_decimal(interest_rate)): This calculates the factor by which the loan amount increases due to the interest rate. For example, if the interest rate is 5%, this factor would be 1.05. - ** -loan_term: This raises the above factor to the power of negative loan_term. It represents the compounding effect of interest over the loan term. For example, if the loan term is 12 months, this factor would be (1.05) ** -12 - (1 - (1 + utils.percent_to_decimal(interest_rate)) ** -loan_term): This calculates the ratio of the remaining loan balance after making monthly payments to the initial loan amount. It represents the discounted value of the loan. - (monthly_income - monthly_expenses): This calculates the disposable income available for loan repayment each month. - (monthly_income - monthly_expenses) * (1 - (1 + utils.percent_to_decimal(interest_rate)) ** -loan_term): This calculates the discounted monthly loan payment amount based on the available disposable income. - - """ - try: - # monthly_income = income / 12 - # monthly_expenses = expenses / 12 - - max_loan_amount = functions.calculate_max_loan_amount( - income, expenses, loan_term, interest_rate - ) - - return { - "income": income, - "expenses": expenses, - "loan_term": loan_term, - "interest_rate": interest_rate, - "max_loan_amount": max_loan_amount, - } - except: - return HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail="Some Error occured", - ) + return calculate_loan_affordability_task( + income, expenses, loan_term, interest_rate + ) @app.get( @@ -2741,19 +1581,7 @@ def calculate_loan_affordability( description="Calculate BVPS (Book value per share)", ) def calculate_bvps(stockholders_equity, preferred_stock, average_outstanding_shares): - try: - book_value = functions.calulate_bvps( - stockholders_equity, preferred_stock, average_outstanding_shares - ) - return { - "Tag": "Calculate Book value per share", - "Stockholders Equity": stockholders_equity, - "Preferred Stock value": preferred_stock, - "Average outstanding shares": average_outstanding_shares, - "Book value per share": f"{book_value}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return calculate_bvps_task(stockholders_equity, preferred_stock, average_outstanding_shares) @app.get( @@ -2762,28 +1590,7 @@ def calculate_bvps(stockholders_equity, preferred_stock, average_outstanding_sha description="Calculate gratuity", ) def calculate_gratuity(last_salary: float, tenure_years: int, tenure_months: int): - """ - Gratuity in India refers to the amount payable to an employee who has rendered his / her services - to the company for a minimum period of five years (continuously) - Partial years in the tenure are rounded off to 1 if the number of months is greater than 6. - Last salary includes the basic salary and the dearness allowanace - Gratuity is calculated as: (15 * last salary * tenure in years) / 26 - - Inputs: last drawn salary, tenure in years, last partial year in months - """ - try: - gratuity = functions.calculate_gratuity( - last_salary, tenure_years, tenure_months - ) - return { - "Tag": "Gratuity", - "Last salary (basic + dearness allowance)": last_salary, - "Tenure in years (excluding last partial year)": tenure_years, - "Last partial year in months": tenure_months, - "Gratuity Amount": f"{gratuity}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return calculate_gratuity_task(last_salary, tenure_years, tenure_months) @app.get( @@ -2794,17 +1601,7 @@ def calculate_gratuity(last_salary: float, tenure_years: int, tenure_months: int def personal_savings(init: int, monthly: int, tenure: float): - try: - personal_savings = functions.personal_savings(init, monthly, tenure) - return { - "Tag": "Simple Personal Savings", - "Initial Deposit": init, - "total number of years": tenure, - "Monthly Contribution": monthly, - "Total Amount Saved": f"{total_amount}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return personal_savings_task(init, monthly, tenure) @app.get( @@ -2820,46 +1617,15 @@ def accrued_interest( frequency: int = 1, basis: int = 0, ): - try: - accr_int = functions.accrint( - issue_date, settlement_date, rate, par, frequency, basis - ) - return { - "Tag": "Accrued Interest", - "Issue Date": issue_date, - "Settlement Date": settlement_date, - "Rate": rate, - "Par": par, - "Frequency": frequency, - "Basis": basis, - "Accrued Interest": accr_int, - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return accrued_interest_task( + issue_date, settlement_date, rate, par, frequency, basis + ) @app.get('/mortrages', tags=["mortrage"], description="Endpoint to calculate Mortrages") def mortrage(princial: int, interest_rate: float, years: int, down_payment: int, property_tax_rate: float, insurance_rate: float): - try: - mortrage = functions.calculate_mortgage( - principal=princial, - interest_rate=interest_rate, - years=years, - down_payment=down_payment, - property_tax_rate=property_tax_rate, - insurance_rate=insurance_rate - ) - return { - "Monthly Payment": mortrage['monthly_payment'], - "Total Payment": mortrage['total_payment'], - "Total Property Tax": mortrage['total_property_tax'], - "Total insurance cost": mortrage['total_insurance_cost'], - "Total Cost": mortrage['total_cost'], - "Loan to value ratio": mortrage["loan_to_value_ratio"] - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return mortrage_task(princial, interest_rate, years, down_payment, property_tax_rate, insurance_rate) @app.get( @@ -2873,21 +1639,7 @@ def calculate_net_profit_margin(revenue: float, other_expenses: float, interest: float, taxes: float): - try: - net_profit_margin = functions.calulate_net_profit_margin( - revenue, cost_of_goods_sold, operating_expenses, other_expenses, interest, taxes) - return { - "Tag": "Calculate net profit margin", - "Revenue": revenue, - "Cost of goods sold": cost_of_goods_sold, - "Operating Expenses": operating_expenses, - "Interest": interest, - "Taxes": taxes, - "Net Profit Margin": net_profit_margin, - - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return calculate_net_profit_margin_task(revenue, cost_of_goods_sold, operating_expenses, other_expenses, interest, taxes) @app.get( @@ -2898,18 +1650,7 @@ def calculate_net_profit_margin(revenue: float, def calculate_expected_return_of_portfolio(no_of_investments: int, investment_amount: list, rate_of_return: list): - try: - expected_return_of_portfolio = functions.calculate_expected_return_of_portfolio( - no_of_investments, investment_amount, rate_of_return) - return { - "Tag": "Calculate expected return of portfolio", - "No of investments": no_of_investments, - "Investment Amount": investment_amount, - "Rate of Return": rate_of_return - - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return calculate_expected_return_of_portfolio_task(no_of_investments, investment_amount, rate_of_return) # Endpoint to calculate Net annual salary of an employee @@ -2926,23 +1667,7 @@ def calculate_salary(base: int, bonus: int, ptax: int, deduction: int): - try: - calculate_salary = functions.calculate_salary( - base, jb, stock, pb, bonus, ptax, deduction) - return { - - "Tag": "Net Salary Calculator", - "Base Salary per month": base, - "joining bonus/retention bonus": jb, - "RSU/stock bonus": stock, - "performance bonus": pb, - "any additional bonus": bonus, - "tax percentage": ptax, - "any additional deduction": deduction, - "ctc calculated": f"{ctc}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return calculate_salary_task(base, jb, stock, pb, bonus, ptax, deduction) @app.get( @@ -2952,18 +1677,7 @@ def calculate_salary(base: int, ) def ss(birth_date: str, earnings: int, retirement_age: int): - try: - monthly_benefits, future_benefits = functions.calculate_social_security( - birth_date=birth_date, - earnings=earnings, - retirement_age=retirement_age - ) - return { - f"The monthly benefits are {monthly_benefits} and future benefits are {future_benefits}" - } - - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return ss_task(birth_date, earnings, retirement_age) @app.get( @@ -2974,18 +1688,7 @@ def ss(birth_date: str, earnings: int, retirement_age: int): def calculate_post_tax_return_percentage(tax_rate_percentage: float, annual_net_income: float, initial_cost_of_investment: float): - try: - post_tax_return_percentage = functions.calculate_post_tax_return_percentage( - tax_rate_percentage, annual_net_income, initial_cost_of_investment) - return { - "Tag": "Calculate post tax return percentage", - "Tax Rate Percentage": tax_rate_percentage, - "Annual net income": annual_net_income, - "Initial cost of investment": initial_cost_of_investment, - "Post tax return percentage": post_tax_return_percentage - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return calculate_post_tax_return_percentage_task(tax_rate_percentage, annual_net_income, initial_cost_of_investment) # Endpoint for function Treynor Ratio @@ -2997,19 +1700,7 @@ def calculate_post_tax_return_percentage(tax_rate_percentage: float, def treynor_ratio( returns: list[float], risk_free_rate: float, beta: float ): - try: - ratio = functions.calculate_treynor_ratio( - returns, risk_free_rate, beta) - return { - "Tag": "Treynor Ratio", - "Returns": returns, - "Risk-free Rate": risk_free_rate, - "Beta": beta, - "Treynor Ratio": ratio, - } - except Exception as e: - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e)) + return treynor_ratio_task(returns, risk_free_rate, beta) # Endpoint for function Loan to Value Ratio @@ -3020,16 +1711,7 @@ def treynor_ratio( description="Calculate loan amount to value of collateral ratio", ) def loan_to_value_ratio(loan_amount: float, value_of_collateral: float): - try: - ratio = functions.loan_to_value_ratio(loan_amount, value_of_collateral) - return { - "Tag": "Loan to Value Ratio", - "Loan Amount": loan_amount, - "Value Of Collateral": value_of_collateral, - "Loan to Value Ratio": f"{ratio}%", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return loan_to_value_ratio_task(loan_amount, value_of_collateral) # Endpoint for function Free Cash Flow To Equity @@ -3050,39 +1732,7 @@ def free_cash_flow_to_equity( current_liabilities: float, amount_a_company_borrows: float, debt_it_repays: float): - try: - fcfe = functions.free_cash_flow_to_equity( - total_revenues, total_expenses, initial_cost_of_asset, lifetime_of_asset, - change_in_PPE, current_depreciation, current_assets, current_liabilities, - amount_a_company_borrows, debt_it_repays - ) - net_income = total_revenues - total_expenses, - depreciation_and_amortization = initial_cost_of_asset / lifetime_of_asset, - capEx = change_in_PPE + current_depreciation, - change_in_working_capital = current_assets - current_liabilities, - net_borrowing = amount_a_company_borrows - debt_it_repays, - - return { - "Tag": "Free Cash Flow to Equity", - "Total Revenues": total_revenues, - "Total Expenses": total_expenses, - "Inital Cost of Asset": initial_cost_of_asset, - "Life Time of Asset": lifetime_of_asset, - "Change in Price, Property or Equity": change_in_PPE, - "Current Depreciation": current_depreciation, - "Current Assets": current_assets, - "Current Liabilities": current_liabilities, - "Amount a Company Borrows": amount_a_company_borrows, - "Debt it Repays": debt_it_repays, - "Net Income": net_income, - "Depreciation and Amortization": depreciation_and_amortization, - "Capital Expenditures": capEx, - "Change in Working Capital": change_in_working_capital, - "Net Borrowing": net_borrowing, - "Free Cash Flow to Equity": fcfe - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return free_cash_flow_to_equity_task( total_revenues, total_expenses, initial_cost_of_asset, lifetime_of_asset, change_in_PPE, current_depreciation, current_assets, current_liabilities, amount_a_company_borrows, debt_it_repays) @app.get( "/net_worth", @@ -3090,17 +1740,7 @@ def free_cash_flow_to_equity( description="Calculate net worth", ) def net_worth_calculation(assets: float, liabilities: float, loans: float, mortgages: float): - try: - total_liabilities = liabilities + loans + mortgages - net_worth = assets - total_liabilities - return { - "Tag": "Net Worth", - "Assets": assets, - "Liabilities": total_liabilities, - "Net Worth": net_worth, - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return net_worth_calculation_task(assets, liabilities, loans, mortgages) ## Endpoint for function Capital Gains Yield @@ -3111,16 +1751,7 @@ def net_worth_calculation(assets: float, liabilities: float, loans: float, mortg description="Calculate Capital Gains Yield of a Stock", ) def capital_gains_yield(inital_price: float, price_after_first_period: float): - try: - gains_yield = functions.capital_gains_yield(inital_price, price_after_first_period) - return { - "Tag": "Capital Gains Yield", - "Inital Price of Stock": inital_price, - "Price of Stock After First Period": price_after_first_period, - "Capital Gains Yield": f"{gains_yield}%", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return capital_gains_yield_task(inital_price, price_after_first_period) @app.get( "/calculate_macaulay_duration", @@ -3135,23 +1766,7 @@ def calculate_macaulay_duration( Inputs: face value of bond, coupon rate, dt, month, year of maturity, coupon frequency, discount rate Ouput: Macaulay duration in years ''' - try: - duration = functions.calculate_gratuity( - face_value, coupon_rate, dt, month, year, coupon_frequency, discount_rate - ) - return { - "Tag": "Macaulay_duration", - "Face-value of bond": face_value, - "Coupon Rate (in decimal)": coupon_rate, - "Date of maturity(DD)": dt, - "Month of maturity(MM)": month, - "Year of maturity(YY)": year, - "Coupon frequency": coupon_frequency, - "Discount frequency (int decimal)": discount_rate, - "Macaulay duration": f"{duration}", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return calculate_macaulay_duration_task(face_value, coupon_rate, dt, month, year, coupon_frequency, discount_rate) @app.get( "/calculate_financial_leverage", @@ -3163,19 +1778,7 @@ def calculate_financial_leverage(total_assets : float, short_term_debt : float, long_term_debt : float ): - try: - financial_leverage = functions.calculate_financial_leverage( - total_assets, total_liabilities, short_term_debt, long_term_debt) - return { - "Tag": "Calculate financial leverage", - "Total Assets": total_assets, - "Total Liabilities": total_liabilities, - "Short term debt": short_term_debt, - "Long term debt": long_term_debt, - "Financial Leverage": financial_leverage, - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return calculate_financial_leverage_task(total_assets, total_liabilities, short_term_debt, long_term_debt) @app.get( @@ -3189,17 +1792,7 @@ def portfolio_return_monte_carlo(principal: float, volatility_range_start: float, volatility_range_end: float, num_simulations: float): - try: - portfolio_returns = functions.portfolio_return_monte_carlo(principal, expected_return_range_start,expected_return_range_end, volatility_range_start,volatility_range_end, num_simulations) - - return { - "Tag": "Portfolio Return Monte Carlo", - "Principal": principal, - "Number of Simulations": num_simulations, - "Portfolio Returns": f"{portfolio_returns}%" - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return portfolio_return_monte_carlo_task(principal, expected_return_range_start, expected_return_range_end, volatility_range_start, volatility_range_end, num_simulations) #Endpoint for function Capitalization Rate @app.get( @@ -3214,29 +1807,7 @@ def capitalization_rate( propertyTaxes:float, insurance: float, current_market_value: float): - try: - rate = functions.capitalization_rate(rental_income, amenities, propertyManagement, - propertyTaxes, insurance, current_market_value - ) - annual_income = rental_income + amenities, - expenses = propertyManagement + propertyTaxes + insurance, - net_operating_income = annual_income - expenses, - - return { - "Tag": "Capitalization Rate", - "Rental Income": rental_income, - "Amenities": amenities, - "Property Management": propertyManagement, - "Property Taxes": propertyTaxes, - "Insurance": insurance, - "Annual Income": annual_income, - "Expenses": expenses, - "Net Operating Income": net_operating_income, - "Current Market Value": current_market_value, - "Capitalization Rate": f"{rate}%" - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + return capitalization_rate_task(rental_income, amenities, propertyManagement, propertyTaxes, insurance, current_market_value) @app.get( "/accounts_payable_turnover_ratio", @@ -3246,16 +1817,4 @@ def capitalization_rate( def accounts_payable_turnover_ratio(total_supply_purchases: float, beginning_accounts_payable: float, ending_accounts_payable: float): - try: - ap_turnover_ratio = functions.accounts_payable_turnover_ratio(total_supply_purchases, - beginning_accounts_payable, - ending_accounts_payable) - return { - "Tag": "Accounts Payable Turnover Ratio", - "Total Supply Purchases": total_supply_purchases, - "Beginning Accounts Payable": beginning_accounts_payable, - "Ending Accounts Payable": ending_accounts_payable, - "Accounts Payable Turnover Ratio": ap_turnover_ratio - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file + return accounts_payable_turnover_ratio_task(total_supply_purchases, beginning_accounts_payable, ending_accounts_payable) \ No newline at end of file diff --git a/tasks/accounts_payable_turnover_ratio.py b/tasks/accounts_payable_turnover_ratio.py new file mode 100644 index 00000000..73ea0df9 --- /dev/null +++ b/tasks/accounts_payable_turnover_ratio.py @@ -0,0 +1,19 @@ +from helpers import functions +from fastapi import HTTPException, status + +def accounts_payable_turnover_ratio_task(total_supply_purchases: float, + beginning_accounts_payable: float, + ending_accounts_payable: float): + try: + ap_turnover_ratio = functions.accounts_payable_turnover_ratio(total_supply_purchases, + beginning_accounts_payable, + ending_accounts_payable) + return { + "Tag": "Accounts Payable Turnover Ratio", + "Total Supply Purchases": total_supply_purchases, + "Beginning Accounts Payable": beginning_accounts_payable, + "Ending Accounts Payable": ending_accounts_payable, + "Accounts Payable Turnover Ratio": ap_turnover_ratio + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/accrint.py b/tasks/accrint.py new file mode 100644 index 00000000..cc29bf34 --- /dev/null +++ b/tasks/accrint.py @@ -0,0 +1,27 @@ +from helpers import functions +from fastapi import HTTPException, status + +def accrued_interest_task( + issue_date: str, + settlement_date: str, + rate: float, + par: float, + frequency: int = 1, + basis: int = 0, +): + try: + accr_int = functions.accrint( + issue_date, settlement_date, rate, par, frequency, basis + ) + return { + "Tag": "Accrued Interest", + "Issue Date": issue_date, + "Settlement Date": settlement_date, + "Rate": rate, + "Par": par, + "Frequency": frequency, + "Basis": basis, + "Accrued Interest": accr_int, + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/acid_test_ratio.py b/tasks/acid_test_ratio.py new file mode 100644 index 00000000..7c827673 --- /dev/null +++ b/tasks/acid_test_ratio.py @@ -0,0 +1,23 @@ +from helpers import functions +from fastapi import HTTPException, status + +def acid_test_ratio_task( + cash: float, + marketable_securities: float, + accounts_receivable: float, + current_liabilities: float, +): + try: + ratio = functions.acid_test_ratio( + cash, marketable_securities, accounts_receivable, current_liabilities + ) + return { + "Tag": "Acid Test Ratio", + "Cash and Cash Equivalents": cash, + "Marketable Securities": marketable_securities, + "Accounts Receivable": accounts_receivable, + "Current Liabilities": current_liabilities, + "Acid Test Ratio (Quick Ratio)": f"{ratio}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/asdcr.py b/tasks/asdcr.py new file mode 100644 index 00000000..808bd4f8 --- /dev/null +++ b/tasks/asdcr.py @@ -0,0 +1,23 @@ +from helpers import functions +from fastapi import HTTPException, status + +def asdcr_task( + net_operating_cost: float, + depreciation: float, + non_cash_expenses: float, + annual_debt_service: float, +): + try: + asdcr_debt = functions.annual_debt_service_coverage_ratio( + net_operating_cost, depreciation, non_cash_expenses, annual_debt_service + ) + return { + "Tag": "Annual Debt Service Coverage Ratio", + "Annual Debt Ratio": asdcr_debt, + "Net Operating Income": net_operating_cost, + "Depreciation": depreciation, + "Non Cash Expenses": non_cash_expenses, + "Annual Debt": annual_debt_service, + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/asset_portfolio.py b/tasks/asset_portfolio.py new file mode 100644 index 00000000..0e351745 --- /dev/null +++ b/tasks/asset_portfolio.py @@ -0,0 +1,31 @@ +from helpers import functions +from fastapi import HTTPException, status + +def asset_portfolio_task( + price_A: float, + price_B: float, + return_A: float, + return_B: float, + standard_dev_A: float, + standard_dev_B: float, + correlation: float, +): + try: + weight_A = price_A / (price_A + price_B) + weight_B = price_B / (price_A + price_B) + cov = 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 + ) + expected_return = functions.decimal_to_percent( + weight_A * return_A + weight_B * return_B + ) + return { + "Tag": "Portfolio Variance", + "Expected Returns": f"{expected_return}%", + "Portfolio Variance": f"{portfolio_variance}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/asset_turnover_ratio.py b/tasks/asset_turnover_ratio.py new file mode 100644 index 00000000..fd7d427a --- /dev/null +++ b/tasks/asset_turnover_ratio.py @@ -0,0 +1,20 @@ +from helpers import functions +from fastapi import HTTPException, status + +def asset_turnover_ratio_task( + net_sales: float, total_asset_beginning: float, total_asset_ending: float +): + try: + asset_turnover_ratio = functions.asset_turnover_ratio( + net_sales, total_asset_beginning, total_asset_ending + ) + return { + "Tag": "Asset Turnover Ratio", + "Net Sales": net_sales, + "Total beginning asset": total_asset_beginning, + "Total ending asset": total_asset_ending, + "Total average asset": (total_asset_beginning + total_asset_ending) / 2, + "Asset Turnover Ratio": f"{asset_turnover_ratio}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/balloon_balance.py b/tasks/balloon_balance.py new file mode 100644 index 00000000..a0f56ef5 --- /dev/null +++ b/tasks/balloon_balance.py @@ -0,0 +1,23 @@ +from helpers import functions +from fastapi import HTTPException, status + +def balloon_balance_task( + present_value: float, + payment: float, + rate_per_payment: float, + number_of_payments: float, +): + try: + balloon_balance = functions.balloon_balance_of_loan( + present_value, payment, rate_per_payment, number_of_payments + ) + return { + "Tag": "Balloon Balance of a Loan", + "Present Value (Original Balance)": present_value, + "Payment": payment, + "Rate per Payment": rate_per_payment, + "Number of Payments": number_of_payments, + "Future Value (Balloon Balance)": balloon_balance, + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/balloon_loan_payment.py b/tasks/balloon_loan_payment.py new file mode 100644 index 00000000..a53f0cb0 --- /dev/null +++ b/tasks/balloon_loan_payment.py @@ -0,0 +1,23 @@ +from helpers import functions +from fastapi import HTTPException, status + +def balloon_loan_payment_task( + principal: float, + interest_rate: float, + term_years: float, + balloon_payment_year: float, +): + try: + balloon_loan_payment = functions.balloon_loan_payment( + principal, interest_rate, term_years, balloon_payment_year + ) + return { + "Tag": "Balloon Loan Payment", + "Principal": principal, + "Interest Rate": interest_rate, + "Term Years": term_years, + "Balloon Payment Year": balloon_payment_year, + "Balloon Loan Payment": balloon_loan_payment, + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/bep.py b/tasks/bep.py new file mode 100644 index 00000000..05b758db --- /dev/null +++ b/tasks/bep.py @@ -0,0 +1,18 @@ +from helpers import functions +from fastapi import HTTPException, status + +def break_even_point_task(fixed_cost: float, selling_price: float, variable_cost: float): + try: + + bep = functions.break_even_point( + fixed_cost, selling_price, variable_cost) + return { + "Tag": "Break Even Point (BEP)", + "Fixed costs": fixed_cost, + "Selling price per unit": selling_price, + "Variable cost per unit": variable_cost, + "Break Even Point in units": f"{bep[0]}", + "Break Even Point in Rupees": f"{bep[1]}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/bid_ask_spread.py b/tasks/bid_ask_spread.py new file mode 100644 index 00000000..3b58304f --- /dev/null +++ b/tasks/bid_ask_spread.py @@ -0,0 +1,14 @@ +from helpers import functions +from fastapi import HTTPException, status + +def bid_ask_spread_task(ask_price: float, bid_price: float): + try: + bid_ask_spread = functions.bid_ask_spread(ask_price, bid_price) + return { + "Tag": "Bid Ask Spread", + "Ask Price": ask_price, + "Bid Price": bid_price, + "Bid Ask Spread": bid_ask_spread, + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/bond_equivalent_yield.py b/tasks/bond_equivalent_yield.py new file mode 100644 index 00000000..8fbea09b --- /dev/null +++ b/tasks/bond_equivalent_yield.py @@ -0,0 +1,19 @@ +from helpers import functions +from fastapi import HTTPException, status + +def bond_equivalent_yield_task( + face_value: float, purchase_price: float, days_to_maturity: int +): + try: + bey = functions.calculate_bond_equivalent_yield( + face_value, purchase_price, days_to_maturity + ) + return { + "Tag": "Bond Equivalent Yield", + "Face value": face_value, + "Purchase Price": purchase_price, + "Days to maturity": days_to_maturity, + "Bond Equivalent Yield (BEY)": f"{functions.decimal_to_percent(bey)}%", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/calculate_bvps.py b/tasks/calculate_bvps.py new file mode 100644 index 00000000..c94cbb61 --- /dev/null +++ b/tasks/calculate_bvps.py @@ -0,0 +1,17 @@ +from helpers import functions +from fastapi import HTTPException, status + +def calculate_bvps_task(stockholders_equity, preferred_stock, average_outstanding_shares): + try: + book_value = functions.calulate_bvps( + stockholders_equity, preferred_stock, average_outstanding_shares + ) + return { + "Tag": "Calculate Book value per share", + "Stockholders Equity": stockholders_equity, + "Preferred Stock value": preferred_stock, + "Average outstanding shares": average_outstanding_shares, + "Book value per share": f"{book_value}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/calculate_expected_return_of_portfolio.py b/tasks/calculate_expected_return_of_portfolio.py new file mode 100644 index 00000000..a01abe86 --- /dev/null +++ b/tasks/calculate_expected_return_of_portfolio.py @@ -0,0 +1,18 @@ +from helpers import functions +from fastapi import HTTPException, status + +def calculate_expected_return_of_portfolio_task(no_of_investments: int, + investment_amount: list, + rate_of_return: list): + try: + expected_return_of_portfolio = functions.calculate_expected_return_of_portfolio( + no_of_investments, investment_amount, rate_of_return) + return { + "Tag": "Calculate expected return of portfolio", + "No of investments": no_of_investments, + "Investment Amount": investment_amount, + "Rate of Return": rate_of_return + + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/calculate_financial_leverage.py b/tasks/calculate_financial_leverage.py new file mode 100644 index 00000000..b9da1c3d --- /dev/null +++ b/tasks/calculate_financial_leverage.py @@ -0,0 +1,21 @@ +from helpers import functions +from fastapi import HTTPException, status + +def calculate_financial_leverage_task(total_assets : float, + total_liabilities : float, + short_term_debt : float, + long_term_debt : float + ): + try: + financial_leverage = functions.calculate_financial_leverage( + total_assets, total_liabilities, short_term_debt, long_term_debt) + return { + "Tag": "Calculate financial leverage", + "Total Assets": total_assets, + "Total Liabilities": total_liabilities, + "Short term debt": short_term_debt, + "Long term debt": long_term_debt, + "Financial Leverage": financial_leverage, + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/calculate_gratuity.py b/tasks/calculate_gratuity.py new file mode 100644 index 00000000..c311af11 --- /dev/null +++ b/tasks/calculate_gratuity.py @@ -0,0 +1,26 @@ +from helpers import functions +from fastapi import HTTPException, status + +def calculate_gratuity_task(last_salary: float, tenure_years: int, tenure_months: int): + """ + Gratuity in India refers to the amount payable to an employee who has rendered his / her services + to the company for a minimum period of five years (continuously) + Partial years in the tenure are rounded off to 1 if the number of months is greater than 6. + Last salary includes the basic salary and the dearness allowanace + Gratuity is calculated as: (15 * last salary * tenure in years) / 26 + + Inputs: last drawn salary, tenure in years, last partial year in months + """ + try: + gratuity = functions.calculate_gratuity( + last_salary, tenure_years, tenure_months + ) + return { + "Tag": "Gratuity", + "Last salary (basic + dearness allowance)": last_salary, + "Tenure in years (excluding last partial year)": tenure_years, + "Last partial year in months": tenure_months, + "Gratuity Amount": f"{gratuity}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/calculate_gst.py b/tasks/calculate_gst.py new file mode 100644 index 00000000..b9a5060b --- /dev/null +++ b/tasks/calculate_gst.py @@ -0,0 +1,15 @@ +from helpers import functions +from fastapi import HTTPException, status + +def calculate_gst_task(price, gst_rate): + try: + gst_amount, total_price = functions.calulate_gst(price, gst_rate) + return { + "Tag": "Calculate GST and Total Price", + "Original Price": price, + "GST rate": gst_rate, + "Amount of GST": f"{gst_amount}", + "Total price after GST": f"{total_price}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/calculate_macaulay_duration.py b/tasks/calculate_macaulay_duration.py new file mode 100644 index 00000000..6edf4261 --- /dev/null +++ b/tasks/calculate_macaulay_duration.py @@ -0,0 +1,28 @@ +from helpers import functions +from fastapi import HTTPException, status + +def calculate_macaulay_duration_task( + face_value : float, coupon_rate : float, dt : int, month : int, year : int, coupon_frequency : int, discount_rate : float +): + ''' + Macaulay duration is the weighted average term to maturity of the cash flows from a bond. + Inputs: face value of bond, coupon rate, dt, month, year of maturity, coupon frequency, discount rate + Ouput: Macaulay duration in years + ''' + try: + duration = functions.calculate_gratuity( + face_value, coupon_rate, dt, month, year, coupon_frequency, discount_rate + ) + return { + "Tag": "Macaulay_duration", + "Face-value of bond": face_value, + "Coupon Rate (in decimal)": coupon_rate, + "Date of maturity(DD)": dt, + "Month of maturity(MM)": month, + "Year of maturity(YY)": year, + "Coupon frequency": coupon_frequency, + "Discount frequency (int decimal)": discount_rate, + "Macaulay duration": f"{duration}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/calculate_market_cap.py b/tasks/calculate_market_cap.py new file mode 100644 index 00000000..86838e63 --- /dev/null +++ b/tasks/calculate_market_cap.py @@ -0,0 +1,18 @@ +from helpers import functions +from fastapi import HTTPException, status + +def calculate_market_cap_task( + current_market_share_price: int, total_number_of_shares_outstanding: int +): + try: + calculate = functions.calculate_market_cap( + current_market_share_price, total_number_of_shares_outstanding + ) + return { + "Tag": "Market capitalization value", + "Current market share price": current_market_share_price, + "Total number of shares outstanding": total_number_of_shares_outstanding, + "Marketcap value": f"{calculate}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/calculate_net_profit_margin.py b/tasks/calculate_net_profit_margin.py new file mode 100644 index 00000000..7a3edc25 --- /dev/null +++ b/tasks/calculate_net_profit_margin.py @@ -0,0 +1,24 @@ +from helpers import functions +from fastapi import HTTPException, status + +def calculate_net_profit_margin_task(revenue: float, + cost_of_goods_sold: float, + operating_expenses: float, + other_expenses: float, + interest: float, + taxes: float): + try: + net_profit_margin = functions.calulate_net_profit_margin( + revenue, cost_of_goods_sold, operating_expenses, other_expenses, interest, taxes) + return { + "Tag": "Calculate net profit margin", + "Revenue": revenue, + "Cost of goods sold": cost_of_goods_sold, + "Operating Expenses": operating_expenses, + "Interest": interest, + "Taxes": taxes, + "Net Profit Margin": net_profit_margin, + + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/calculate_pension.py b/tasks/calculate_pension.py new file mode 100644 index 00000000..95fad8be --- /dev/null +++ b/tasks/calculate_pension.py @@ -0,0 +1,26 @@ +from helpers import functions +from fastapi import HTTPException, status + +def calculate_pension_task( + monthly_investment_amount, + no_of_years, + annuity_rates, + annuity_purchased, + yearly_interest_rates, +): + try: + (total_corpus, lump_sum_pension, monthly_pension) = functions.calculate_pension( + monthly_investment_amount, + no_of_years, + annuity_rates, + annuity_purchased, + yearly_interest_rates, + ) + return { + "Tag": "Calculate pension", + "Total Corpus": total_corpus, + "Lump sum pension": lump_sum_pension, + "Monthly pension": monthly_pension, + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/calculate_period_FV_PV_rate.py b/tasks/calculate_period_FV_PV_rate.py new file mode 100644 index 00000000..abe5a479 --- /dev/null +++ b/tasks/calculate_period_FV_PV_rate.py @@ -0,0 +1,14 @@ +from helpers import functions +from fastapi import HTTPException, status + +def CalculatePeriods_task(present_val: float, future_val: float, rate: float): + try: + period = functions.CalculatePeriods(present_val, future_val, rate) + return { + "Tag": "Period in years ", + "Present Value": present_val, + "Future Value": future_val, + "Periods": period, + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/calculate_post_tax_return_percentage.py b/tasks/calculate_post_tax_return_percentage.py new file mode 100644 index 00000000..32d4f6fe --- /dev/null +++ b/tasks/calculate_post_tax_return_percentage.py @@ -0,0 +1,18 @@ +from helpers import functions +from fastapi import HTTPException, status + +def calculate_post_tax_return_percentage_task(tax_rate_percentage: float, + annual_net_income: float, + initial_cost_of_investment: float): + try: + post_tax_return_percentage = functions.calculate_post_tax_return_percentage( + tax_rate_percentage, annual_net_income, initial_cost_of_investment) + return { + "Tag": "Calculate post tax return percentage", + "Tax Rate Percentage": tax_rate_percentage, + "Annual net income": annual_net_income, + "Initial cost of investment": initial_cost_of_investment, + "Post tax return percentage": post_tax_return_percentage + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/calculate_retirement_goals.py b/tasks/calculate_retirement_goals.py new file mode 100644 index 00000000..64a1d4ac --- /dev/null +++ b/tasks/calculate_retirement_goals.py @@ -0,0 +1,29 @@ +from helpers import functions +from fastapi import HTTPException, status + +def calculate_retirement_goals_task( + retirement_age: int, + annual_retirement_expenses: int, + inflation_rate: float, + annual_retirement_income: int, + current_age: int, +): + try: + amount = functions.calculate_retirement_goals( + retirement_age, + annual_retirement_expenses, + inflation_rate, + annual_retirement_income, + current_age, + ) + return { + "Tag": "Retirement Goals", + "Retirement age": retirement_age, + "Annual retirement expenses": annual_retirement_expenses, + "inflation rate": inflation_rate, + "Annual Retirement Income": annual_retirement_income, + "Current Age": current_age, + "Retirement Goals": f"{amount}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/calculate_retirement_goalspy b/tasks/calculate_retirement_goalspy new file mode 100644 index 00000000..64a1d4ac --- /dev/null +++ b/tasks/calculate_retirement_goalspy @@ -0,0 +1,29 @@ +from helpers import functions +from fastapi import HTTPException, status + +def calculate_retirement_goals_task( + retirement_age: int, + annual_retirement_expenses: int, + inflation_rate: float, + annual_retirement_income: int, + current_age: int, +): + try: + amount = functions.calculate_retirement_goals( + retirement_age, + annual_retirement_expenses, + inflation_rate, + annual_retirement_income, + current_age, + ) + return { + "Tag": "Retirement Goals", + "Retirement age": retirement_age, + "Annual retirement expenses": annual_retirement_expenses, + "inflation rate": inflation_rate, + "Annual Retirement Income": annual_retirement_income, + "Current Age": current_age, + "Retirement Goals": f"{amount}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/calculate_salary.py b/tasks/calculate_salary.py new file mode 100644 index 00000000..3ce5e9ef --- /dev/null +++ b/tasks/calculate_salary.py @@ -0,0 +1,27 @@ +from helpers import functions +from fastapi import HTTPException, status + +def calculate_salary_task(base: int, + jb: int, + stock: int, + pb: int, + bonus: int, + ptax: int, + deduction: int): + try: + calculate_salary = functions.calculate_salary( + base, jb, stock, pb, bonus, ptax, deduction) + return { + + "Tag": "Net Salary Calculator", + "Base Salary per month": base, + "joining bonus/retention bonus": jb, + "RSU/stock bonus": stock, + "performance bonus": pb, + "any additional bonus": bonus, + "tax percentage": ptax, + "any additional deduction": deduction, + "ctc calculated": f"{ctc}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/calculate_vat.py b/tasks/calculate_vat.py new file mode 100644 index 00000000..5a790481 --- /dev/null +++ b/tasks/calculate_vat.py @@ -0,0 +1,19 @@ +from helpers import functions +from fastapi import HTTPException, status + +async def calculate_vat_task(price: float, vat_rate: float): + try: + excluding_vat = price / (1 + functions.percent_to_decimal(vat_rate)) + including_vat = price + vat_amount = price - excluding_vat + + return { + "Price (excluding VAT)": excluding_vat, + "Price (including VAT)": including_vat, + "VAT Amount": vat_amount, + } + except Exception as e: + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail="An error occurred during VAT calculation", + ) diff --git a/tasks/capital_Asset_Pricing_Model.py b/tasks/capital_Asset_Pricing_Model.py new file mode 100644 index 00000000..35c056c6 --- /dev/null +++ b/tasks/capital_Asset_Pricing_Model.py @@ -0,0 +1,21 @@ +from helpers import functions +from fastapi import HTTPException, status + +def Capital_Asset_Pricing_Model_task( + risk_free_interest_rate: float, + beta_of_security: float, + expected_market_return: float, +): + try: + Capital_Asset_Pricing_Model = functions.Capital_Asset_Pricing_Model( + risk_free_interest_rate, beta_of_security, expected_market_return + ) + return { + "Tag": "Capital Asset Pricing Model", + "Risk free interest rate": risk_free_interest_rate, + "Beta of security": beta_of_security, + "Expected market return": expected_market_return, + "Capital asset expected return": f"{Capital_Asset_Pricing_Model}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/capital_gains_yield.py b/tasks/capital_gains_yield.py new file mode 100644 index 00000000..958967d6 --- /dev/null +++ b/tasks/capital_gains_yield.py @@ -0,0 +1,14 @@ +from helpers import functions +from fastapi import HTTPException, status + +def capital_gains_yield_task(inital_price: float, price_after_first_period: float): + try: + gains_yield = functions.capital_gains_yield(inital_price, price_after_first_period) + return { + "Tag": "Capital Gains Yield", + "Inital Price of Stock": inital_price, + "Price of Stock After First Period": price_after_first_period, + "Capital Gains Yield": f"{gains_yield}%", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/capitalization_rate.py b/tasks/capitalization_rate.py new file mode 100644 index 00000000..5860c91e --- /dev/null +++ b/tasks/capitalization_rate.py @@ -0,0 +1,33 @@ +from helpers import functions +from fastapi import HTTPException, status + +def capitalization_rate_task( + rental_income: float, + amenities: float, + propertyManagement: float, + propertyTaxes:float, + insurance: float, + current_market_value: float): + try: + rate = functions.capitalization_rate(rental_income, amenities, propertyManagement, + propertyTaxes, insurance, current_market_value + ) + annual_income = rental_income + amenities, + expenses = propertyManagement + propertyTaxes + insurance, + net_operating_income = annual_income - expenses, + + return { + "Tag": "Capitalization Rate", + "Rental Income": rental_income, + "Amenities": amenities, + "Property Management": propertyManagement, + "Property Taxes": propertyTaxes, + "Insurance": insurance, + "Annual Income": annual_income, + "Expenses": expenses, + "Net Operating Income": net_operating_income, + "Current Market Value": current_market_value, + "Capitalization Rate": f"{rate}%" + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/certificate_of_deposit.py b/tasks/certificate_of_deposit.py new file mode 100644 index 00000000..0b11d409 --- /dev/null +++ b/tasks/certificate_of_deposit.py @@ -0,0 +1,20 @@ +from helpers import functions +from fastapi import HTTPException, status + +def certificate_of_deposit_task( + principal_amount: float, interest_rate: float, yrs: int, compounding_per_yr: int +): + try: + cd = functions.certificate_of_deposit( + principal_amount, interest_rate, yrs, compounding_per_yr + ) + return { + "Tag": "Certificate of Deposit (CD)", + "Principal amount": principal_amount, + "Interest Rate": interest_rate, + "Time in Years": yrs, + "Number of Compounding per Year": compounding_per_yr, + "Certificate of Deposit (CD)": f"{cd}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/cogr.py b/tasks/cogr.py new file mode 100644 index 00000000..68b51d0e --- /dev/null +++ b/tasks/cogr.py @@ -0,0 +1,18 @@ +from helpers import functions +from fastapi import HTTPException, status + +def compound_annual_growth_rate_task( + beginning_value: float, ending_value: float, years: int +): + try: + rate = functions.compound_annual_growth_rate( + beginning_value, ending_value, years + ) + return { + "Tag": "Compound Annual Growth Rate", + "Beginning Value": beginning_value, + "Ending Value": ending_value, + "Compound Annual Growth Rate": f"{rate}%", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/cogs.py b/tasks/cogs.py new file mode 100644 index 00000000..d4d6d806 --- /dev/null +++ b/tasks/cogs.py @@ -0,0 +1,19 @@ +from helpers import functions +from fastapi import HTTPException, status + +def cost_of_goods_sold_task( + beginning_inventory: float, purchases: float, ending_inventory: float +): + try: + cogs = functions.cost_of_goods_sold( + beginning_inventory, purchases, ending_inventory + ) + return { + "Tag": "Cost of Goods Sold", + "Beginning Inventory": beginning_inventory, + "Purchases during the period": purchases, + "Ending Inventory": ending_inventory, + "Cost of Goods Sold(In Rupees)": f"{cogs}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/college_cost.py b/tasks/college_cost.py new file mode 100644 index 00000000..286003a2 --- /dev/null +++ b/tasks/college_cost.py @@ -0,0 +1,35 @@ +from helpers import functions +from fastapi import HTTPException, status + +def college_cost_task( + book_cost: float, + college_tuition: float, + Devices: float, + travel_expenses: float, + hostel_charges: float, + mess_fee: float, + miscellaneous: float, +): + try: + cost = functions.college_cost( + book_cost, + college_tuition, + Devices, + travel_expenses, + hostel_charges, + mess_fee, + miscellaneous, + ) + return { + "Tag": "College Cost", + "Books cost of one year": book_cost, + "College tuition fee per year": college_tuition, + "Electronic devices cost": Devices, + "Monthly Travel expenses": travel_expenses, + "Monthly Hostel charges": hostel_charges, + "Monthly mess fee": mess_fee, + "monthly miscellaneous expenses": miscellaneous, + "Total cost of one year": cost, + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/commission_calc.py b/tasks/commission_calc.py new file mode 100644 index 00000000..6e730b04 --- /dev/null +++ b/tasks/commission_calc.py @@ -0,0 +1,33 @@ +from helpers import functions +from fastapi import HTTPException, status + +def commission_calc_task( + sales_price: float = None, commission_rate: float = None, commission: float = None +): + try: + output = functions.commission_calc( + sales_price, commission_rate, commission) + + if sales_price == None and commission_rate != None and commission != None: + return { + "Tag": "Sales Price", + "Sales Price": output, + "Commission Rate": f"{commission_rate}%", + "Commission": commission, + } + elif sales_price != None and commission_rate == None and commission != None: + return { + "Tag": "Commission Rate", + "Sales Price": sales_price, + "Commission Rate": f"{output}%", + "Commission": commission, + } + elif sales_price != None and commission_rate != None and commission == None: + return { + "Tag": "Commission", + "Sales Price": sales_price, + "Commission Rate": f"{commission_rate}%", + "Commission": output, + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/compound_annual_growth_rate.py b/tasks/compound_annual_growth_rate.py new file mode 100644 index 00000000..58d21228 --- /dev/null +++ b/tasks/compound_annual_growth_rate.py @@ -0,0 +1,19 @@ +from helpers import functions +from fastapi import HTTPException, status + +def compound_annual_growth_rate_1_task( + ending_value: float, beginning_value: float, number_of_periods: float +): + try: + cagr = functions.compound_annual_growth_rate_1( + ending_value, beginning_value, number_of_periods + ) + return { + "Tag": "compound annual growth rate 1", + "ending_value": ending_value, + "beginning value": beginning_value, + "Number of periods": number_of_periods, + "compound annual growth rate": f"{cagr}%", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/compound_interest.py b/tasks/compound_interest.py new file mode 100644 index 00000000..58a13f0c --- /dev/null +++ b/tasks/compound_interest.py @@ -0,0 +1,20 @@ +from helpers import functions +from fastapi import HTTPException, status + +def compound_interest_task( + principal_amount: float, interest_rate: float, years: int, compounding_period: int +): + try: + amount = functions.compound_interest( + principal_amount, interest_rate, years, compounding_period + ) + return { + "Tag": "Compound Interest Amount", + "Principle amount": principal_amount, + "Intrest Rate": interest_rate, + "Time in Years": years, + "Compounding Period": compounding_period, + "Amount after interest": f"{amount}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) diff --git a/tasks/compounded_annual_growth_rate.py b/tasks/compounded_annual_growth_rate.py new file mode 100644 index 00000000..aeaa0d15 --- /dev/null +++ b/tasks/compounded_annual_growth_rate.py @@ -0,0 +1,20 @@ +from helpers import functions +from fastapi import HTTPException, status + +def compounded_annual_growth_rate_task( + end_investment_value: float, initial_investment_value: float, years: int +): + try: + cagr = functions.compounded_annual_growth_rate( + end_investment_value, initial_investment_value, years + ) + + return { + "Tag": "Compounded Annual Growth Rate", + "End investment value": end_investment_value, + "Initial investment value": initial_investment_value, + "Years": years, + "Compounded Annual Growth Rate": f"{cagr}%", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/convexity_duration.py b/tasks/convexity_duration.py new file mode 100644 index 00000000..9396d3b5 --- /dev/null +++ b/tasks/convexity_duration.py @@ -0,0 +1,20 @@ +from helpers import functions +from fastapi import HTTPException, status + +def duration_task(rate, coupon_rate, frequency, face_value, settlement_date, maturity_date): + try: + duration = functions.duration( + rate, coupon_rate, frequency, face_value, settlement_date, maturity_date + ) + return { + "Tag": "Convexity Adjusted Duration", + "Market Rate": rate, + "Coupon rate": coupon_rate, + "Frequency": frequency, + "Face Value": face_value, + "Settlement Date": settlement_date, + "Maturity Date": maturity_date, + "Convexity Adjusted Duration": f"{duration}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/cost_of_equity.py b/tasks/cost_of_equity.py new file mode 100644 index 00000000..a489c165 --- /dev/null +++ b/tasks/cost_of_equity.py @@ -0,0 +1,19 @@ +from helpers import functions +from fastapi import HTTPException, status + +def cost_of_equity_task( + risk_free_rate_of_return: float, Beta: float, market_rate_of_return: float +): + try: + costOfEquity = functions.cost_of_equity( + risk_free_rate_of_return, Beta, market_rate_of_return + ) + return { + "Tag": "Cost of Equity", + "Risk free rate of return": risk_free_rate_of_return, + "Beta": Beta, + "Market rate of return ": market_rate_of_return, + "Cost of equity": f"{costOfEquity}%", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/credit_card_equation.py b/tasks/credit_card_equation.py new file mode 100644 index 00000000..ff447b86 --- /dev/null +++ b/tasks/credit_card_equation.py @@ -0,0 +1,19 @@ +from helpers import functions +from fastapi import HTTPException, status + +def credit_card_equation_task( + balance: float, monthly_payment: float, daily_interest_rate: float +): + try: + N = functions.credit_card_equation( + balance, monthly_payment, daily_interest_rate + ) + return { + "Tag": "Credit card equation", + "Balance": balance, + "Monthly Payment": monthly_payment, + "daily interest rate": daily_interest_rate, + "credit card equation": f"{N}%", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/credit_card_payoff.py b/tasks/credit_card_payoff.py new file mode 100644 index 00000000..f6956444 --- /dev/null +++ b/tasks/credit_card_payoff.py @@ -0,0 +1,22 @@ +from helpers import functions +from fastapi import HTTPException, status + +def credit_card_payoff_task( + debts: list, interest_rates: list, minimum_payments: list, monthly_payment: int +): + try: + result = functions.credit_card_payoff( + debts, interest_rates, minimum_payments, monthly_payment + ) + return { + "Tag": "Credit card payoff", + "debts": debts, + "interest rates": interest_rates, + "minimum payments": minimum_payments, + "Monthly payment": monthly_payment, + "Months": [r["month"] for r in result], + "Interest paid": [r["interest_paid"] for r in result], + "Total Payment": [r["total_payment"] for r in result], + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/current_liability_coverage_ratio.py b/tasks/current_liability_coverage_ratio.py new file mode 100644 index 00000000..31db0f02 --- /dev/null +++ b/tasks/current_liability_coverage_ratio.py @@ -0,0 +1,23 @@ +from helpers import functions +from fastapi import HTTPException, status + +def current_liability_coverage_ratio_task( + net_cash_from_operating_activities: float, + total_current_liabilities: float, + number_of_liabilities: int, +): + try: + current_liability_coverage_ratio = functions.current_liability_coverage_ratio( + net_cash_from_operating_activities, + total_current_liabilities, + number_of_liabilities, + ) + return { + "Tag": "current liability coverage ratio", + "net cash from operating activities": net_cash_from_operating_activities, + "total current liabilities": total_current_liabilities, + "number of liabilities": number_of_liabilities, + "current liability coverage ratio": f"{current_liability_coverage_ratio}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/current_ratio.py b/tasks/current_ratio.py new file mode 100644 index 00000000..42e5404b --- /dev/null +++ b/tasks/current_ratio.py @@ -0,0 +1,15 @@ +from helpers import functions +from fastapi import HTTPException, status + +def current_ratio_task(total_current_assets: float, total_liabilities: float): + try: + ratio = functions.current_ratio( + total_current_assets, total_liabilities) + return { + "Tag": "Current Ratio", + "Total Current Assets": total_current_assets, + "Total Liabilities": total_liabilities, + "Current Ratio": f"{ratio}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/debt_to_income_ratio.py b/tasks/debt_to_income_ratio.py new file mode 100644 index 00000000..b4f4359b --- /dev/null +++ b/tasks/debt_to_income_ratio.py @@ -0,0 +1,15 @@ +from helpers import functions +from fastapi import HTTPException, status + +def debt_to_income_ratio_task(annual_income: float, total_debt_per_month: float): + try: + DTI = functions.debt_to_income_ratio( + annual_income, total_debt_per_month) + return { + "Tag": "Debt to income ratio", + "Annual income": annual_income, + "Total debt per month": total_debt_per_month, + "Debt to income ratio per month": f"{DTI}%", + } + except: + raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE) \ No newline at end of file diff --git a/tasks/diluted_earnings_per_share.py b/tasks/diluted_earnings_per_share.py new file mode 100644 index 00000000..dec39445 --- /dev/null +++ b/tasks/diluted_earnings_per_share.py @@ -0,0 +1,21 @@ +from helpers import functions +from fastapi import HTTPException, status + +def calculate_diluted_eps_task( + net_income: float, + weighted_avg_shares: float, + dilutive_securities: float, +): + try: + result = functions.diluted_eps( + net_income, weighted_avg_shares, dilutive_securities + ) + return { + "Tag": "Diluted Earnings Per Share (EPS)", + "Net Income": net_income, + "Weighted Average Shares Outstanding": weighted_avg_shares, + "Number of Dilutive Securities": dilutive_securities, + "Diluted EPS": f"{result}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/discount_opex.py b/tasks/discount_opex.py new file mode 100644 index 00000000..197f7e06 --- /dev/null +++ b/tasks/discount_opex.py @@ -0,0 +1,15 @@ +from helpers import functions +from fastapi import HTTPException, status + +def discount_opex_task(annual_opex: float, wacc: float, project_lifetime: float): + try: + dis_opex = functions.discount_opex(annual_opex, wacc, project_lifetime) + return { + "Tag": "Discount OPEX", + "Annual OPEX": annual_opex, + "WACC": wacc, + "project lifetime": project_lifetime, + "Discount opex": f"{dis_opex}%", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/discounted_cash_flow.py b/tasks/discounted_cash_flow.py new file mode 100644 index 00000000..43bb94ef --- /dev/null +++ b/tasks/discounted_cash_flow.py @@ -0,0 +1,23 @@ +from helpers import functions +from fastapi import HTTPException, status + +def discounted_cash_flow_task( + real_feed_in_tariff: float, + annual_production: float, + wacc: float, + project_lifetime: float, +): + try: + d_cash_flow = functions.discounted_cash_flow( + real_feed_in_tariff, annual_production, wacc, project_lifetime + ) + return { + "Tag": "Discounted cash flow", + "Real feed in teriff": real_feed_in_tariff, + "annual production": annual_production, + "wacc": wacc, + "project lifetime": project_lifetime, + "discounted cash flow": f"{d_cash_flow}%", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/discounted_payback_period.py b/tasks/discounted_payback_period.py new file mode 100644 index 00000000..c8b04233 --- /dev/null +++ b/tasks/discounted_payback_period.py @@ -0,0 +1,17 @@ +from helpers import functions +from fastapi import HTTPException, status + +def discounted_payback_period_task(outflow: float, rate: float, periodic_cash_flow: float): + try: + discounted_payback_period = functions.discounted_payback_period( + outflow, rate, periodic_cash_flow + ) + return { + "Tag": "Discounted Payback Period", + "Initial Investment (Outflow)": outflow, + "Rate": rate, + "Periodic Cash Flow": periodic_cash_flow, + "Discounted Payback Period": discounted_payback_period, + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/dividend_payout_ratio.py b/tasks/dividend_payout_ratio.py new file mode 100644 index 00000000..7a20dfe2 --- /dev/null +++ b/tasks/dividend_payout_ratio.py @@ -0,0 +1,16 @@ +from helpers import functions +from fastapi import HTTPException, status + +def dividend_payout_ratio_task(dividend_per_share: float, earnings_per_share: float): + try: + dividend_payout = functions.dividend_payout_ratio( + dividend_per_share, earnings_per_share + ) + return { + "Tag": "Dividend payout ratio", + "Dividend per share": dividend_per_share, + "Share price": earnings_per_share, + "Dividend yield ratio": f"{dividend_payout}%", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/dividend_yield_ratio.py b/tasks/dividend_yield_ratio.py new file mode 100644 index 00000000..19544d46 --- /dev/null +++ b/tasks/dividend_yield_ratio.py @@ -0,0 +1,15 @@ +from helpers import functions +from fastapi import HTTPException, status + +def dividend_yield_ratio_task(dividend_per_share: float, share_price: float): + try: + dividend_yield = functions.dividend_yield_ratio( + dividend_per_share, share_price) + return { + "Tag": "Dividend yield ratio", + "Dividend per share": dividend_per_share, + "Share price": share_price, + "Dividend yield ratio": f"{dividend_yield}%", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/doubling_time.py b/tasks/doubling_time.py new file mode 100644 index 00000000..caab1a77 --- /dev/null +++ b/tasks/doubling_time.py @@ -0,0 +1,13 @@ +from helpers import functions +from fastapi import HTTPException, status + +def doubling_time_task(r: float): + try: + doubling_time = functions.doubling_time(r) + return { + "Tag": "Doubling Time", + "Rate of Interest": r, + "Time in years to double the money": f"{doubling_time}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/effective_annual_rate..py b/tasks/effective_annual_rate..py new file mode 100644 index 00000000..b1244e44 --- /dev/null +++ b/tasks/effective_annual_rate..py @@ -0,0 +1,18 @@ +from helpers import functions +from fastapi import HTTPException, status + +def effective_annual_rate_task(annual_interest_rate: float, compounding_period: int): + try: + eff_annual_rate = functions.effective_annual_rate( + annual_interest_rate, compounding_period + ) + eff_annual_rate_percentage = functions.decimal_to_percent( + eff_annual_rate) + return { + "Tag": "Effective Annual Rate", + "Annual Intrest Rate": annual_interest_rate, + "Compounding Period": compounding_period, + "Effective Annual Rate (in percentage)": f"{eff_annual_rate_percentage}%", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/effective_annual_rate.py b/tasks/effective_annual_rate.py new file mode 100644 index 00000000..6831c482 --- /dev/null +++ b/tasks/effective_annual_rate.py @@ -0,0 +1,18 @@ +from helpers import functions +from fastapi import HTTPException, status + +def effective_annual_rate_task(annual_interest_rate: float, compounding_period: int): + try: + eff_annual_rate = functions.effective_annual_rate( + annual_interest_rate, compounding_period + ) + eff_annual_rate_percentage = functions.decimal_to_percent( + eff_annual_rate) + return { + "Tag": "Effective Annual Rate", + "Annual Intrest Rate": annual_interest_rate, + "Compounding Period": compounding_period, + "Effective Annual Rate (in percentage)": f"{eff_annual_rate_percentage}%", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) diff --git a/tasks/enterprise_value.py b/tasks/enterprise_value.py new file mode 100644 index 00000000..f2c4d5ae --- /dev/null +++ b/tasks/enterprise_value.py @@ -0,0 +1,31 @@ +from helpers import functions +from fastapi import HTTPException, status + +def calculate_enterprise_value_task( + share_price: float, + fully_diluted_shares_outstanding: int, + total_debt: float, + preferred_stock: float, + non_controlling_interest: float, + cash_and_cash_equivalents: float, +): + try: + enterprise_value = functions.calculate_enterprise_value( + share_price, + fully_diluted_shares_outstanding, + total_debt, + preferred_stock, + non_controlling_interest, + cash_and_cash_equivalents, + ) + return { + "Tag": "Enterprise Value", + "Equity Value": share_price * fully_diluted_shares_outstanding, + "Total Debt": total_debt, + "Preferred Stock": preferred_stock, + "Non-Controlling Interest": non_controlling_interest, + "Cash & Cash Equivalents": cash_and_cash_equivalents, + "Enterprise Value": enterprise_value, + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/excess_reserves.py b/tasks/excess_reserves.py new file mode 100644 index 00000000..a588d597 --- /dev/null +++ b/tasks/excess_reserves.py @@ -0,0 +1,15 @@ +from helpers import functions +from fastapi import HTTPException, status + +def excess_reserves_task(deposits: float, reserve_requirement: float): + try: + excess_reserves = functions.excess_reserves( + deposits, reserve_requirement) + return { + "Tag": "Excess Reserves", + "Deposits": deposits, + "Reserve Requirement": reserve_requirement, + "Excess Reserves": excess_reserves, + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/fcff.py b/tasks/fcff.py new file mode 100644 index 00000000..d72e4c7e --- /dev/null +++ b/tasks/fcff.py @@ -0,0 +1,30 @@ +from helpers import functions +from fastapi import HTTPException, status + +def free_cash_flow_to_firm_task( + sales: float, + operating_cost: float, + depreciation: float, + interest: float, + tax_rate: float, + fcInv: float, + wcInv: float, +): + try: + ebitda = sales - operating_cost + ebit = ebitda - depreciation + ebt = ebit - interest + + eat = ebt - ebt * (tax_rate * 0.01) + fcff = functions.free_cash_flow_to_firm( + sales, operating_cost, depreciation, interest, tax_rate, fcInv, wcInv + ) + return { + "Tag": "Free Cash Flow to Firm (FCFF)", + "Earnings before interest, taxes, depreciation and amortization": f"{ebitda}", + "Earnings before interest and taxes : ": f"{ebit}", + "Net Income": f"{eat}", + "Free Cash Flow to Firm": f"{fcff}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/fha_loan.py b/tasks/fha_loan.py new file mode 100644 index 00000000..dd2eb362 --- /dev/null +++ b/tasks/fha_loan.py @@ -0,0 +1,30 @@ +from helpers import functions +from fastapi import HTTPException, status + +async def fha_loan_task( + home_price: float, + down_payment_percentage: float, + loan_term_years: float, + interest_rate: float, + fha_annual_mip_percentage: float, +): + try: + result = functions.calculate_fha_loan( + home_price, + down_payment_percentage, + loan_term_years, + interest_rate, + fha_annual_mip_percentage, + ) + return { + "down_payment": result["down_payment"], + "fha_base_loan_amount": result["fha_base_loan_amount"], + "fha_upfront_mip": result["fha_upfront_mip"], + "monthly_mortgage_payment": result["monthly_mortgage_payment"], + "monthly_mip": result["monthly_mip"], + "total_fha_loan_amount": result["total_fha_loan_amount"], + "total_monthly_payment": result["total_monthly_payment"], + "total_cost_of_loan": result["total_cost_of_loan"], + } + except Exception as e: + raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/fixed_charges_coverage_ratio.py b/tasks/fixed_charges_coverage_ratio.py new file mode 100644 index 00000000..f8488903 --- /dev/null +++ b/tasks/fixed_charges_coverage_ratio.py @@ -0,0 +1,21 @@ +from helpers import functions +from fastapi import HTTPException, status + +def fixed_charge_coverage_ratio_task( + earnings_before_interest_taxes: float, + fixed_charge_before_tax: float, + interest: float, +): + try: + fccr = functions.fixed_charge_coverage_ratio( + earnings_before_interest_taxes, fixed_charge_before_tax, interest + ) + return { + "Tag": "fixed charges coverage ratio", + "Earnings before interest taxes": earnings_before_interest_taxes, + "Fixed charge before tax": fixed_charge_before_tax, + "Interest": interest, + "Fixed charge coverage ratio": f"{fccr}%", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/free_cash_flow_to_equity.py b/tasks/free_cash_flow_to_equity.py new file mode 100644 index 00000000..09ad1e86 --- /dev/null +++ b/tasks/free_cash_flow_to_equity.py @@ -0,0 +1,47 @@ +from helpers import functions +from fastapi import HTTPException, status + +def free_cash_flow_to_equity_task( + total_revenues: float, + total_expenses: float, + initial_cost_of_asset: float, + lifetime_of_asset: float, + change_in_PPE: float, + current_depreciation: float, + current_assets: float, + current_liabilities: float, + amount_a_company_borrows: float, + debt_it_repays: float): + try: + fcfe = functions.free_cash_flow_to_equity( + total_revenues, total_expenses, initial_cost_of_asset, lifetime_of_asset, + change_in_PPE, current_depreciation, current_assets, current_liabilities, + amount_a_company_borrows, debt_it_repays + ) + net_income = total_revenues - total_expenses, + depreciation_and_amortization = initial_cost_of_asset / lifetime_of_asset, + capEx = change_in_PPE + current_depreciation, + change_in_working_capital = current_assets - current_liabilities, + net_borrowing = amount_a_company_borrows - debt_it_repays, + + return { + "Tag": "Free Cash Flow to Equity", + "Total Revenues": total_revenues, + "Total Expenses": total_expenses, + "Inital Cost of Asset": initial_cost_of_asset, + "Life Time of Asset": lifetime_of_asset, + "Change in Price, Property or Equity": change_in_PPE, + "Current Depreciation": current_depreciation, + "Current Assets": current_assets, + "Current Liabilities": current_liabilities, + "Amount a Company Borrows": amount_a_company_borrows, + "Debt it Repays": debt_it_repays, + "Net Income": net_income, + "Depreciation and Amortization": depreciation_and_amortization, + "Capital Expenditures": capEx, + "Change in Working Capital": change_in_working_capital, + "Net Borrowing": net_borrowing, + "Free Cash Flow to Equity": fcfe + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/future_sip.py b/tasks/future_sip.py new file mode 100644 index 00000000..29598ff0 --- /dev/null +++ b/tasks/future_sip.py @@ -0,0 +1,19 @@ +from helpers import functions +from fastapi import HTTPException, status + +def future_sip_task( + interval_investment: float, rate_of_return: float, number_of_payments: int +): + try: + value = functions.future_sip( + interval_investment, rate_of_return, number_of_payments + ) + return { + "Tag": "Future Value of SIP", + "Investment at every Interval": interval_investment, + "Interest": functions.percent_to_decimal(rate_of_return) / 12, + "Number of Payments": number_of_payments, + "Future Value": f"{value}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/future_value_of_annuity.py b/tasks/future_value_of_annuity.py new file mode 100644 index 00000000..a023f1cb --- /dev/null +++ b/tasks/future_value_of_annuity.py @@ -0,0 +1,19 @@ +from helpers import functions +from fastapi import HTTPException, status + +def future_value_of_annuity_task( + payments_per_period: float, interest_rate: float, number_of_periods: float +): + try: + fva = functions.future_value_of_annuity( + payments_per_period, interest_rate, number_of_periods + ) + return { + "Tag": "Future value of annuity", + "Payments per periods": payments_per_period, + "interest rate": interest_rate, + "number of periods": number_of_periods, + "future value of annuity": f"{fva}%", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/future_value_of_annuity_due.py b/tasks/future_value_of_annuity_due.py new file mode 100644 index 00000000..45a28c35 --- /dev/null +++ b/tasks/future_value_of_annuity_due.py @@ -0,0 +1,19 @@ +from helpers import functions +from fastapi import HTTPException, status + +def future_value_of_annuity_due_task( + periodic_payment: float, number_of_periods: int, effective_interest_rate: float +): + try: + future_value_of_annuity_due = functions.future_value_of_annuity_due( + periodic_payment, number_of_periods, effective_interest_rate + ) + return { + "Tag": "Future value of the ordinary annuity", + "Periodic payment": periodic_payment, + "Number of periods": number_of_periods, + "Effective interest rate": effective_interest_rate, + "Number of periods": f"{future_value_of_annuity_due}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/future_value_of_ordinary_due.py b/tasks/future_value_of_ordinary_due.py new file mode 100644 index 00000000..7d1047d6 --- /dev/null +++ b/tasks/future_value_of_ordinary_due.py @@ -0,0 +1,19 @@ +from helpers import functions +from fastapi import HTTPException, status + +def future_value_of_ordinary_due_task( + periodic_payment: float, number_of_periods: int, effective_interest_rate: float +): + try: + future_value_of_ordinary_due = functions.future_value_of_ordinary_due( + periodic_payment, number_of_periods, effective_interest_rate + ) + return { + "Tag": "Future value of the ordinary annuity", + "Periodic payment": periodic_payment, + "Number of periods": number_of_periods, + "Effective interest rate": effective_interest_rate, + "Number of periods": f"{future_value_of_ordinary_due}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/gdp_growth_rate.py b/tasks/gdp_growth_rate.py new file mode 100644 index 00000000..8b90cdb0 --- /dev/null +++ b/tasks/gdp_growth_rate.py @@ -0,0 +1,15 @@ +from helpers import functions +from fastapi import HTTPException, status + +def gdp_growth_rate_task(current_year_gdp: float, last_year_gdp: float): + try: + gdp_growth_rate = functions.gdp_growth_rate( + current_year_gdp, last_year_gdp) + return { + "Tag": "GDP Growth Rate", + "Current Year GDP": current_year_gdp, + "Last Year GDP": last_year_gdp, + "GDP Growth Rate": gdp_growth_rate, + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/herfindahl_Index.py b/tasks/herfindahl_Index.py new file mode 100644 index 00000000..c6ba6a92 --- /dev/null +++ b/tasks/herfindahl_Index.py @@ -0,0 +1,13 @@ +from helpers import functions +from fastapi import HTTPException, status + +def herfindahl_Index_task(Firms_market_shares: str): + try: + herfindahl_Index = functions.herfindal_Index(Firms_market_shares) + return { + "Tag": "Herfindahl Index", + "Firms market shares": Firms_market_shares, + "Herfindahl Index": f"{herfindahl_Index}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/inflation.py b/tasks/inflation.py new file mode 100644 index 00000000..a69e668e --- /dev/null +++ b/tasks/inflation.py @@ -0,0 +1,16 @@ +from helpers import functions +from fastapi import HTTPException, status + +def inflation_task(present_amount: float, inflation_rate: float, years: float): + try: + future_amount = functions.inflation( + present_amount, inflation_rate, years) + return { + "Tag": "Inflated Amount", + "Present Amount": present_amount, + "Inflation Rate": inflation_rate, + "Time in Years": years, + "Future Amount": f"{future_amount}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/inflation_adjusted_return.py b/tasks/inflation_adjusted_return.py new file mode 100644 index 00000000..454def8f --- /dev/null +++ b/tasks/inflation_adjusted_return.py @@ -0,0 +1,30 @@ +from helpers import functions +from fastapi import HTTPException, status + +def inflation_adjusted_return_task( + beginning_price: float, + ending_price: float, + dividends: float, + beginning_cpi_level: float, + ending_cpi__level: float, +): + try: + stock_return = (ending_price - beginning_price + + dividends) / beginning_price + inflation = (ending_cpi__level - beginning_cpi_level) / \ + beginning_cpi_level + inflation_adj_return = functions.inflation_adjusted_return( + beginning_price, + ending_price, + dividends, + beginning_cpi_level, + ending_cpi__level, + ) + return { + "Tag": "Inflation Adjusted Return", + "Stock Return": f"{stock_return}%", + "Inflation Rate": f"{inflation}%", + "Inflation Adjusted Return": f"{inflation_adj_return}%", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/inflation_rate.py b/tasks/inflation_rate.py new file mode 100644 index 00000000..52133631 --- /dev/null +++ b/tasks/inflation_rate.py @@ -0,0 +1,16 @@ +from helpers import functions +from fastapi import HTTPException, status + +def inflation_rate_task(bigger_year: int, smaller_year: int, base_year: int): + try: + inflation_rate = functions.inflation_rate( + bigger_year, smaller_year, base_year) + return { + "Tag": "Inflation Rate", + "Bigger Year": bigger_year, + "Smaller Year": smaller_year, + "Base Year": base_year, + "Inflation Rate": inflation_rate, + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/inventory_shrinkage_rate.py b/tasks/inventory_shrinkage_rate.py new file mode 100644 index 00000000..637f54b0 --- /dev/null +++ b/tasks/inventory_shrinkage_rate.py @@ -0,0 +1,19 @@ +from helpers import functions +from fastapi import HTTPException, status + +def inventory_shrinkage_rate_task(recorded_inventory: float, actual_inventory: float): + try: + inventory_shrinkage_rate = functions.inventory_shrinkage_rate( + recorded_inventory, actual_inventory + ) + return { + "Tag": "Inventory shrinkage rate", + "Recorded Inventory": recorded_inventory, + "Actual Inventory": actual_inventory, + "Inventory Shrinkage Rate": inventory_shrinkage_rate, + "Inventory Shrinkage Rate (%)": functions.decimal_to_percent( + inventory_shrinkage_rate + ), + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/inventory_turnover_ratio.py b/tasks/inventory_turnover_ratio.py new file mode 100644 index 00000000..9f7e8861 --- /dev/null +++ b/tasks/inventory_turnover_ratio.py @@ -0,0 +1,17 @@ +from helpers import functions +from fastapi import HTTPException, status + +def inventory_turnover_ratio_task( + cost_of_goods_sold: float, beginning_inventory: float, ending_inventory: float +): + try: + ratio = functions.inventory_turnover_ratio( + cost_of_goods_sold, beginning_inventory, ending_inventory + ) + return { + "Tag": "Inventory Turnover Ratio", + "Cost of Goods Sold": cost_of_goods_sold, + "Inventory Turnover Ratio": f"{ratio}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/jensens_alpha.py b/tasks/jensens_alpha.py new file mode 100644 index 00000000..b601c0d2 --- /dev/null +++ b/tasks/jensens_alpha.py @@ -0,0 +1,26 @@ +from helpers import functions +from fastapi import HTTPException, status + +def jensens_alpha_task( + return_from_investment: float, + return_of_appropriate_market_index: float, + risk_free_rate: float, + beta: float, +): + try: + alpha = functions.jensens_alpha( + return_from_investment, + return_of_appropriate_market_index, + risk_free_rate, + beta, + ) + return { + "Tag": "Jensen's Alpha", + "Total return from investment": return_from_investment, + "Return of appropriate market index": return_of_appropriate_market_index, + "Risk free rate": risk_free_rate, + "Beta of the portfolio investment w.r.t chosen market index": beta, + "Alpha of the return ": f"{alpha}%", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/k401.py b/tasks/k401.py new file mode 100644 index 00000000..cab4db6b --- /dev/null +++ b/tasks/k401.py @@ -0,0 +1,37 @@ +from helpers import functions +from fastapi import HTTPException, status + +def estimate_401k_task( + income: float, + contribution_percentage: float, + current_age: int, + age_at_retirement: int, + rate_of_return: float, + salary_increase_rate: float, + withdraw_tax_rate: float, +): + try: + estimated_401k = functions.calculate_401k( + income, + contribution_percentage, + current_age, + age_at_retirement, + rate_of_return, + salary_increase_rate, + ) + return { + "Tag": "Estimated 401(k)", + "income": income, + "contribution_percentage": contribution_percentage, + "current_age": current_age, + "age_at_retirement": age_at_retirement, + "rate_of_return": rate_of_return, + "withdraw_tax_rate": withdraw_tax_rate, + "estimated_401k": estimated_401k, + "annual_withdraw_amount": round( + functions.percent_to_decimal( + withdraw_tax_rate) * estimated_401k, 3 + ), + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/leverage_ratio_equity.py b/tasks/leverage_ratio_equity.py new file mode 100644 index 00000000..ad304951 --- /dev/null +++ b/tasks/leverage_ratio_equity.py @@ -0,0 +1,15 @@ +from helpers import functions +from fastapi import HTTPException, status + +def leverage_equity_task(debt_payments: int, equity: int): + try: + leverage_ratio = functions.leverage_equity(debt_payments, equity) + + return { + "Tag": "Leverage Ratio By Equity", + "Debt ": debt_payments, + "Equity": equity, + "Leverage Ratio": f"{leverage_ratio}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/leverage_ratio_income.py b/tasks/leverage_ratio_income.py new file mode 100644 index 00000000..9a557b76 --- /dev/null +++ b/tasks/leverage_ratio_income.py @@ -0,0 +1,15 @@ +from helpers import functions +from fastapi import HTTPException, status + +def leverage_income_task(debt_payments: int, income: int): + try: + leverage_ratio = functions.leverage_income(debt_payments, income) + + return { + "Tag": "Leverage Ratio By Income", + "Debt ": debt_payments, + "Income": income, + "Leverage Ratio": f"{leverage_ratio}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/levered_beta.py b/tasks/levered_beta.py new file mode 100644 index 00000000..15ae4e0e --- /dev/null +++ b/tasks/levered_beta.py @@ -0,0 +1,16 @@ +from helpers import functions +from fastapi import HTTPException, status + +def levered_beta_task(unlevered_beta: float, tax_rate: float, debt: float, equity: float): + try: + l_beta = functions.levered_beta(unlevered_beta, tax_rate, debt, equity) + return { + "Tag": "Levered Beta", + "Unlevered Beta": unlevered_beta, + "Tax rate": tax_rate, + "debt": debt, + "Equity": equity, + "Levered Beta": f"{l_beta}%", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/loan_affordability.py b/tasks/loan_affordability.py new file mode 100644 index 00000000..2e2c922b --- /dev/null +++ b/tasks/loan_affordability.py @@ -0,0 +1,43 @@ +from helpers import functions +from fastapi import HTTPException, status + +def calculate_loan_affordability_task( + income: float, # annual Income + expenses: float, # annual expenses + loan_term: int, # loan term period + interest_rate: float, # annual interest rate +): + """ + This endpoint is use to check your ability to take any particular Loan on the Basis on + your income,expenses,loan_term,intrest_rate, This is basically loan affordability function + + eg url :- http://127.0.0.1:8000/loan-affordability?income=5000&expenses=2000&loan_term=12&interest_rate=5 + + explanation for calculating max_loan_amount :- + (1 + utils.percent_to_decimal(interest_rate)): This calculates the factor by which the loan amount increases due to the interest rate. For example, if the interest rate is 5%, this factor would be 1.05. + ** -loan_term: This raises the above factor to the power of negative loan_term. It represents the compounding effect of interest over the loan term. For example, if the loan term is 12 months, this factor would be (1.05) ** -12 + (1 - (1 + utils.percent_to_decimal(interest_rate)) ** -loan_term): This calculates the ratio of the remaining loan balance after making monthly payments to the initial loan amount. It represents the discounted value of the loan. + (monthly_income - monthly_expenses): This calculates the disposable income available for loan repayment each month. + (monthly_income - monthly_expenses) * (1 - (1 + utils.percent_to_decimal(interest_rate)) ** -loan_term): This calculates the discounted monthly loan payment amount based on the available disposable income. + + """ + try: + # monthly_income = income / 12 + # monthly_expenses = expenses / 12 + + max_loan_amount = functions.calculate_max_loan_amount( + income, expenses, loan_term, interest_rate + ) + + return { + "income": income, + "expenses": expenses, + "loan_term": loan_term, + "interest_rate": interest_rate, + "max_loan_amount": max_loan_amount, + } + except: + return HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail="Some Error occured", + ) \ No newline at end of file diff --git a/tasks/loan_emi.py b/tasks/loan_emi.py new file mode 100644 index 00000000..cdc0372a --- /dev/null +++ b/tasks/loan_emi.py @@ -0,0 +1,18 @@ +from helpers import functions +from fastapi import HTTPException, status + +def loan_emi_task(principle_amount: float, annual_rate: float, months: int): + try: + emi = functions.loan_emi(principle_amount, annual_rate, months) + return { + "Tag": "Loan Emi", + "Principal amount borrowed": principle_amount, + "Annual Rate of interest": annual_rate, + "Total number of monthly payments": months, + "EMI": f"{round(emi,3)}", + "Total Amount Payble": f"{round(emi*months,3)}", + "Interest amount": f"{round(emi*months-principle_amount,3)}", + } + except Exception as e: + print(e) + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/loan_to_value.py b/tasks/loan_to_value.py new file mode 100644 index 00000000..8d71305c --- /dev/null +++ b/tasks/loan_to_value.py @@ -0,0 +1,14 @@ +from helpers import functions +from fastapi import HTTPException, status + +def loan_to_value_task(mortgage_value: float, appraised_value: float): + try: + ratio = functions.loan_to_value(mortgage_value, appraised_value) + return { + "Tag": "Loan to Value (LTV) ratio", + "Mortgage Value": mortgage_value, + "Appraised Property Value": appraised_value, + "Loan to Value ratio": f"{ratio}%", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/loan_to_value_ratio.py b/tasks/loan_to_value_ratio.py new file mode 100644 index 00000000..a465cc59 --- /dev/null +++ b/tasks/loan_to_value_ratio.py @@ -0,0 +1,14 @@ +from helpers import functions +from fastapi import HTTPException, status + +def loan_to_value_ratio_task(loan_amount: float, value_of_collateral: float): + try: + ratio = functions.loan_to_value_ratio(loan_amount, value_of_collateral) + return { + "Tag": "Loan to Value Ratio", + "Loan Amount": loan_amount, + "Value Of Collateral": value_of_collateral, + "Loan to Value Ratio": f"{ratio}%", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/lumpsum.py b/tasks/lumpsum.py new file mode 100644 index 00000000..dae1e6b5 --- /dev/null +++ b/tasks/lumpsum.py @@ -0,0 +1,16 @@ +from helpers import functions +from fastapi import HTTPException, status + +async def calculate_lumpsum_task(principal: float, interest_rate: float, years: int): + + try: + total_amount = principal * ( + (1 + functions.percent_to_decimal(interest_rate)) ** years + ) + interest_earned = total_amount - principal + return { + "total_amount": round(total_amount, 2), + "interest_earned": round(interest_earned, 2), + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/markup_percentage.py b/tasks/markup_percentage.py new file mode 100644 index 00000000..38bebb50 --- /dev/null +++ b/tasks/markup_percentage.py @@ -0,0 +1,14 @@ +from helpers import functions +from fastapi import HTTPException, status + +def markup_percentage_task(price: float, cost: float): + try: + markup_percentage = functions.markup_percentage(price, cost) + return { + "Tag": "Markup Percentage", + "Price": price, + "Cost": cost, + "Markup Percentage": markup_percentage, + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/monthly_emi.py b/tasks/monthly_emi.py new file mode 100644 index 00000000..895b2eec --- /dev/null +++ b/tasks/monthly_emi.py @@ -0,0 +1,17 @@ +from helpers import functions +from fastapi import HTTPException, status + +def monthly_emi_task(loan_amt: float, interest_rate: float, number_of_installments: float): + try: + monthly_emi = functions.monthly_emi( + loan_amt, interest_rate, number_of_installments + ) + return { + "Tag": "Monthly EMI", + "Loan Amount": loan_amt, + "Interest Rate": interest_rate, + "Number of Installments": number_of_installments, + "Total EMI": f"{monthly_emi}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/monthly_lease_payment.py b/tasks/monthly_lease_payment.py new file mode 100644 index 00000000..e4276ae9 --- /dev/null +++ b/tasks/monthly_lease_payment.py @@ -0,0 +1,21 @@ +from helpers import functions +from fastapi import HTTPException, status + +def monthly_lease_payment_task( + Asset_value: float, + monthly_lease_interest_rate: float, + number_of_lease_payments: float, +): + try: + pmt = functions.monthly_lease_payment( + Asset_value, monthly_lease_interest_rate, number_of_lease_payments + ) + return { + "Tag": "Monthly Lease Payment", + "Asset value": Asset_value, + "Monthly lease interest rate": monthly_lease_interest_rate, + "Number of lease payments": number_of_lease_payments, + "Monthly Lease Payment": f"{pmt}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/monthly_payment.py b/tasks/monthly_payment.py new file mode 100644 index 00000000..1cd6af66 --- /dev/null +++ b/tasks/monthly_payment.py @@ -0,0 +1,23 @@ +from helpers import functions +from fastapi import HTTPException, status + +def monthly_payment_task( + principal: float, + interest_rate: float, + number_of_periods: float, + payments_per_period: float, +): + try: + monthly_pay = functions.monthly_payment( + principal, interest_rate, number_of_periods, payments_per_period + ) + return { + "Tag": "Monthly Payment", + "Principal": principal, + "Interest Rate": interest_rate, + "Number of Periods": number_of_periods, + "Payments per period": payments_per_period, + "Levered Beta": f"{monthly_pay}%", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/mortgage_amortization.py b/tasks/mortgage_amortization.py new file mode 100644 index 00000000..acfc02cc --- /dev/null +++ b/tasks/mortgage_amortization.py @@ -0,0 +1,24 @@ +from helpers import functions +from fastapi import HTTPException, status + +def mortgage_amortization_task( + mortgage_amount: float, + mortgage_deposit: float, + annual_interest_rate: float, + loan_term: int, +): + try: + annual_payment = functions.calculate_mortgage_interest( + mortgage_amount, mortgage_deposit, annual_interest_rate, loan_term + ) + return { + "TAG": "Mortgage monthly payments", + "mortgage_amount": mortgage_amount, + "mortgage_deposit": mortgage_deposit, + "annual_interest_rate": annual_interest_rate, + "loan_term": loan_term, + "monthly_payment": round(annual_payment / 12, 3), + "annual_payment": round(annual_payment, 3), + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/mortrages.py b/tasks/mortrages.py new file mode 100644 index 00000000..baf1340d --- /dev/null +++ b/tasks/mortrages.py @@ -0,0 +1,24 @@ +from helpers import functions +from fastapi import HTTPException, status + +def mortrage_task(princial: int, interest_rate: float, years: int, down_payment: int, property_tax_rate: float, insurance_rate: float): + + try: + mortrage = functions.calculate_mortgage( + principal=princial, + interest_rate=interest_rate, + years=years, + down_payment=down_payment, + property_tax_rate=property_tax_rate, + insurance_rate=insurance_rate + ) + return { + "Monthly Payment": mortrage['monthly_payment'], + "Total Payment": mortrage['total_payment'], + "Total Property Tax": mortrage['total_property_tax'], + "Total insurance cost": mortrage['total_insurance_cost'], + "Total Cost": mortrage['total_cost'], + "Loan to value ratio": mortrage["loan_to_value_ratio"] + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/net_present_value.py b/tasks/net_present_value.py new file mode 100644 index 00000000..4768416b --- /dev/null +++ b/tasks/net_present_value.py @@ -0,0 +1,17 @@ +from helpers import functions +from fastapi import HTTPException, status + +def net_present_value_task(cash_flows: str, discount_rate: float, initial_investment: float): + try: + net_present_value = functions.net_present_value( + cash_flows, discount_rate, initial_investment + ) + return { + "Tag": "Net present value", + "cash flows": cash_flows, + "discount rate": discount_rate, + "initial investment": initial_investment, + "Net present value": net_present_value, + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/net_worth.py b/tasks/net_worth.py new file mode 100644 index 00000000..6ff8a1b4 --- /dev/null +++ b/tasks/net_worth.py @@ -0,0 +1,15 @@ +from helpers import functions +from fastapi import HTTPException, status + +def net_worth_calculation_task(assets: float, liabilities: float, loans: float, mortgages: float): + try: + total_liabilities = liabilities + loans + mortgages + net_worth = assets - total_liabilities + return { + "Tag": "Net Worth", + "Assets": assets, + "Liabilities": total_liabilities, + "Net Worth": net_worth, + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/payback_period.py b/tasks/payback_period.py new file mode 100644 index 00000000..8ef872d0 --- /dev/null +++ b/tasks/payback_period.py @@ -0,0 +1,19 @@ +from helpers import functions +from fastapi import HTTPException, status + +def payback_period_task( + years_before_recovery: int, unrecovered_cost: float, cash_flow: float +): + try: + period = functions.payback_period( + years_before_recovery, unrecovered_cost, cash_flow + ) + return { + "Tag": "Payback period", + "Years before full recovery": years_before_recovery, + "Unrecovered cost at start of the year": unrecovered_cost, + "Cash flow during the year": cash_flow, + "Payback period": f"{period}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/periodic_lease_payment.py b/tasks/periodic_lease_payment.py new file mode 100644 index 00000000..632f4be6 --- /dev/null +++ b/tasks/periodic_lease_payment.py @@ -0,0 +1,21 @@ +from helpers import functions +from fastapi import HTTPException, status + +def periodic_lease_payment_task( + Asset_value: float, + monthly_lease_interest_rate: float, + number_of_lease_payments: float, +): + try: + pmt = functions.periodic_lease_payment( + Asset_value, monthly_lease_interest_rate, number_of_lease_payments + ) + return { + "Tag": "Periodic Lease Payment", + "Asset value": Asset_value, + "Monthly lease interest rate": monthly_lease_interest_rate, + "Number of lease payments": number_of_lease_payments, + "Periodic Lease Payment": f"{pmt}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/perpetuity_payment.py b/tasks/perpetuity_payment.py new file mode 100644 index 00000000..cd82e881 --- /dev/null +++ b/tasks/perpetuity_payment.py @@ -0,0 +1,13 @@ +from helpers import functions +from fastapi import HTTPException, status + +def perpetuity_payment_task(present_value: float, rate: float): + try: + payment = functions.perpetuity_payment(present_value, rate) + return { + "Tag": "Perpetuity Payment", + "Present Value": present_value, + "Perpetuity Payment": f"{payment}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/personal_loan.py b/tasks/personal_loan.py new file mode 100644 index 00000000..74ccb673 --- /dev/null +++ b/tasks/personal_loan.py @@ -0,0 +1,20 @@ +from helpers import functions +from fastapi import HTTPException, status + +def personal_loan_task( + loan_amount: float, interest_rate: float, loan_term_years: int, loan_start_date: str +): + try: + result = functions.personal_loan( + loan_amount, interest_rate, loan_term_years, loan_start_date + ) + return { + "Tag": "Personal Loan", + "Loan amount": loan_amount, + "Monthly payment": round(result["Monthly payment"], 2), + "Total interest paid": round(result["Total interest paid"], 2), + "Total cost loan": round(result["Total cost loan"], 2), + "Schedule": result["Schedule"], + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/personal_savings.py b/tasks/personal_savings.py new file mode 100644 index 00000000..a9283ae9 --- /dev/null +++ b/tasks/personal_savings.py @@ -0,0 +1,17 @@ +from helpers import functions +from fastapi import HTTPException, status + +def personal_savings_task(init: int, + monthly: int, + tenure: float): + try: + personal_savings = functions.personal_savings(init, monthly, tenure) + return { + "Tag": "Simple Personal Savings", + "Initial Deposit": init, + "total number of years": tenure, + "Monthly Contribution": monthly, + "Total Amount Saved": f"{total_amount}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/portfolio_return_monte_carlo.py b/tasks/portfolio_return_monte_carlo.py new file mode 100644 index 00000000..62f9360b --- /dev/null +++ b/tasks/portfolio_return_monte_carlo.py @@ -0,0 +1,20 @@ +from helpers import functions +from fastapi import HTTPException, status + +def portfolio_return_monte_carlo_task(principal: float, + expected_return_range_start: float, + expected_return_range_end: float, + volatility_range_start: float, + volatility_range_end: float, + num_simulations: float): + try: + portfolio_returns = functions.portfolio_return_monte_carlo(principal, expected_return_range_start,expected_return_range_end, volatility_range_start,volatility_range_end, num_simulations) + + return { + "Tag": "Portfolio Return Monte Carlo", + "Principal": principal, + "Number of Simulations": num_simulations, + "Portfolio Returns": f"{portfolio_returns}%" + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/preferred_stock_value.py b/tasks/preferred_stock_value.py new file mode 100644 index 00000000..a6e17685 --- /dev/null +++ b/tasks/preferred_stock_value.py @@ -0,0 +1,15 @@ +from helpers import functions +from fastapi import HTTPException, status + +def preferred_stock_value_task(dividend: float, discount_rate: float): + try: + preferred_stock_value = functions.preferred_stock_value( + dividend, discount_rate) + return { + "Tag": "Preferred stock value", + "Dividend": dividend, + "Discount Rate": discount_rate, + "Preferred Stock Value": preferred_stock_value, + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/present_value_of_annuity_due.py b/tasks/present_value_of_annuity_due.py new file mode 100644 index 00000000..868bb763 --- /dev/null +++ b/tasks/present_value_of_annuity_due.py @@ -0,0 +1,19 @@ +from helpers import functions +from fastapi import HTTPException, status + +def present_value_of_annuity_due_task( + periodic_payment: float, number_of_periods: int, rate_per_period: float +): + try: + present_value_of_annuity_due = functions.present_value_of_annuity_due( + periodic_payment, number_of_periods, rate_per_period + ) + return { + "Tag": "Present value of annuity due", + "Periodic payment": periodic_payment, + "Number of periods": number_of_periods, + "Rate Per Period": rate_per_period, + "PV of Annuity Due": f"{present_value_of_annuity_due}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/price_to_earning_ratio.py b/tasks/price_to_earning_ratio.py new file mode 100644 index 00000000..aee86de5 --- /dev/null +++ b/tasks/price_to_earning_ratio.py @@ -0,0 +1,14 @@ +from helpers import functions +from fastapi import HTTPException, status + +def price_to_earning_ratio_task(share_price: float, earnings_per_share: float): + try: + p_e_ratio = functions.price_to_earning(share_price, earnings_per_share) + return { + "Tag": "Price to Earning ratio", + "Share price": share_price, + "Earning per share": earnings_per_share, + "Price to Earning ratio": f"{p_e_ratio}%", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/profitability_index.py b/tasks/profitability_index.py new file mode 100644 index 00000000..2bb5539f --- /dev/null +++ b/tasks/profitability_index.py @@ -0,0 +1,16 @@ +from helpers import functions +from fastapi import HTTPException, status + +def profitability_index_task(initial_investment: float, pv_of_future_cash_flows: float): + try: + profitability_index = functions.profitability_index( + initial_investment, pv_of_future_cash_flows + ) + return { + "Tag": "Profitability Index", + "Initial Investment": initial_investment, + "PV of Future Cash Flows": pv_of_future_cash_flows, + "Profitability Index": profitability_index, + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/profitability_index2.py b/tasks/profitability_index2.py new file mode 100644 index 00000000..34429bd7 --- /dev/null +++ b/tasks/profitability_index2.py @@ -0,0 +1,19 @@ +from helpers import functions +from fastapi import HTTPException, status + +def profitability_index2_task( + initial_investment: float, annual_cash_flows: str, discount_rate: float +): + try: + profitability_index = functions.profitability_index2( + initial_investment, annual_cash_flows, discount_rate + ) + return { + "Tag": "profitability_index", + "initial_investment": initial_investment, + "annual_cash_flows": annual_cash_flows, + "discount_rate": discount_rate, + "profitability index": f"{profitability_index}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/project_efficiency.py b/tasks/project_efficiency.py new file mode 100644 index 00000000..b2db837d --- /dev/null +++ b/tasks/project_efficiency.py @@ -0,0 +1,17 @@ +from helpers import functions +from fastapi import HTTPException, status + +def project_efficiency_task(annual_production: float, collector_surface: float, dni: float): + try: + project_eff = functions.project_efficiency( + annual_production, collector_surface, dni + ) + return { + "Tag": "Project efficiency", + "Annual production": annual_production, + "collector surface": collector_surface, + "dni": dni, + "Discount opex": f"{project_eff}%", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/purchasing_power.py b/tasks/purchasing_power.py new file mode 100644 index 00000000..548a1c5b --- /dev/null +++ b/tasks/purchasing_power.py @@ -0,0 +1,17 @@ +from helpers import functions +from fastapi import HTTPException, status + +def purchasing_power_task(initial_amount: float, annual_inflation_rate: float, time: float): + try: + purchasing_power = functions.purchasing_power( + initial_amount, annual_inflation_rate, time + ) + return { + "Tag": "Purchasing Power", + "Initial Amount": initial_amount, + "Annual Inflation Rate": annual_inflation_rate, + "Time in years": time, + "Purchasing Power": f"{purchasing_power}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/put_call_parity.py b/tasks/put_call_parity.py new file mode 100644 index 00000000..14f68fa9 --- /dev/null +++ b/tasks/put_call_parity.py @@ -0,0 +1,16 @@ +from helpers import functions +from fastapi import HTTPException, status + +def put_call_parity_task(call_price: float, put_price: float, strike_price: float): + try: + future_amount = functions.put_call_parity( + call_price, put_price, strike_price) + return { + "Tag": "Pull Call Parity", + "Future Price": f"{future_amount}", + "Call Price": f"{call_price}", + "Put Price": f"{put_price}", + "Strike Price": f"{strike_price}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/real_gdp.py b/tasks/real_gdp.py new file mode 100644 index 00000000..1b1314cc --- /dev/null +++ b/tasks/real_gdp.py @@ -0,0 +1,14 @@ +from helpers import functions +from fastapi import HTTPException, status + +def real_gdp_task(nominal_gdp: float, gdp_deflator: float): + try: + real_gdp = functions.real_gdp(nominal_gdp, gdp_deflator) + return { + "Tag": "Real GDP", + "Nominal GDP": nominal_gdp, + "GDP Deflator": gdp_deflator, + "Real GDP": real_gdp, + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/receivables_turnover_ratio.py b/tasks/receivables_turnover_ratio.py new file mode 100644 index 00000000..a3ca0970 --- /dev/null +++ b/tasks/receivables_turnover_ratio.py @@ -0,0 +1,16 @@ +from helpers import functions +from fastapi import HTTPException, status + +def receivables_turnover_ratio_task(sales_revenue: float, avg_accounts_receivable: float): + try: + receivables_turnover_ratio = functions.receivables_turnover_ratio( + sales_revenue, avg_accounts_receivable + ) + return { + "Tag": "Receivables Turnover Ratio", + "Sales Revenue": sales_revenue, + "Avg Accounts Receivables": avg_accounts_receivable, + "Receivables Turnover Ratio": receivables_turnover_ratio, + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/refinance.py b/tasks/refinance.py new file mode 100644 index 00000000..6fa3668f --- /dev/null +++ b/tasks/refinance.py @@ -0,0 +1,41 @@ +from helpers import functions +from fastapi import HTTPException, status + +def refinance_task( + current_loan_amount: float, + current_interest_rate: float, + current_loan_term_years: int, + time_remaining_years: int, + new_interest_rate: float, + new_loan_term_years: int, + cash_out_amount: float, +): + try: + result = functions.refinance_calculator( + current_loan_amount, + current_interest_rate, + current_loan_term_years, + time_remaining_years, + new_interest_rate, + new_loan_term_years, + cash_out_amount, + ) + return { + "Tag": "Refinance", + "Current loan amount": current_loan_amount, + "Balance left on loan": round(result["Balance left on loan"], 2), + "New loan amount": round(result["New loan amount"], 2), + "Current monthly payment": round(result["Current monthly payment"], 2), + "New monthly payment": round(result["New monthly payment"], 2), + "Monthly savings": round(result["Monthly savings"], 2), + "Current interest paid left": round( + result["Current left interest paid"], 2 + ), + "New total interest paid": round(result["New total interest paid"], 2), + "Total interest saving": round(result["Total interest saving"], 2), + "Current total cost left": round(result["Current total cost left"], 2), + "New total cost loan": round(result["New total cost loan"], 2), + "Total cost saving": round(result["Total cost saving"], 2), + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/remaining_balance.py b/tasks/remaining_balance.py new file mode 100644 index 00000000..77c6ec79 --- /dev/null +++ b/tasks/remaining_balance.py @@ -0,0 +1,26 @@ +from helpers import functions +from fastapi import HTTPException, status + +def remaining_balance_task( + regular_payment: float, + interest_rate_per_period: float, + number_of_payments: float, + number_of_payments_done: float, +): + try: + B = functions.remaining_balance( + regular_payment, + interest_rate_per_period, + number_of_payments, + number_of_payments_done, + ) + return { + "Tag": "Remaining balance", + "regular_payment": regular_payment, + "interest rate per period": interest_rate_per_period, + "number of payments": number_of_payments, + "number of payments done": number_of_payments_done, + "remaining balance": B, + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/retention_ratio.py b/tasks/retention_ratio.py new file mode 100644 index 00000000..b55150c1 --- /dev/null +++ b/tasks/retention_ratio.py @@ -0,0 +1,14 @@ +from helpers import functions +from fastapi import HTTPException, status + +def retention_ratio_task(net_income: float, dividends: float): + try: + retention_ratio = functions.retention_ratio(net_income, dividends) + return { + "Tag": "Retention Ratio", + "Net Income": net_income, + "Dividends": dividends, + "Retention Ratio": retention_ratio, + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/roi.py b/tasks/roi.py new file mode 100644 index 00000000..dbe7c455 --- /dev/null +++ b/tasks/roi.py @@ -0,0 +1,17 @@ +from helpers import functions +from fastapi import HTTPException, status + +def return_on_investment_task(current_value_of_investment: float, cost_of_investment: float): + try: + roi = functions.return_on_investment( + current_value_of_investment, cost_of_investment + ) + + return { + "Tag": "Return on Investment", + "Current Value of Investment": current_value_of_investment, + "Cost of Investment": cost_of_investment, + "Return on Investment": f"{roi}%", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/roi_equity_funds.py b/tasks/roi_equity_funds.py new file mode 100644 index 00000000..7f119df6 --- /dev/null +++ b/tasks/roi_equity_funds.py @@ -0,0 +1,22 @@ +from helpers import functions +from fastapi import HTTPException, status + +def calculate_roi_equity_funds_task( + amount_invested: float, + amount_returned: float, + tenure: float, +): + try: + roi, annualized_roi = functions.calculate_roi_equity_funds( + amount_invested, amount_returned, tenure + ) + return { + "Tag": "Calculate return of investments on equity funds", + "Amount Invested": amount_invested, + "Amount Returned": amount_returned, + "Duration of investment": tenure, + "Return of Investment": f"{roi}%", + "Annualized Return": f"{annualized_roi}%", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/roth_ira.py b/tasks/roth_ira.py new file mode 100644 index 00000000..d97979fa --- /dev/null +++ b/tasks/roth_ira.py @@ -0,0 +1,26 @@ +from helpers import functions +from fastapi import HTTPException, status + +def roth_ira_task( + principal: float, + interest_rate: float, + years: int, + tax_rate: float, + annual_contribution: float, +): + try: + roth_ira_balance, taxable_saving_balance = functions.roth_ira( + principal, interest_rate, years, tax_rate, annual_contribution + ) + return { + "Tag": "Roth-IRA", + "Principal": principal, + "Interest Rate": interest_rate, + "Years": years, + "Tax Rates": tax_rate, + "Annual Contributions": annual_contribution, + "Roth Ira Balance": roth_ira_balance, + "Taxable saving Balance": taxable_saving_balance, + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/ruleof72.py b/tasks/ruleof72.py new file mode 100644 index 00000000..a232a18c --- /dev/null +++ b/tasks/ruleof72.py @@ -0,0 +1,13 @@ +from helpers import functions +from fastapi import HTTPException, status + +def rule_of_72_task(rate_of_roi: float): + try: + time_period = functions.rule_of_72(rate_of_roi) + return { + "Tag": "Rule of 72", + "Rate of ROI": rate_of_roi, + "Time period in which investment get double(in years)": f"{time_period}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/salary_calculate.py b/tasks/salary_calculate.py new file mode 100644 index 00000000..b00a14aa --- /dev/null +++ b/tasks/salary_calculate.py @@ -0,0 +1,22 @@ +from helpers import functions +from fastapi import HTTPException, status + +def salary_calculate_task( + salary_amount: float, + payment_frequency: str, + hours_worked_per_day: int, + days_worked_per_week: int, +): + try: + salary = functions.salary_calculate( + salary_amount, payment_frequency, hours_worked_per_day, days_worked_per_week + ) + + return { + "Tag": "Calculate Salary", + "Salary Amount": salary_amount, + "Payment frequency": payment_frequency, + "Salary": salary, + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/sharpe_ratio.py b/tasks/sharpe_ratio.py new file mode 100644 index 00000000..fbc639a3 --- /dev/null +++ b/tasks/sharpe_ratio.py @@ -0,0 +1,21 @@ +from helpers import functions +from fastapi import HTTPException, status + +def sharpe_ratio_task( + portfolio_return: float, + risk_free_rate: float, + standard_deviation_of_portfolio: float, +): + try: + sharpe_ratio = functions.sharpe_ratio( + portfolio_return, risk_free_rate, standard_deviation_of_portfolio + ) + return { + "Tag": "Sharpe Ratio", + "Portfolio Return": portfolio_return, + "Risk Free Rate": risk_free_rate, + "Standard Deviation of Portfolio": standard_deviation_of_portfolio, + "Sharpe Ratio": f"{sharpe_ratio}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/simple_interest_rate.py b/tasks/simple_interest_rate.py new file mode 100644 index 00000000..8ae71fb6 --- /dev/null +++ b/tasks/simple_interest_rate.py @@ -0,0 +1,16 @@ +from helpers import functions +from fastapi import HTTPException, status + +def simple_interest_rate_task(amount_paid: float, principle_amount: float, months: int): + try: + rate = functions.simple_interest_rate( + amount_paid, principle_amount, months) + return { + "Tag": "Simple Interest Rate", + "Total amount paid": amount_paid, + "Principle amount": principle_amount, + "Interest Paid": amount_paid - principle_amount, + "Interest Rate": f"{rate}%", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/social_securities.py b/tasks/social_securities.py new file mode 100644 index 00000000..57d065c4 --- /dev/null +++ b/tasks/social_securities.py @@ -0,0 +1,17 @@ +from helpers import functions +from fastapi import HTTPException, status + +def ss_task(birth_date: str, earnings: int, retirement_age: int): + + try: + monthly_benefits, future_benefits = functions.calculate_social_security( + birth_date=birth_date, + earnings=earnings, + retirement_age=retirement_age + ) + return { + f"The monthly benefits are {monthly_benefits} and future benefits are {future_benefits}" + } + + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/student_loan.py b/tasks/student_loan.py new file mode 100644 index 00000000..382030ce --- /dev/null +++ b/tasks/student_loan.py @@ -0,0 +1,16 @@ +from helpers import functions +from fastapi import HTTPException, status + +def student_loan_task(principal: int, tenure: int, interest_rate: float): + try: + student_loan = functions.student_loan(principal, tenure, interest_rate) + return { + "Tag": "Student Loan", + "Total amount to borrow": principal, + "total number of years to pay loan": tenure, + "interest rate percentage annual": interest_rate, + "total monthly cost": f"{student_loan[0]}", + "Total Amount of loan": f"{student_loan[1]}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/tax_equivalent_yield.py b/tasks/tax_equivalent_yield.py new file mode 100644 index 00000000..566aca19 --- /dev/null +++ b/tasks/tax_equivalent_yield.py @@ -0,0 +1,15 @@ +from helpers import functions +from fastapi import HTTPException, status + +def tax_equivalent_yield_task(tax_free_yield: float, tax_rate: float): + try: + tax_equivalent_yield = functions.tax_equivalent_yield( + tax_free_yield, tax_rate) + return { + "Tag": "Tax Equivalent Yield", + "Tax Free Yield": tax_free_yield, + "Tax Rate": tax_rate, + "Tax Equivalent Yield": tax_equivalent_yield, + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/time_period_required_for_growth.py b/tasks/time_period_required_for_growth.py new file mode 100644 index 00000000..21ffb6cb --- /dev/null +++ b/tasks/time_period_required_for_growth.py @@ -0,0 +1,15 @@ +from helpers import functions +from fastapi import HTTPException, status + +def time_period_required_for_growth_task(interest_rate: float, growth_factor: int): + try: + time_period_required_for_growth = functions.time_period_required_for_growth( + interest_rate, growth_factor + ) + return { + "Tag": "Time period required for exponential growth", + "interest rate": interest_rate, + "growth factor": growth_factor, + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/treynor_ratio.py b/tasks/treynor_ratio.py new file mode 100644 index 00000000..58fcbd07 --- /dev/null +++ b/tasks/treynor_ratio.py @@ -0,0 +1,19 @@ +from helpers import functions +from fastapi import HTTPException, status + +def treynor_ratio_task( + returns: list[float], risk_free_rate: float, beta: float +): + try: + ratio = functions.calculate_treynor_ratio( + returns, risk_free_rate, beta) + return { + "Tag": "Treynor Ratio", + "Returns": returns, + "Risk-free Rate": risk_free_rate, + "Beta": beta, + "Treynor Ratio": ratio, + } + except Exception as e: + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e)) \ No newline at end of file diff --git a/tasks/wacc.py b/tasks/wacc.py new file mode 100644 index 00000000..38286728 --- /dev/null +++ b/tasks/wacc.py @@ -0,0 +1,21 @@ +from helpers import functions +from fastapi import HTTPException, status + +def weighted_average_cost_of_capital_task( + firm_equity, firm_debt, cost_of_equity, cost_of_debt, corporate_tax_rate +): + try: + wacc = functions.wacc( + firm_equity, firm_debt, cost_of_equity, cost_of_debt, corporate_tax_rate + ) + return { + "Tag": "Weighted Average Cost of Capital (WACC)", + "Market value of firm's equity": firm_equity, + "Market value of firm's debt": firm_debt, + "Cost of equity": cost_of_equity, + "Cost of debt": cost_of_debt, + "Corporate tax rate": corporate_tax_rate, + "WACC": f"{wacc}%", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/weighted_average.py b/tasks/weighted_average.py new file mode 100644 index 00000000..c37d8c23 --- /dev/null +++ b/tasks/weighted_average.py @@ -0,0 +1,14 @@ +from helpers import functions +from fastapi import HTTPException, status + +def weighted_average_task(ratio: list, rates: list): + try: + weighted_average = functions.weighted_average(ratio, rates) + return { + "Tag": "Weighted Average", + "Ratio of each investment principal": ratio, + "Rates": rates, + "Weighted average : ": f"{weighted_average}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/weighted_average_of_values.py b/tasks/weighted_average_of_values.py new file mode 100644 index 00000000..e3d1708c --- /dev/null +++ b/tasks/weighted_average_of_values.py @@ -0,0 +1,16 @@ +from helpers import functions +from fastapi import HTTPException, status + +def weighted_average_of_values_task(Assigned_weight_values: str, data_point_values: str): + try: + weighted_average = functions.weighted_average_of_values( + Assigned_weight_values, data_point_values + ) + return { + "Tag": "weighted_average", + "Assigned weight values": Assigned_weight_values, + "Data point values": data_point_values, + "Weighted average": f"{weighted_average}", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/year_to_year.py b/tasks/year_to_year.py new file mode 100644 index 00000000..978cafd3 --- /dev/null +++ b/tasks/year_to_year.py @@ -0,0 +1,13 @@ +from helpers import functions +from fastapi import HTTPException, status + +def year_over_year_task(later_period_value: float, earlier_period_value: float): + try: + growth = functions.year_over_year( + later_period_value, earlier_period_value) + return { + "Tag": "Year to Year Growth", + "Year to Year growth": f"{growth}%", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/yield_to_maturity.py b/tasks/yield_to_maturity.py new file mode 100644 index 00000000..f1b422cf --- /dev/null +++ b/tasks/yield_to_maturity.py @@ -0,0 +1,18 @@ +from helpers import functions +from fastapi import HTTPException, status + +def yield_to_maturity_task( + bond_price: float, face_value: float, coupon_rate: float, years_to_maturity: float +): + try: + yield_cal = functions.yield_to_maturity( + bond_price, face_value, coupon_rate, years_to_maturity + ) + return { + "Tag": "Yield To Maturity", + "Face Value": face_value, + "Years to maturity": years_to_maturity, + "Yield to Maturity": f"{yield_cal}%", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/zero_coupoun_bond_value.py b/tasks/zero_coupoun_bond_value.py new file mode 100644 index 00000000..25a6e4fa --- /dev/null +++ b/tasks/zero_coupoun_bond_value.py @@ -0,0 +1,18 @@ +from helpers import functions +from fastapi import HTTPException, status + +def zero_coupon_bond_value_task( + face_value: float, rate_of_yield: float, time_of_maturity: float +): + try: + zcbv = functions.zero_coupon_bond_value( + face_value, rate_of_yield, time_of_maturity + ) + return { + "Tag": "Zero Coupon Bond Value", + "Face Value": face_value, + "Rate of yield": f"{rate_of_yield}%", + "Zero Coupon Bond Value": zcbv, + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/zero_coupoun_bond_yield.py b/tasks/zero_coupoun_bond_yield.py new file mode 100644 index 00000000..78b3567e --- /dev/null +++ b/tasks/zero_coupoun_bond_yield.py @@ -0,0 +1,19 @@ +from helpers import functions +from fastapi import HTTPException, status + +def zero_coupon_bond_yield_task( + face_value: float, present_value: float, time_of_maturity: float +): + try: + zcby = functions.zero_coupon_bond_yield( + face_value, present_value, time_of_maturity + ) + return { + "Tag": "Zero Coupon Bond Effective Yield", + "Face Value": face_value, + "Present Value": present_value, + "Time to maturity": time_of_maturity, + "Zero Coupon Bond Effective Yield": f"{zcby}%", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/test_main.py b/tests/test_main.py similarity index 100% rename from test_main.py rename to tests/test_main.py diff --git a/tests/test_tasks.py b/tests/test_tasks.py new file mode 100644 index 00000000..e69de29b diff --git a/validators/request_validators.py b/validators/request_validators.py new file mode 100644 index 00000000..8e845f5f --- /dev/null +++ b/validators/request_validators.py @@ -0,0 +1,858 @@ +from pydantic import BaseModel + +class SimpleInterestRateRequest(BaseModel): + amount_paid: float + principle_amount: float + months: int + +class futureSip(BaseModel): + interval_investment: float + rate_of_return: float + number_of_payments: int + +class calculatePension(BaseModel): + monthly_investment_amount: float + no_of_years: int + annuity_rates: float + annuity_purchased: float + yearly_interest_rates: float + +class paybackPeriod(BaseModel): + years_before_recovery: int + unrecovered_cost: float + cash_flow: float + +class compoundInterest(BaseModel): + principal_amount: float + interest_rate: float + years: int + compounding_period: int + +class certificateOfDeposit(BaseModel): + principal_amount: float + interest_rate: float + yrs: int + compounding_per_yr: int + +class inflation(BaseModel): + present_amount: float + inflation_rate: float + years: float + +class effectiveAnnualRate(BaseModel): + annual_interest_rate: float + compounding_period: int + +class roi(BaseModel): + current_value_of_investment: float + cost_of_investment: float + +class compoundedAnnualGrowthRate(BaseModel): + end_investment_value: float + initial_investment_value: float + years: int + +class jensensAlpha(BaseModel): + return_from_investment: float + return_of_appropriate_market_index: float + risk_free_rate: float + beta: float + +class wacc(BaseModel): + firm_equity: float + firm_debt: float + cost_of_equity: float + cost_of_debt: float + corporate_tax_rate: float + +class loanEmi(BaseModel): + principle_amount: float + annual_rate: float + months: int + +class assetPortfolio(BaseModel): + price_A: float + price_B: float + return_A: float + return_B: float + standard_dev_A: float + standard_dev_B: float + correlation: float + +class putCallParity(BaseModel): + call_price: float + put_price: float + strike_price: float + +class bep(BaseModel): + fixed_cost: float + selling_price: float + variable_cost: float + +class fcff(BaseModel): + sales: float + operating_cost: float + depreciation: float + interest: float + tax_rate: float + fcInv: float + wcInv: float + +class priceToEarningRatio(BaseModel): + share_price: float + earnings_per_share: float + +class dividendYieldRatio(BaseModel): + dividend_per_share: float + share_price: float + +class dividendPayoutRatio(BaseModel): + dividend_per_share: float + earnings_per_share: float + +class debtToIncomeRatio(BaseModel): + annual_income: float + total_debt_per_month: float + +class fixedChargesCoverageRatio(BaseModel): + earnings_before_interest_taxes: float + fixed_charge_before_tax: float + interest: float + +class inventoryShrinkageRate(BaseModel): + recorded_inventory: float + actual_inventory: float + +class markupPercentage(BaseModel): + price: float + cost: float + +class sharpeRatio(BaseModel): + return_of_portfolio: float + risk_free_rate: float + standard_deviation_of_portfolio: float + +class purchasingPower(BaseModel): + current_amount: float + current_inflation_rate: float + target_inflation_rate: float + +class monthlyEmi(BaseModel): + principal_amount: float + annual_rate: float + months: int + +class doublingTime(BaseModel): + principal_amount: float + annual_rate: float + +class weightedAverage(BaseModel): + values: list + weights: list + +class capitalAssetPricingModel(BaseModel): + risk_free_rate: float + beta: float + expected_market_return: float + +class costOfEquity(BaseModel): + risk_free_rate: float + beta: float + expected_market_return: float + +class cogs(BaseModel): + beginning_inventory: float + ending_inventory: float + cost_of_goods_sold: float + +class ruleof72(BaseModel): + rate: float + +class acidTestRatio(BaseModel): + cash: float + marketable_securities: float + accounts_receivable: float + current_liabilities: float + +class inflationAdjustedReturn(BaseModel): + nominal_return: float + inflation_rate: float + +class cogr(BaseModel): + beginning_value: float + ending_value: float + number_of_periods: int + +class currentLiabilityCoverageRatio(BaseModel): + cash_flow_from_operations: float + current_liabilities: float + +class leveredBeta(BaseModel): + unlevered_beta: float + debt_to_equity_ratio: float + tax_rate: float + +class monthlyPayment(BaseModel): + principal_amount: float + annual_rate: float + months: int + +class convexityDuration(BaseModel): + convexity: float + duration: float + change_in_yield: float + +class currentRatio(BaseModel): + current_assets: float + current_liabilities: float + +class inventoryTurnoverRatio(BaseModel): + cost_of_goods_sold: float + average_inventory: float + +class inflationRate(BaseModel): + current_price_index: float + previous_price_index: float + +class herfindalIndex(BaseModel): + market_share: list + +class discountOpex(BaseModel): + discount_rate: float + opex: float + +class projectEfficiency(BaseModel): + cost_of_project: float + present_value_of_cash_inflows: float + +class realGDP(BaseModel): + nominal_gdp: float + gdp_deflator: float + +class excessReserves(BaseModel): + deposits: float + required_reserves: float + +class discountedCashFlow(BaseModel): + cash_flow: float + discount_rate: float + time_period: int + +class gdpGrowthRate(BaseModel): + current_gdp: float + previous_gdp: float + +class creditCardEquation(BaseModel): + balance: float + interest_rate: float + monthly_payment: float + +class creditCardPayoff(BaseModel): + balance: float + interest_rate: float + monthly_payment: float + +class futureValueOfOrdinaryDue(BaseModel): + periodic_payment: float + interest_rate: float + number_of_payments: int + +class futureValueOfAnnuityDue(BaseModel): + periodic_payment: float + interest_rate: float + number_of_payments: int + +class presentValueOfAnnuityDue(BaseModel): + periodic_payment: float + interest_rate: float + number_of_payments: int + +class compoundAnnualGrowthRate(BaseModel): + beginning_value: float + ending_value: float + number_of_periods: int + +class loanToValue(BaseModel): + loan_amount: float + value_of_property: float + +class retentionRatio(BaseModel): + net_income: float + dividends: float + +class taxEquivalentYield(BaseModel): + tax_free_yield: float + tax_rate: float + +class yearToYear(BaseModel): + current_year: float + previous_year: float + +class futureValueOfAnnuity(BaseModel): + periodic_payment: float + interest_rate: float + number_of_payments: int + +class balloonBalance(BaseModel): + loan_amount: float + interest_rate: float + number_of_payments: int + +class periodicLeasePayment(BaseModel): + present_value: float + interest_rate: float + number_of_payments: int + +class weightedAverageOfValues(BaseModel): + values: list + weights: list + +class discountedPaybackPeriod(BaseModel): + cash_flow: float + discount_rate: float + +class yieldToMaturity(BaseModel): + current_bond_price: float + face_value: float + years_to_maturity: int + coupon_rate: float + +class perpetuityPayment(BaseModel): + interest_rate: float + present_value: float + +class zeroCoupounBondValue(BaseModel): + face_value: float + interest_rate: float + years_to_maturity: int + +class zeroCoupounBondYield(BaseModel): + face_value: float + current_bond_price: float + years_to_maturity: int + +class profitabilityIndex(BaseModel): + initial_investment: float + cash_flow: float + discount_rate: float + +class profitabilityIndex2(BaseModel): + initial_investment: float + cash_flow: float + discount_rate: float + number_of_years: int + +class receivablesTurnoverRatio(BaseModel): + net_credit_sales: float + average_accounts_receivable: float + +class remainingBalance(BaseModel): + loan_amount: float + interest_rate: float + number_of_payments: int + +class netPresentValue(BaseModel): + initial_investment: float + cash_flow: float + discount_rate: float + +class leverageRatioIncome(BaseModel): + total_debt: float + net_income: float + +class leverageRatioEquity(BaseModel): + total_debt: float + total_equity: float + +class timePeriodRequiredForGrowth(BaseModel): + present_value: float + future_value: float + rate: float + +class preferredStockValue(BaseModel): + dividend: float + required_rate_of_return: float + +class assetTurnoverRatio(BaseModel): + net_sales: float + average_total_assets: float + +class bidAskSpread(BaseModel): + bid_price: float + ask_price: float + +class calculatePeriodFV(BaseModel): + present_value: float + future_value: float + rate: float + +class balloonLoanPayment(BaseModel): + loan_amount: float + interest_rate: float + number_of_payments: int + +class monthlyLeasePayment(BaseModel): + present_value: float + interest_rate: float + number_of_payments: int + +class estimate401k(BaseModel): + current_age: float + retirement_age: float + current_401k_balance: float + annual_contribution: float + annual_salary: float + annual_raise: float + employer_match: float + employer_max_match: float + +class rothIra(BaseModel): + current_age: float + retirement_age: float + annual_contribution: float + annual_salary: float + annual_raise: float + current_roth_balance: float + expected_annual_return: float + +class mortgageAmortization(BaseModel): + loan_amount: float + interest_rate: float + number_of_payments: int + +class enterpriseValue(BaseModel): + market_capitalization: float + total_debt: float + cash_and_cash_equivalents: float + +class salaryCalculate(BaseModel): + salary: float + pay_frequency: str + +class personalLoan(BaseModel): + loan_amount: float + interest_rate: float + number_of_payments: int + +class lumpsum(BaseModel): + initial_investment: float + interest_rate: float + number_of_payments: int + +class refinance(BaseModel): + current_loan_balance: float + current_interest_rate: float + current_loan_term: int + new_interest_rate: float + new_loan_term: int + +class commissionCalc(BaseModel): + sales_price: float + commission_rate: float + commission: float + +class collegeCost(BaseModel): + tuition_fee: float + annual_increase: float + years: int + +class dilutedEps(BaseModel): + net_income: float + weighted_average_shares: float + dilutive_securities: float + +class asdcr(BaseModel): + net_operating_income: float + total_debt_service: float + +class calculateGst(BaseModel): + price: float + gst_rate: float + +class calculateMarketCap(BaseModel): + price_per_share: float + number_of_shares: float + +class calculateExpectedReturnOfPortfolio(BaseModel): + expected_return_of_asset_1: float + expected_return_of_asset_2: float + weight_of_asset_1: float + weight_of_asset_2: float + +class calculateFinancialLeverage(BaseModel): + total_assets: float + total_equity: float + +class calculateGratuity(BaseModel): + basic_salary: float + dearness_allowance: float + number_of_years: float + gratuity_rate: float + +class calculateMacaulayDuration(BaseModel): + cash_flow: float + discount_rate: float + time_period: int + +class calculateNetProfitMargin(BaseModel): + net_income: float + net_sales: float + +class calculatePostTaxReturnPercentage(BaseModel): + pre_tax_return: float + tax_rate: float + +class calculateSalary(BaseModel): + salary: float + pay_frequency: str + +class capitalGainsYield(BaseModel): + initial_price: float + ending_price: float + dividends: float + +class capitalizationRate(BaseModel): + net_operating_income: float + property_value: float + +class freeCashFlowToEquity(BaseModel): + net_income: float + capital_expenditure: float + change_in_working_capital: float + debt_issued: float + debt_repaid: float + +class loanAffordability(BaseModel): + monthly_income: float + monthly_debt: float + interest_rate: float + loan_term: int + +class bondEquivalentYield(BaseModel): + face_value: float + price: float + days_to_maturity: int + +class calculateVat(BaseModel): + price: float + vat_rate: float + +class loanToValueRatio(BaseModel): + loan_amount: float + value_of_property: float + +class mortrage(BaseModel): + loan_amount: float + interest_rate: float + number_of_payments: int + +class netWorth(BaseModel): + assets: float + liabilities: float + +class personalSavings(BaseModel): + annual_salary: float + monthly_expenses: float + savings_rate: float + annual_raise: float + current_savings: float + years: int + +class portfolioReturnMonteCarlo(BaseModel): + initial_investment: float + annual_contribution: float + annual_return: float + standard_deviation: float + years: int + iterations: int + +class calculatePeriodFV(BaseModel): + present_value: float + future_value: float + rate: float + +class balloonLoanPayment(BaseModel): + loan_amount: float + interest_rate: float + number_of_payments: int + +class monthlyLeasePayment(BaseModel): + present_value: float + interest_rate: float + number_of_payments: int + +class estimate401k(BaseModel): + current_age: float + retirement_age: float + current_401k_balance: float + annual_contribution: float + annual_salary: float + annual_raise: float + employer_match: float + employer_max_match: float + +class rothIra(BaseModel): + current_age: float + retirement_age: float + annual_contribution: float + annual_salary: float + annual_raise: float + current_roth_balance: float + expected_annual_return: float + +class mortgageAmortization(BaseModel): + loan_amount: float + interest_rate: float + number_of_payments: int + +class enterpriseValue(BaseModel): + market_capitalization: float + total_debt: float + cash_and_cash_equivalents: float + +class salaryCalculate(BaseModel): + salary: float + pay_frequency: str + +class personalLoan(BaseModel): + loan_amount: float + interest_rate: float + number_of_payments: int + +class lumpsum(BaseModel): + initial_investment: float + interest_rate: float + number_of_payments: int + +class refinance(BaseModel): + current_loan_balance: float + current_interest_rate: float + current_loan_term: int + new_interest_rate: float + new_loan_term: int + +class commissionCalc(BaseModel): + sales_price: float + commission_rate: float + commission: float + +class collegeCost(BaseModel): + tuition_fee: float + annual_increase: float + years: int + +class dilutedEps(BaseModel): + net_income: float + weighted_average_shares: float + dilutive_securities: float + +class asdcr(BaseModel): + net_operating_income: float + total_debt_service: float + +class calculateGst(BaseModel): + price: float + gst_rate: float + +class calculateMarketCap(BaseModel): + price_per_share: float + number_of_shares: float + +class calculateRetirementGoals(BaseModel): + current_age: float + retirement_age: float + annual_salary: float + annual_savings: float + retirement_savings: float + retirement_expenses: float + retirement_income: float + retirement_inflation: float + +class calculateExpectedReturnOfPortfolio(BaseModel): + expected_return_of_asset_1: float + expected_return_of_asset_2: float + weight_of_asset_1: float + weight_of_asset_2: float + +class calculateFinancialLeverage(BaseModel): + total_assets: float + total_equity: float + +class calculateGratuity(BaseModel): + basic_salary: float + dearness_allowance: float + number_of_years: float + gratuity_rate: float + +class calculateMacaulayDuration(BaseModel): + cash_flow: float + discount_rate: float + time_period: int + +class calculateNetProfitMargin(BaseModel): + net_income: float + net_sales: float + +class calculatePostTaxReturnPercentage(BaseModel): + pre_tax_return: float + tax_rate: float + +class calculateSalary(BaseModel): + salary: float + pay_frequency: str + +class capitalGainsYield(BaseModel): + initial_price: float + ending_price: float + dividends: float + +class capitalizationRate(BaseModel): + net_operating_income: float + property_value: float + +class freeCashFlowToEquity(BaseModel): + net_income: float + capital_expenditure: float + change_in_working_capital: float + debt_issued: float + debt_repaid: float + +class loanAffordability(BaseModel): + monthly_income: float + monthly_debt: float + interest_rate: float + loan_term: int + +class bondEquivalentYield(BaseModel): + face_value: float + price: float + days_to_maturity: int + +class calculateVat(BaseModel): + price: float + vat_rate: float + +class loanToValueRatio(BaseModel): + loan_amount: float + value_of_property: float + +class mortrage(BaseModel): + loan_amount: float + interest_rate: float + number_of_payments: int + +class netWorth(BaseModel): + assets: float + liabilities: float + +class personalSavings(BaseModel): + annual_salary: float + monthly_expenses: float + savings_rate: float + annual_raise: float + current_savings: float + years: int + +class portfolioReturnMonteCarlo(BaseModel): + initial_investment: float + annual_contribution: float + annual_return: float + standard_deviation: float + years: int + iterations: int + +class calculatePeriodFV(BaseModel): + present_value: float + future_value: float + rate: float + +class balloonLoanPayment(BaseModel): + loan_amount: float + interest_rate: float + number_of_payments: int + +class monthlyLeasePayment(BaseModel): + present_value: float + interest_rate: float + number_of_payments: int + +class estimate401k(BaseModel): + current_age: float + retirement_age: float + current_401k_balance: float + annual_contribution: float + annual_salary: float + annual_raise: float + employer_match: float + employer_max_match: float + +class rothIra(BaseModel): + current_age: float + retirement_age: float + annual_contribution: float + annual_salary: float + annual_raise: float + current_roth_balance: float + expected_annual_return: float + +class mortgageAmortization(BaseModel): + loan_amount: float + interest_rate: float + number_of_payments: int + +class enterpriseValue(BaseModel): + market_capitalization: float + total_debt: float + cash_and_cash_equivalents: float + +class salaryCalculate(BaseModel): + salary: float + pay_frequency: str + +class personalLoan(BaseModel): + loan_amount: float + interest_rate: float + number_of_payments: int + +class lumpsum(BaseModel): + initial_investment: float + interest_rate: float + number_of_payments: int + +class refinance(BaseModel): + current_loan_balance: float + current_interest_rate: float + current_loan_term: int + new_interest_rate: float + new_loan_term: int + +class commissionCalc(BaseModel): + sales_price: float + commission_rate: float + commission: float + +class collegeCost(BaseModel): + tuition_fee: float + annual_increase: float + years: int + +class dilutedEps(BaseModel): + net_income: float + weighted_average_shares: float + dilutive_securities: float + +class asdcr(BaseModel): + net_operating_income: float + total_debt_service: float + +class calculateGst(BaseModel): + price: float + gst_rate: float + +class calculateMarketCap(BaseModel): + price_per_share: float + number_of_shares: float + +class calculateBvps(BaseModel): + total_equity: float + number_of_shares: float \ No newline at end of file From e21dbd40bd387cbcfb7444ee50e6a27a1d342a6c Mon Sep 17 00:00:00 2001 From: Subho Ghosh <93722719+ighoshsubho@users.noreply.github.com> Date: Thu, 29 Jun 2023 18:24:30 +0530 Subject: [PATCH 23/66] V2: Updated CONTRIBUTING.md --- CONTRIBUTING.md | 34 ++++++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2a9daa9d..ab6b84c6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -21,6 +21,12 @@ fintect-api β”‚ β””β”€β”€β”€πŸ“‚helpers β”‚ β”‚ { Python functions for different calculations } +β”‚ +β””β”€β”€β”€πŸ“‚tasks +β”‚ β”‚ { Python functions for different tasks } +β”‚ +β””β”€β”€β”€πŸ“‚validators +β”‚ β”‚ { Pydantic Models for different validations } πŸ“„.gitignore πŸ“„CONTRIBUTING.md @@ -112,14 +118,18 @@ def simple_interest_rate(amount_paid:float, principle_amount:float, months:int): ``` + Cross-validate your endpoint output from some online calculators available or even manually. -+ Once the function is ready, create an endpoint in the `main.py` file following all the good practices of Fast API. ++ After completing with creating the function, create the request validation in `validators/request_validation.py` like this - + +```python +class SimpleInterestRateRequest(BaseModel): + amount_paid: float + principle_amount: float + months: int +``` + ++ Once the validation is done, create a task called `simple_interest.py` in `./tasks` and the task like this - ```python -@app.get( - "/simple_interest_rate", - tags=["simple_interest_rate"], - description="Calculate simple interest rates", -) def simple_interest_rate(amount_paid: float, principle_amount: float, months: int): try: rate = functions.simple_interest_rate(amount_paid, principle_amount, months) @@ -134,6 +144,18 @@ def simple_interest_rate(amount_paid: float, principle_amount: float, months: in return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) ``` ++ Once the task is ready, create an endpoint in the `main.py` file following all the good practices of Fast API. + +```python +@app.get( + "/simple_interest_rate", + tags=["simple_interest_rate"], + description="Calculate simple interest rates", +) +def simple_interest_rate(request: SimpleInterestRateRequest): + return simple_interest_rate_task(request.amount_paid, request.principle_amount, request.months) +``` + +Also add your funtion in `ENDPOINTS.md`. ``` **GET** `/simple_interest_rate` From 35fceab7928949a7ad245721cd8ff769e04547bc Mon Sep 17 00:00:00 2001 From: ighoshsubho Date: Thu, 29 Jun 2023 19:22:17 +0530 Subject: [PATCH 24/66] V2: Authentication --- main.py | 39 +++++++++++++++++++++++++++++++++------ 1 file changed, 33 insertions(+), 6 deletions(-) diff --git a/main.py b/main.py index ce5232c6..6b97957f 100644 --- a/main.py +++ b/main.py @@ -1,4 +1,7 @@ -from fastapi import FastAPI +from fastapi import FastAPI, Depends, HTTPException, status +from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials +from fastapi.responses import JSONResponse +import jwt # Importing all the tasks from tasks.simple_interest_rate import simple_interest_rate_task @@ -260,10 +263,33 @@ def index(): }, } +class UnauthorizedException(HTTPException): + def __init__(self, detail="Unauthorized"): + super().__init__( + status_code=status.HTTP_401_UNAUTHORIZED, + detail=detail, + headers={"WWW-Authenticate": "Bearer"}, + ) + +# Validate access token (Not for all endpoints) +def validate_access_token(credentials: HTTPAuthorizationCredentials = Depends(HTTPBearer())): + try: + token = credentials.credentials + payload = jwt.decode(token,"fintech-api", algorithms=["HS256"]) + return payload + except jwt.exceptions.DecodeError: + raise UnauthorizedException() + + +# Endpoint to generate access token +@app.get("/generate-access-token") +def generate_access_token(): + token = jwt.encode({},"fintech-api", algorithm="HS256") + return {"access_token": token} # Endpoints to calculate simple interest. -@app.get( +@app.post( "/simple_interest_rate", tags=["simple_interest_rate"], description="Calculate simple interest rates", @@ -273,19 +299,20 @@ def simple_interest_rate(request: SimpleInterestRateRequest): # Endpoints to calculate Future sip -@app.get( +@app.post( "/future_sip", tags=["future_sip"], description="Calculate Future Value of SIP", ) def future_sip( request: futureSip, + payload: dict = Depends(validate_access_token) ): return future_sip_task(request.interval_investment, request.rate_of_return, request.number_of_payments) # Endpoints to calculate Future value -@app.get( +@app.post( "/calculate_pension", tags=["calculate_pension"], description="Calculate pension", @@ -297,7 +324,7 @@ def calculate_pension( # endpoint for payback period -@app.get( +@app.post( "/payback_period", tags=["payback_period_years"], description="Calculate payback period", @@ -309,7 +336,7 @@ def payback_period( # Endpoints to calculate Compound Interest. -@app.get( +@app.post( "/compound_interest", tags=["compound_interest_amount"], description="Calculate compound interest amount", From a18c170a8294df6d9baff0f9de1eadad3906e228 Mon Sep 17 00:00:00 2001 From: Subho Ghosh <93722719+ighoshsubho@users.noreply.github.com> Date: Thu, 29 Jun 2023 19:22:53 +0530 Subject: [PATCH 25/66] V2: Created DOCUMENTATION.md --- DOCUMENTATION.md | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 DOCUMENTATION.md diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md new file mode 100644 index 00000000..4ce85ec1 --- /dev/null +++ b/DOCUMENTATION.md @@ -0,0 +1,8 @@ +| Endpoint | Description | Parameters | +|---------------------------|----------------------------------------|---------------------------------------------------------| +| GET /simple_interest_rate | Calculate simple interest rates | - `amount_paid` (float): The amount paid. | +| | | - `principle_amount` (float): The principle amount. | +| | | - `months` (int): The number of months. | +| GET /future_sip | Calculate Future Value of SIP | - `interval_investment` (float): The interval investment| +| | | - `rate_of_return` (float): The rate of return. | +| | | - `number_of_payments` (int): The number of payments. | From 9d83b1df47c13cc84d24d65105bfd52a424b37ec Mon Sep 17 00:00:00 2001 From: Subho Ghosh <93722719+ighoshsubho@users.noreply.github.com> Date: Thu, 29 Jun 2023 19:30:58 +0530 Subject: [PATCH 26/66] V2.1:Updated CONTRIBUTING.md --- CONTRIBUTING.md | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ab6b84c6..40fd019c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -147,7 +147,7 @@ def simple_interest_rate(amount_paid: float, principle_amount: float, months: in + Once the task is ready, create an endpoint in the `main.py` file following all the good practices of Fast API. ```python -@app.get( +@app.post( "/simple_interest_rate", tags=["simple_interest_rate"], description="Calculate simple interest rates", @@ -158,18 +158,22 @@ def simple_interest_rate(request: SimpleInterestRateRequest): +Also add your funtion in `ENDPOINTS.md`. ``` -**GET** `/simple_interest_rate` +**POST** `/simple_interest_rate` -- Required parameters : `amount_paid`, `principle_amount` and `months` +- Request body : `{ + "amount_paid": 20.23, + "principle_amount": 30.9, + "months": 5 +}` - Sample output ```py { - "Tag": "Simple Interest Rate", - "Total amount paid": 5000.0, - "Principle amount": 4500.0, - "Interest Paid": 500.0, - "Interest Rate": "11.11111111111111%" + "Tag": "Simple Interest Rate", + "Total amount paid": 20.23, + "Principle amount": 30.9, + "Interest Paid": -10.669999999999998, + "Interest Rate": "-82.87378640776697%" } ``` ``` From 261c1a8f823e28b707fca1ea5ff62c3a6b8bced0 Mon Sep 17 00:00:00 2001 From: Subho Ghosh <93722719+ighoshsubho@users.noreply.github.com> Date: Fri, 30 Jun 2023 08:23:57 +0530 Subject: [PATCH 27/66] V2: Updated Readme.md --- Readme.md | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index f9bbc7a6..56f0e249 100644 --- a/Readme.md +++ b/Readme.md @@ -1,5 +1,5 @@ -

FinTech API

+

FinTech API v2

Welcome to FinTech API, our powerful API is designed to simplify your life by offering a wide range of financial calculations at your fingertips. From simple interest and compound interest to return on investment (ROI) and more, FinTech APIzap provides the tools you need to handle a variety of financial tasks effortlessly such as annual percentage rate (APR), FHA loans, debt-to-income ratio and income related calculations. Whether you're building a web app, mobile application, or even a chrome extension, integrating our API is a breeze. You can focus on the core aspects of your project while leaving the financial calculations to us.

@@ -22,6 +22,14 @@ Welcome to FinTech API, our powerful API is designed to simplify your life by of ## ✨ Features +- **Modular structure**: Not the API has a clean structure which benifits in improved code organizationqn and enhanced reusability of components + +- **Request validation**: It improves security, prevents errors and vulnerabilities to the API + +- **API Docs**: API documentation provides clear and comprehensive guidance to developers, simplifies integration and usage, promotes rapid adoption + +- **Authentication**: And finally the API has authentication enabled, for endpoints with much latency calculation, we can provide authentication which will enhance security. + - **User-Friendly Integration**: Seamlessly integrate the FinTech APIzap into your web app, mobile application, or chrome extension with our user-friendly API. - **Fast and Reliable**: Enjoy a fast and reliable API service, ensuring quick response times and minimal downtime. From 44698ab55253dffb705b1e973e48957c7f434815 Mon Sep 17 00:00:00 2001 From: Subho Ghosh <93722719+ighoshsubho@users.noreply.github.com> Date: Fri, 30 Jun 2023 08:30:45 +0530 Subject: [PATCH 28/66] V2.2: Updated CONTRIBUTING.md --- CONTRIBUTING.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 40fd019c..f7d9f1f7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -176,6 +176,13 @@ def simple_interest_rate(request: SimpleInterestRateRequest): "Interest Rate": "-82.87378640776697%" } ``` ++Update the Docs +``` +|---------------------------|----------------------------------------|---------------------------------------------------------| +| GET /simple_interest_rate | Calculate simple interest rates | - `amount_paid` (float): The amount paid. | +| | | - `principle_amount` (float): The principle amount. | +| | | - `months` (int): The number of months. | +``` ``` + And that's it, you are now ready to make your pull request. From f0f211601b8b60f0b0d36cbe78e6718c0cdc8a17 Mon Sep 17 00:00:00 2001 From: Ritik Raj Date: Fri, 30 Jun 2023 20:26:15 +0530 Subject: [PATCH 29/66] removed redundant compounded annual growth rate --- ENDPOINTS.md | 14 ------------- helpers/functions.py | 18 ----------------- main.py | 28 -------------------------- tasks/compound_annual_growth_rate.py | 19 ----------------- tasks/compounded_annual_growth_rate.py | 20 ------------------ tests/test_main.py | 14 ------------- 6 files changed, 113 deletions(-) delete mode 100644 tasks/compound_annual_growth_rate.py delete mode 100644 tasks/compounded_annual_growth_rate.py diff --git a/ENDPOINTS.md b/ENDPOINTS.md index 0b1bb25f..eef07088 100644 --- a/ENDPOINTS.md +++ b/ENDPOINTS.md @@ -105,20 +105,6 @@ } ``` -**GET** `/compounded_annual_growth_rate` - -- Required parameters : `end_investment_value`, `initial_investment_value` and`years` -- Sample output - -```py -{ - "Tag":"Compounded Annual Growth Rate", - "End investment value":100000, - "Initial investment value":70000, - "Years":3, - "Compunded Annual Growth Rate":0.12624788 -} -``` **GET** `/asset_portfolio` diff --git a/helpers/functions.py b/helpers/functions.py index 7ba95169..354e7750 100644 --- a/helpers/functions.py +++ b/helpers/functions.py @@ -101,15 +101,6 @@ def return_on_investment(current_value_of_investment: float, cost_of_investment: return decimal_to_percent(roi) -# Function to calculate Compounded Annual Growth Rate (CAGR) -def compounded_annual_growth_rate( - end_investment_value: float, initial_investment_value: float, years: int -): - n = 1 / years - cagr = (end_investment_value / initial_investment_value) ** n - 1 - return cagr - - # Function to calculate Jensens Alpha def jensens_alpha( return_from_investment: float, @@ -650,15 +641,6 @@ def present_value_of_annuity_due( return present_value_of_annuity_due -# function to calculate compound annual growth rate -def compound_annual_growth_rate_1( - ending_value: float, beginning_value: float, number_of_periods: float -): - a = (ending_value // beginning_value) ** (1 // number_of_periods) - cagr = a - 1 - return cagr - - # Function to calculate loan to value def loan_to_value(mortage_value: float, appraised_value: float): ratio = mortage_value / appraised_value diff --git a/main.py b/main.py index 6b97957f..5b56c1e1 100644 --- a/main.py +++ b/main.py @@ -12,7 +12,6 @@ from tasks.certificate_of_deposit import certificate_of_deposit_task from tasks.inflation import inflation_task from tasks.roi import return_on_investment_task -from tasks.compounded_annual_growth_rate import compounded_annual_growth_rate_task from tasks.jensens_alpha import jensens_alpha_task from tasks.social_securities import ss_task from tasks.tax_equivalent_yield import tax_equivalent_yield_task @@ -48,7 +47,6 @@ from tasks.monthly_payment import monthly_payment_task from tasks.convexity_duration import duration_task from tasks.current_ratio import current_ratio_task -from tasks.compound_annual_growth_rate import compound_annual_growth_rate_1_task from tasks.credit_card_equation import credit_card_equation_task from tasks.credit_card_payoff import credit_card_payoff_task from tasks.discount_opex import discount_opex_task @@ -171,7 +169,6 @@ def index(): "/inflation": "Calculate Inflated amount", "/effective_annual_rate": "Calculate Effective Annual Rate", "/roi": "Calculate return on investment", - "/compounded_annual_growth_rate": "Calculate compounded annual growth rate", "/jensens_alpha": "Calculate Jensen's Alpha of a market return", "/wacc": "Calculate Weighted Average Cost of Capital (WACC)", "/loan_emi": "Calculate Loan EMI", @@ -381,18 +378,6 @@ def return_on_investment(current_value_of_investment: float, cost_of_investment: return return_on_investment_task(current_value_of_investment, cost_of_investment) -# Endpoint to calculate Compounded Annual Growth Rate. -@app.get( - "/compounded_annual_growth_rate", - tags=["compounded_annual_growth_rate"], - description="Calculate compounded annual growth rate", -) -def compounded_annual_growth_rate( - end_investment_value: float, initial_investment_value: float, years: int -): - return compounded_annual_growth_rate_task( end_investment_value, initial_investment_value, years) - - # Endpoint to calculate Jensen's Alpha @app.get( "/jensens_alpha", @@ -933,19 +918,6 @@ def present_value_of_annuity_due( return present_value_of_annuity_due_task( periodic_payment, number_of_periods, rate_per_period) -@app.get( - "/compound_annual_growth_rate", - tags=["compound_annual_growth_rate"], - description="Calculating compound annual growth rate", -) -def compound_annual_growth_rate_1( - ending_value: float, beginning_value: float, number_of_periods: float -): - return compound_annual_growth_rate_1_task( - ending_value, beginning_value, number_of_periods - ) - - # Endpoint to calculate loan to value @app.get( "/loan_to_value", diff --git a/tasks/compound_annual_growth_rate.py b/tasks/compound_annual_growth_rate.py deleted file mode 100644 index 58d21228..00000000 --- a/tasks/compound_annual_growth_rate.py +++ /dev/null @@ -1,19 +0,0 @@ -from helpers import functions -from fastapi import HTTPException, status - -def compound_annual_growth_rate_1_task( - ending_value: float, beginning_value: float, number_of_periods: float -): - try: - cagr = functions.compound_annual_growth_rate_1( - ending_value, beginning_value, number_of_periods - ) - return { - "Tag": "compound annual growth rate 1", - "ending_value": ending_value, - "beginning value": beginning_value, - "Number of periods": number_of_periods, - "compound annual growth rate": f"{cagr}%", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/compounded_annual_growth_rate.py b/tasks/compounded_annual_growth_rate.py deleted file mode 100644 index aeaa0d15..00000000 --- a/tasks/compounded_annual_growth_rate.py +++ /dev/null @@ -1,20 +0,0 @@ -from helpers import functions -from fastapi import HTTPException, status - -def compounded_annual_growth_rate_task( - end_investment_value: float, initial_investment_value: float, years: int -): - try: - cagr = functions.compounded_annual_growth_rate( - end_investment_value, initial_investment_value, years - ) - - return { - "Tag": "Compounded Annual Growth Rate", - "End investment value": end_investment_value, - "Initial investment value": initial_investment_value, - "Years": years, - "Compounded Annual Growth Rate": f"{cagr}%", - } - except: - return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tests/test_main.py b/tests/test_main.py index d8531a11..6c44a0b6 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -222,20 +222,6 @@ def test_return_on_investment(): "Return on Investment": "1891.1764705882351%" } -def test_compounded_annual_growth_rate(): - response = client.get( - "http://127.0.0.1:8000/compounded_annual_growth_rate?end_investment_value=456&initial_investment_value=113&years=4" - ) - assert response.status_code == status.HTTP_200_OK - - assert response.json() == { - "Tag": "Compounded Annual Growth Rate", - "End investment value": 456, - "Initial investment value": 113, - "Years": 4, - "Compounded Annual Growth Rate": "0.4173320235605005%" -} - def test_jensens_alpha(): response = client.get( "http://127.0.0.1:8000/jensens_alpha?return_from_investment=4566&return_of_appropriate_market_index=32&risk_free_rate=3&beta=45" From 43f116ee5757f14f9b764678d1932bf3da2480d4 Mon Sep 17 00:00:00 2001 From: Nishitbariya <85815172+Nishitbaria@users.noreply.github.com> Date: Sat, 1 Jul 2023 12:08:55 +0530 Subject: [PATCH 30/66] =?UTF-8?q?GitHub=20Workflow=20Created=20=E2=9C=94?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/lint.yml | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 .github/workflows/lint.yml diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 00000000..515d5a0f --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,27 @@ +name: Prettier Code Formatting + +on: + push: + branches: + - main + - develop + pull_request: + branches: + - main + - develop + +jobs: + prettier-lint: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v3 + + - name: Run prettier + run: | + npx prettier --check . + prettier_exit_code=$? + if [ $prettier_exit_code -ne 0 ]; then + echo "Prettier check failed. Please run 'npx prettier --write .' to fix formatting issues." + exit 1 + fi From 16e8463cfeb74faaccad4dca49840cc9bc841e69 Mon Sep 17 00:00:00 2001 From: Shivansh Date: Sat, 1 Jul 2023 15:32:16 +0530 Subject: [PATCH 31/66] fixing some bugs in endpoints --- helpers/functions.py | 47 +++++---------------------------- main.py | 4 +-- tasks/credit_card_payoff.py | 2 +- tasks/price_to_earning_ratio.py | 2 +- tasks/sharpe_ratio.py | 4 +-- 5 files changed, 13 insertions(+), 46 deletions(-) diff --git a/helpers/functions.py b/helpers/functions.py index 7ba95169..ff1e572d 100644 --- a/helpers/functions.py +++ b/helpers/functions.py @@ -250,9 +250,8 @@ def sharpe_ratio( risk_free_rate: float, standard_deviation_of_portfolio: float, ): - sharpe_ratio = (portfolio_return - risk_free_rate) / \ - standard_deviation_of_portfolio - return sharpe_ratio + sharpe_ratio_val = (portfolio_return - risk_free_rate) / standard_deviation_of_portfolio + return sharpe_ratio_val # Function to calculate Purchasing Power @@ -415,7 +414,6 @@ def duration( 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) @@ -565,9 +563,9 @@ def credit_card_payoff( cards.append( { "index": i, - "debt": debts[i], - "minimum_payment": minimum_payments[i], - "interest_rate": interest_rates[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, @@ -710,8 +708,8 @@ def 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)) - ) / np.log(1 + rate) + 1 / (1 - (outflow * rate / periodic_cash_flow)),10 + ) / np.log(1 + rate,10) return discounted_payback_period @@ -1770,37 +1768,6 @@ def calculate_salary(base: int, # function to calculate the Sharpe ratio in Python - -def sharpe_ratio(returns, risk_free_rate): - """ - Calculate the Sharpe ratio given a series of returns and the risk-free rate. - - Parameters: - - returns (array-like): An array-like object containing the returns of an investment/portfolio. - - risk_free_rate (float): The risk-free rate of return. - - Returns: - - float: The calculated Sharpe ratio. - """ - avg_return = np.mean(returns) - std_dev = np.std(returns) - - sharpe_ratio = (avg_return - risk_free_rate) / std_dev - - return sharpe_ratio - -# You can use this function by passing your investment/portfolio returns and the risk-free rate to it. For example: - - -returns = [0.05, 0.03, 0.02, 0.04, 0.06] # Example returns -risk_free_rate = 0.02 # Example risk-free rate - -sharpe = sharpe_ratio(returns, risk_free_rate) -print(f"The Sharpe ratio is: {sharpe}") - -# Function to calculate Loan to Value Ratio - - def loan_to_value_ratio( loan_amount: float, value_of_collateral: float): diff --git a/main.py b/main.py index 6b97957f..27be1ce0 100644 --- a/main.py +++ b/main.py @@ -611,7 +611,7 @@ def doubling_time(r: float): # Endpoint to calculate weighted average -@app.get( +@app.post( "/weighted_average", tags=["weighted_average"], description="Weighted Average", @@ -884,7 +884,7 @@ def credit_card_equation( return credit_card_equation_task(balance, monthly_payment, daily_interest_rate) -@app.get( +@app.post( "/credit_card_payoff", tags=["credit_card_payoff"], description="Credit Card Payoff using Debt Avalanche method", diff --git a/tasks/credit_card_payoff.py b/tasks/credit_card_payoff.py index f6956444..54d68c9d 100644 --- a/tasks/credit_card_payoff.py +++ b/tasks/credit_card_payoff.py @@ -18,5 +18,5 @@ def credit_card_payoff_task( "Interest paid": [r["interest_paid"] for r in result], "Total Payment": [r["total_payment"] for r in result], } - except: + except: return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/price_to_earning_ratio.py b/tasks/price_to_earning_ratio.py index aee86de5..3d764007 100644 --- a/tasks/price_to_earning_ratio.py +++ b/tasks/price_to_earning_ratio.py @@ -3,7 +3,7 @@ def price_to_earning_ratio_task(share_price: float, earnings_per_share: float): try: - p_e_ratio = functions.price_to_earning(share_price, earnings_per_share) + p_e_ratio = functions.price_to_earning_ratio(share_price, earnings_per_share) return { "Tag": "Price to Earning ratio", "Share price": share_price, diff --git a/tasks/sharpe_ratio.py b/tasks/sharpe_ratio.py index fbc639a3..fb55c765 100644 --- a/tasks/sharpe_ratio.py +++ b/tasks/sharpe_ratio.py @@ -7,7 +7,7 @@ def sharpe_ratio_task( standard_deviation_of_portfolio: float, ): try: - sharpe_ratio = functions.sharpe_ratio( + sharpe_ratio_val = functions.sharpe_ratio( portfolio_return, risk_free_rate, standard_deviation_of_portfolio ) return { @@ -15,7 +15,7 @@ def sharpe_ratio_task( "Portfolio Return": portfolio_return, "Risk Free Rate": risk_free_rate, "Standard Deviation of Portfolio": standard_deviation_of_portfolio, - "Sharpe Ratio": f"{sharpe_ratio}", + "Sharpe Ratio": f"{sharpe_ratio_val}", } except: return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file From 212f9dd0134613e15a4b8fd8959c95d7139ac82b Mon Sep 17 00:00:00 2001 From: Shivansh Date: Sat, 1 Jul 2023 16:25:55 +0530 Subject: [PATCH 32/66] Adding Endpoint to calculate Capital Asset Pricing Model (CAPM) --- DOCUMENTATION.md | 20 ++++++++++++-------- ENDPOINTS.md | 17 +++++++++++++++++ helpers/functions.py | 5 +++++ main.py | 14 ++++++++++++-- tasks/calculate_capm.py | 16 ++++++++++++++++ validators/request_validators.py | 7 ++++++- 6 files changed, 68 insertions(+), 11 deletions(-) create mode 100644 tasks/calculate_capm.py diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 4ce85ec1..c327dc80 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -1,8 +1,12 @@ -| Endpoint | Description | Parameters | -|---------------------------|----------------------------------------|---------------------------------------------------------| -| GET /simple_interest_rate | Calculate simple interest rates | - `amount_paid` (float): The amount paid. | -| | | - `principle_amount` (float): The principle amount. | -| | | - `months` (int): The number of months. | -| GET /future_sip | Calculate Future Value of SIP | - `interval_investment` (float): The interval investment| -| | | - `rate_of_return` (float): The rate of return. | -| | | - `number_of_payments` (int): The number of payments. | +| Endpoint | Description | Parameters | +|-----------------------------|----------------------------------------------|-----------------------------------------------------------| +| GET /simple_interest_rate | Calculate simple interest rates | - `amount_paid` (float): The amount paid. | +| | | - `principle_amount` (float): The principle amount. | +| | | - `months` (int): The number of months. | +| GET /future_sip | Calculate Future Value of SIP | - `interval_investment` (float): The interval investment | +| | | - `rate_of_return` (float): The rate of return. | +| | | - `number_of_payments` (int): The number of payments. | +| --------------------------- | ---------------------------------------- | --------------------------------------------------------- | +| POST /capm | Calculate Capital Asset Pricing Model (CAPM) | - `risk_free_return` (float): Risk-free rate of return. | +| | | - `sensitivity` (float): Asset's sensitivity. | +| | | - `expected_market_return` (float): Expected return of the market. | \ No newline at end of file diff --git a/ENDPOINTS.md b/ENDPOINTS.md index 0b1bb25f..78777e04 100644 --- a/ENDPOINTS.md +++ b/ENDPOINTS.md @@ -2048,3 +2048,20 @@ Sample Output "Capitalization Rate": 6.16% } ``` +**POST** `/capm` + +- Request body : `{ + "risk_free_return": 86, + "sensitivity": 6, + "expected_market_return": 87 +}` +- Sample output + +```py +{ + "Tag": "Capital Asset Pricing Model (CAPM)", + "Risk-free rate of return": 86, + "Asset's sensitivity": 6, + "Expected return of the market": 87, + "Expected return on the asset": "92.0%" +} \ No newline at end of file diff --git a/helpers/functions.py b/helpers/functions.py index ff1e572d..47a42146 100644 --- a/helpers/functions.py +++ b/helpers/functions.py @@ -1965,3 +1965,8 @@ def net_worth_calculation(assets: float, liabilities: float, loans: float, mortg "Liabilities": total_liabilities, "Net Worth": net_worth, } + + +def capm_calculation(risk_free_return:float, sensitivity:float, expected_market_return:float): + expected_asset_return = risk_free_return + sensitivity * (expected_market_return - risk_free_return) + return expected_asset_return \ No newline at end of file diff --git a/main.py b/main.py index 27be1ce0..a9c072a0 100644 --- a/main.py +++ b/main.py @@ -128,7 +128,8 @@ from tasks.net_worth import net_worth_calculation_task from tasks.personal_savings import personal_savings_task from tasks.portfolio_return_monte_carlo import portfolio_return_monte_carlo_task -from validators.request_validators import SimpleInterestRateRequest, calculatePension, compoundInterest, futureSip, paybackPeriod +from tasks.calculate_capm import calculate_capm +from validators.request_validators import SimpleInterestRateRequest, calculatePension, compoundInterest, futureSip, paybackPeriod, capmRequest # Creating the app app = FastAPI( @@ -1844,4 +1845,13 @@ def capitalization_rate( def accounts_payable_turnover_ratio(total_supply_purchases: float, beginning_accounts_payable: float, ending_accounts_payable: float): - return accounts_payable_turnover_ratio_task(total_supply_purchases, beginning_accounts_payable, ending_accounts_payable) \ No newline at end of file + return accounts_payable_turnover_ratio_task(total_supply_purchases, beginning_accounts_payable, ending_accounts_payable) + + +@app.post( + "/capm", + tags=["Capital Asset Pricing Model (CAPM)"], + description="Estimate the expected return on an investment.", +) +def capm(request: capmRequest): + return calculate_capm(request.risk_free_return, request.sensitivity, request.expected_market_return) \ No newline at end of file diff --git a/tasks/calculate_capm.py b/tasks/calculate_capm.py new file mode 100644 index 00000000..a6988af6 --- /dev/null +++ b/tasks/calculate_capm.py @@ -0,0 +1,16 @@ +from helpers import functions +from fastapi import HTTPException, status + + +def calculate_capm(risk_free_return:float, sensitivity:float, expected_market_return:float): + try: + expected_asset_return = functions.capm_calculation(risk_free_return, sensitivity, expected_market_return) + return { + "Tag": "Capital Asset Pricing Model (CAPM)", + "Risk-free rate of return":risk_free_return, + "Asset's sensitivity": sensitivity, + "Expected return of the market": expected_market_return, + "expected return on the asset": f"{expected_asset_return}%", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/validators/request_validators.py b/validators/request_validators.py index 8e845f5f..a9274284 100644 --- a/validators/request_validators.py +++ b/validators/request_validators.py @@ -855,4 +855,9 @@ class calculateMarketCap(BaseModel): class calculateBvps(BaseModel): total_equity: float - number_of_shares: float \ No newline at end of file + number_of_shares: float + +class capmRequest(BaseModel): + risk_free_return:float + sensitivity:float + expected_market_return:float \ No newline at end of file From 5178d0ce0f62e1e74e070f935c883599f2e96e30 Mon Sep 17 00:00:00 2001 From: Shivansh Date: Sun, 2 Jul 2023 21:53:39 +0530 Subject: [PATCH 33/66] Removing duplicate classes from request_validators.py --- validators/request_validators.py | 280 ------------------------------- 1 file changed, 280 deletions(-) diff --git a/validators/request_validators.py b/validators/request_validators.py index a9274284..9309cd15 100644 --- a/validators/request_validators.py +++ b/validators/request_validators.py @@ -326,10 +326,6 @@ class zeroCoupounBondValue(BaseModel): interest_rate: float years_to_maturity: int -class zeroCoupounBondYield(BaseModel): - face_value: float - current_bond_price: float - years_to_maturity: int class profitabilityIndex(BaseModel): initial_investment: float @@ -386,34 +382,6 @@ class calculatePeriodFV(BaseModel): future_value: float rate: float -class balloonLoanPayment(BaseModel): - loan_amount: float - interest_rate: float - number_of_payments: int - -class monthlyLeasePayment(BaseModel): - present_value: float - interest_rate: float - number_of_payments: int - -class estimate401k(BaseModel): - current_age: float - retirement_age: float - current_401k_balance: float - annual_contribution: float - annual_salary: float - annual_raise: float - employer_match: float - employer_max_match: float - -class rothIra(BaseModel): - current_age: float - retirement_age: float - annual_contribution: float - annual_salary: float - annual_raise: float - current_roth_balance: float - expected_annual_return: float class mortgageAmortization(BaseModel): loan_amount: float @@ -429,11 +397,6 @@ class salaryCalculate(BaseModel): salary: float pay_frequency: str -class personalLoan(BaseModel): - loan_amount: float - interest_rate: float - number_of_payments: int - class lumpsum(BaseModel): initial_investment: float interest_rate: float @@ -566,98 +529,6 @@ class portfolioReturnMonteCarlo(BaseModel): years: int iterations: int -class calculatePeriodFV(BaseModel): - present_value: float - future_value: float - rate: float - -class balloonLoanPayment(BaseModel): - loan_amount: float - interest_rate: float - number_of_payments: int - -class monthlyLeasePayment(BaseModel): - present_value: float - interest_rate: float - number_of_payments: int - -class estimate401k(BaseModel): - current_age: float - retirement_age: float - current_401k_balance: float - annual_contribution: float - annual_salary: float - annual_raise: float - employer_match: float - employer_max_match: float - -class rothIra(BaseModel): - current_age: float - retirement_age: float - annual_contribution: float - annual_salary: float - annual_raise: float - current_roth_balance: float - expected_annual_return: float - -class mortgageAmortization(BaseModel): - loan_amount: float - interest_rate: float - number_of_payments: int - -class enterpriseValue(BaseModel): - market_capitalization: float - total_debt: float - cash_and_cash_equivalents: float - -class salaryCalculate(BaseModel): - salary: float - pay_frequency: str - -class personalLoan(BaseModel): - loan_amount: float - interest_rate: float - number_of_payments: int - -class lumpsum(BaseModel): - initial_investment: float - interest_rate: float - number_of_payments: int - -class refinance(BaseModel): - current_loan_balance: float - current_interest_rate: float - current_loan_term: int - new_interest_rate: float - new_loan_term: int - -class commissionCalc(BaseModel): - sales_price: float - commission_rate: float - commission: float - -class collegeCost(BaseModel): - tuition_fee: float - annual_increase: float - years: int - -class dilutedEps(BaseModel): - net_income: float - weighted_average_shares: float - dilutive_securities: float - -class asdcr(BaseModel): - net_operating_income: float - total_debt_service: float - -class calculateGst(BaseModel): - price: float - gst_rate: float - -class calculateMarketCap(BaseModel): - price_per_share: float - number_of_shares: float - class calculateRetirementGoals(BaseModel): current_age: float retirement_age: float @@ -668,104 +539,6 @@ class calculateRetirementGoals(BaseModel): retirement_income: float retirement_inflation: float -class calculateExpectedReturnOfPortfolio(BaseModel): - expected_return_of_asset_1: float - expected_return_of_asset_2: float - weight_of_asset_1: float - weight_of_asset_2: float - -class calculateFinancialLeverage(BaseModel): - total_assets: float - total_equity: float - -class calculateGratuity(BaseModel): - basic_salary: float - dearness_allowance: float - number_of_years: float - gratuity_rate: float - -class calculateMacaulayDuration(BaseModel): - cash_flow: float - discount_rate: float - time_period: int - -class calculateNetProfitMargin(BaseModel): - net_income: float - net_sales: float - -class calculatePostTaxReturnPercentage(BaseModel): - pre_tax_return: float - tax_rate: float - -class calculateSalary(BaseModel): - salary: float - pay_frequency: str - -class capitalGainsYield(BaseModel): - initial_price: float - ending_price: float - dividends: float - -class capitalizationRate(BaseModel): - net_operating_income: float - property_value: float - -class freeCashFlowToEquity(BaseModel): - net_income: float - capital_expenditure: float - change_in_working_capital: float - debt_issued: float - debt_repaid: float - -class loanAffordability(BaseModel): - monthly_income: float - monthly_debt: float - interest_rate: float - loan_term: int - -class bondEquivalentYield(BaseModel): - face_value: float - price: float - days_to_maturity: int - -class calculateVat(BaseModel): - price: float - vat_rate: float - -class loanToValueRatio(BaseModel): - loan_amount: float - value_of_property: float - -class mortrage(BaseModel): - loan_amount: float - interest_rate: float - number_of_payments: int - -class netWorth(BaseModel): - assets: float - liabilities: float - -class personalSavings(BaseModel): - annual_salary: float - monthly_expenses: float - savings_rate: float - annual_raise: float - current_savings: float - years: int - -class portfolioReturnMonteCarlo(BaseModel): - initial_investment: float - annual_contribution: float - annual_return: float - standard_deviation: float - years: int - iterations: int - -class calculatePeriodFV(BaseModel): - present_value: float - future_value: float - rate: float - class balloonLoanPayment(BaseModel): loan_amount: float interest_rate: float @@ -795,64 +568,11 @@ class rothIra(BaseModel): current_roth_balance: float expected_annual_return: float -class mortgageAmortization(BaseModel): - loan_amount: float - interest_rate: float - number_of_payments: int - -class enterpriseValue(BaseModel): - market_capitalization: float - total_debt: float - cash_and_cash_equivalents: float - -class salaryCalculate(BaseModel): - salary: float - pay_frequency: str - class personalLoan(BaseModel): loan_amount: float interest_rate: float number_of_payments: int -class lumpsum(BaseModel): - initial_investment: float - interest_rate: float - number_of_payments: int - -class refinance(BaseModel): - current_loan_balance: float - current_interest_rate: float - current_loan_term: int - new_interest_rate: float - new_loan_term: int - -class commissionCalc(BaseModel): - sales_price: float - commission_rate: float - commission: float - -class collegeCost(BaseModel): - tuition_fee: float - annual_increase: float - years: int - -class dilutedEps(BaseModel): - net_income: float - weighted_average_shares: float - dilutive_securities: float - -class asdcr(BaseModel): - net_operating_income: float - total_debt_service: float - -class calculateGst(BaseModel): - price: float - gst_rate: float - -class calculateMarketCap(BaseModel): - price_per_share: float - number_of_shares: float - class calculateBvps(BaseModel): total_equity: float number_of_shares: float From 8d39e2f00e9e6f658d94250e8c87762ddae0c76d Mon Sep 17 00:00:00 2001 From: Robera Negussie <47657043+roberanegussie@users.noreply.github.com> Date: Mon, 3 Jul 2023 19:49:40 +0300 Subject: [PATCH 34/66] Debt Service Coverage Ratio --- DOCUMENTATION.md | 9 ++++++++- ENDPOINTS.md | 25 +++++++++++++++++++++++++ helpers/functions.py | 12 +++++++++++- main.py | 19 +++++++++++++++++-- tasks/debt_service_coverage_ratio.py | 26 ++++++++++++++++++++++++++ validators/request_validators.py | 9 ++++++++- 6 files changed, 95 insertions(+), 5 deletions(-) create mode 100644 tasks/debt_service_coverage_ratio.py diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index c327dc80..4de4d8e6 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -9,4 +9,11 @@ | --------------------------- | ---------------------------------------- | --------------------------------------------------------- | | POST /capm | Calculate Capital Asset Pricing Model (CAPM) | - `risk_free_return` (float): Risk-free rate of return. | | | | - `sensitivity` (float): Asset's sensitivity. | -| | | - `expected_market_return` (float): Expected return of the market. | \ No newline at end of file +| | | - `expected_market_return` (float): Expected return of the market. | +| --------------------------- | ---------------------------------------- | --------------------------------------------------------- | +| POST /debt_service_coverage_ratio | Calculate Debt Service Coverage Ratio | - `revenue` (float): Amount of Company Revenue. | +| | | - `operating_expenses` (float): Cost of operating expenses.| +| | | - `interest` (float): Amount of interest to be paid | +| | | - `tax_rate` (float): The tax rate applied. | +| | | - `principal` (float): Amount of principal borrowed. | +| ------------------------------- | ------------------------------------ | --------------------------------------------------------- | \ No newline at end of file diff --git a/ENDPOINTS.md b/ENDPOINTS.md index 9cdd8a1f..b01163f8 100644 --- a/ENDPOINTS.md +++ b/ENDPOINTS.md @@ -2050,4 +2050,29 @@ Sample Output "Asset's sensitivity": 6, "Expected return of the market": 87, "Expected return on the asset": "92.0%" +} +``` + +**POST** `/debt_service_coverage_ratio` + +- Request body : `{ + "revenue": 143528.79, + "operating_expenses": 62148.63, + "interest": 4765.32, + "tax_rate": 20, + "principal": 60371.61 +}` +- Sample output + +```py +{ + "Tag": "Debt Service Coverage Ratio", + "Revenue": 143528.79, + "Operating Expenses": 62148.63, + "Interest": 4765.32, + "Tax Rate": 0.2, + "Principal": 90371.61, + "Net Operating Income": 81380.16, + "Total Debt Service": 64183.866, + "Debt Service Coverage Ratio": 1.34 } \ No newline at end of file diff --git a/helpers/functions.py b/helpers/functions.py index 9ad07fbd..2a956199 100644 --- a/helpers/functions.py +++ b/helpers/functions.py @@ -1951,4 +1951,14 @@ def net_worth_calculation(assets: float, liabilities: float, loans: float, mortg def capm_calculation(risk_free_return:float, sensitivity:float, expected_market_return:float): expected_asset_return = risk_free_return + sensitivity * (expected_market_return - risk_free_return) - return expected_asset_return \ No newline at end of file + return expected_asset_return + +# Function to Calculate Debt Service Coverage Ratio. + +def debt_service_coverage_ratio(revenue: float, operating_expenses: float, interest: float, +tax_rate: float, principal: float): + tax_rate = tax_rate / 100 + net_operating_income = revenue - operating_expenses + total_debt_service = (interest * (1 - tax_rate)) + principal + ratio = net_operating_income / total_debt_service + return ratio \ No newline at end of file diff --git a/main.py b/main.py index 46b33ea7..97b7dcf1 100644 --- a/main.py +++ b/main.py @@ -127,7 +127,8 @@ from tasks.personal_savings import personal_savings_task from tasks.portfolio_return_monte_carlo import portfolio_return_monte_carlo_task from tasks.calculate_capm import calculate_capm -from validators.request_validators import SimpleInterestRateRequest, calculatePension, compoundInterest, futureSip, paybackPeriod, capmRequest +from tasks.debt_service_coverage_ratio import debt_service_coverage_ratio_task +from validators.request_validators import SimpleInterestRateRequest, calculatePension, compoundInterest, futureSip, paybackPeriod, capmRequest, DebtServiceCoverageRatio # Creating the app app = FastAPI( @@ -1826,4 +1827,18 @@ def accounts_payable_turnover_ratio(total_supply_purchases: float, description="Estimate the expected return on an investment.", ) def capm(request: capmRequest): - return calculate_capm(request.risk_free_return, request.sensitivity, request.expected_market_return) \ No newline at end of file + return calculate_capm(request.risk_free_return, request.sensitivity, request.expected_market_return) + +# Endpoint to calculate Debt Service Coverage Ratio + +@app.post( + "/debt_service_coverage_ratio", + tags=["debt_service_coverage_ratio"], + description="Calculate Debt Service Coverage Ratio", +) +def debt_service_coverage_ratio(request: DebtServiceCoverageRatio): + return debt_service_coverage_ratio_task(request.revenue, + request.operating_expenses, + request.interest, + request.tax_rate, + request.principal) \ No newline at end of file diff --git a/tasks/debt_service_coverage_ratio.py b/tasks/debt_service_coverage_ratio.py new file mode 100644 index 00000000..d82113ec --- /dev/null +++ b/tasks/debt_service_coverage_ratio.py @@ -0,0 +1,26 @@ +from helpers import functions +from fastapi import HTTPException, status + +def debt_service_coverage_ratio_task(revenue: float, operating_expenses: float, interest: float, +tax_rate: float, principal: float): + try: + net_operating_income = revenue - operating_expenses + total_debt_service = (interest * (1 - tax_rate)) + principal + ratio = functions.debt_service_coverage_ratio(revenue, + operating_expenses, + interest, + tax_rate, + principal) + return { + "Tag": "Debt Service Coverage Ratio", + "Revenue": revenue, + "Operating Expenses": operating_expenses, + "Interest": interest, + "Tax Rate": tax_rate, + "Principal": principal, + "Net Operating Income": net_operating_income, + "Total Debt Service": total_debt_service, + "Debt Service Coverage Ratio": ratio + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/validators/request_validators.py b/validators/request_validators.py index a9274284..e21ce0e6 100644 --- a/validators/request_validators.py +++ b/validators/request_validators.py @@ -860,4 +860,11 @@ class calculateBvps(BaseModel): class capmRequest(BaseModel): risk_free_return:float sensitivity:float - expected_market_return:float \ No newline at end of file + expected_market_return:float + +class DebtServiceCoverageRatio(BaseModel): + revenue: float + operating_expenses: float + interest: float + tax_rate: float + principal: float \ No newline at end of file From c05e185235d3812c48940db42b8916ef54462627 Mon Sep 17 00:00:00 2001 From: Robera Negussie <47657043+roberanegussie@users.noreply.github.com> Date: Mon, 3 Jul 2023 19:59:43 +0300 Subject: [PATCH 35/66] Debt Service Coverage Ratio --- ENDPOINTS.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ENDPOINTS.md b/ENDPOINTS.md index b01163f8..2da0f55d 100644 --- a/ENDPOINTS.md +++ b/ENDPOINTS.md @@ -2075,4 +2075,5 @@ Sample Output "Net Operating Income": 81380.16, "Total Debt Service": 64183.866, "Debt Service Coverage Ratio": 1.34 -} \ No newline at end of file +} +``` \ No newline at end of file From 320b783ca0d29d2d51b17ec4254e7cf4a70dbf0d Mon Sep 17 00:00:00 2001 From: Robera Negussie <47657043+roberanegussie@users.noreply.github.com> Date: Tue, 4 Jul 2023 18:45:56 +0300 Subject: [PATCH 36/66] Defensive Interval Ratio --- DOCUMENTATION.md | 7 ++++++- ENDPOINTS.md | 25 ++++++++++++++++++++++++- helpers/functions.py | 11 ++++++++++- main.py | 16 ++++++++++++++-- tasks/defensive_interval_ratio.py | 22 ++++++++++++++++++++++ validators/request_validators.py | 9 ++++++++- 6 files changed, 84 insertions(+), 6 deletions(-) create mode 100644 tasks/defensive_interval_ratio.py diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 4de4d8e6..cf3c8011 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -16,4 +16,9 @@ | | | - `interest` (float): Amount of interest to be paid | | | | - `tax_rate` (float): The tax rate applied. | | | | - `principal` (float): Amount of principal borrowed. | -| ------------------------------- | ------------------------------------ | --------------------------------------------------------- | \ No newline at end of file +| ------------------------------- | ------------------------------------ | --------------------------------------------------------- | +| POST /defensive_interval_ratio | Calculate Defensive Interval Ratio | - `cash` (float): The amount of cash on hand. | +| | | - `marketable_securities` (float): The amount of marketable_securities.| +| | | - `net_receivables` (float): The amount of net_receivables. | +| | | - `annual_operating_expenses` (float): The amount of annual_operating_expenses.| +| | | - `non_cash_charges` (float): The amount of non cash charges.| \ No newline at end of file diff --git a/ENDPOINTS.md b/ENDPOINTS.md index 2da0f55d..05a22365 100644 --- a/ENDPOINTS.md +++ b/ENDPOINTS.md @@ -2076,4 +2076,27 @@ Sample Output "Total Debt Service": 64183.866, "Debt Service Coverage Ratio": 1.34 } -``` \ No newline at end of file +``` +**POST** `/defensive_interval_ratio` + +- Request body : `{ + "cash": 40000.00, + "marketable_securities": 20000.00, + "net_receivables": 10000.00, + "annual_operating_expenses": 300000.00, + "non_cash_charges": 25000.00 +}` +- Sample output + +```py +{ + "Tag": "Defensive Interval Ratio", + "Cash": 40000.00, + "Marketable Securites": 20000.00, + "Net Receivables": 10000.00, + "Annual Operating Expenses": 300000.00, + "Non Cash Charges": 25000.00, + "Current Assets": 70000.0, + "Daily Operational Expenses": 753.42, + "Defensive Interval Ratio": 92.90 +} diff --git a/helpers/functions.py b/helpers/functions.py index 2a956199..e3812b68 100644 --- a/helpers/functions.py +++ b/helpers/functions.py @@ -1961,4 +1961,13 @@ def debt_service_coverage_ratio(revenue: float, operating_expenses: float, inter net_operating_income = revenue - operating_expenses total_debt_service = (interest * (1 - tax_rate)) + principal ratio = net_operating_income / total_debt_service - return ratio \ No newline at end of file + return ratio + +## Function to Calculate Defensive Interval Ratio + +def defensive_interval_ratio(cash: float, marketable_securities: float, +net_receivables: float, annual_operating_expenses: float, non_cash_charges: float): + current_assets = cash + marketable_securities + net_receivables + daily_operational_expenses = (annual_operating_expenses - non_cash_charges) / 365 + ratio = current_assets / daily_operational_expenses + return ratio diff --git a/main.py b/main.py index 97b7dcf1..3e558faa 100644 --- a/main.py +++ b/main.py @@ -128,7 +128,8 @@ from tasks.portfolio_return_monte_carlo import portfolio_return_monte_carlo_task from tasks.calculate_capm import calculate_capm from tasks.debt_service_coverage_ratio import debt_service_coverage_ratio_task -from validators.request_validators import SimpleInterestRateRequest, calculatePension, compoundInterest, futureSip, paybackPeriod, capmRequest, DebtServiceCoverageRatio +from tasks.defensive_interval_ratio import defensive_interval_ratio_task +from validators.request_validators import SimpleInterestRateRequest, calculatePension, compoundInterest, futureSip, paybackPeriod, capmRequest, DebtServiceCoverageRatio, DefensiveIntervalRatio # Creating the app app = FastAPI( @@ -1841,4 +1842,15 @@ def debt_service_coverage_ratio(request: DebtServiceCoverageRatio): request.operating_expenses, request.interest, request.tax_rate, - request.principal) \ No newline at end of file + request.principal) + +# Endpoint to calculate Defensive Interval Ratio + +@app.post( + "/defensive_interval_ratio", + tags=["defensive_interval_ratio"], + description="Calculate Defensive Interval Ratio", +) +def defensive_interval_ratio(request: DefensiveIntervalRatio): + return defensive_interval_ratio_task(request.cash, request.marketable_securities, + request.net_receivables, request.annual_operating_expenses , request.non_cash_charges) diff --git a/tasks/defensive_interval_ratio.py b/tasks/defensive_interval_ratio.py new file mode 100644 index 00000000..28389a5c --- /dev/null +++ b/tasks/defensive_interval_ratio.py @@ -0,0 +1,22 @@ +from helpers import functions +from fastapi import HTTPException, status + +def defensive_interval_ratio_task(cash: float, marketable_securities: float, net_receivables: float, +annual_operating_expenses: float, non_cash_charges: float): + try: + current_assets = cash + marketable_securities + net_receivables + daily_operational_expenses = (annual_operating_expenses - non_cash_charges) / 365 + ratio = functions.defensive_interval_ratio(cash, marketable_securities, net_receivables, annual_operating_expenses, non_cash_charges) + return { + "Tag": "Defensive Interval Ratio", + "Cash": cash, + "Marketable Securites": marketable_securities, + "Net Receivables": net_receivables, + "Annual Operating Expenses": annual_operating_expenses, + "Non Cash Charges": non_cash_charges, + "Current Assets": current_assets, + "Daily Operational Expenses": daily_operational_expenses, + "Defensive Interval Ratio": ratio + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) diff --git a/validators/request_validators.py b/validators/request_validators.py index e21ce0e6..796761a5 100644 --- a/validators/request_validators.py +++ b/validators/request_validators.py @@ -867,4 +867,11 @@ class DebtServiceCoverageRatio(BaseModel): operating_expenses: float interest: float tax_rate: float - principal: float \ No newline at end of file + principal: float + +class DefensiveIntervalRatio(BaseModel): + cash: float + marketable_securities: float + net_receivables: float + annual_operating_expenses: float + non_cash_charges: float From 1a55f472f760c518bce2b73d9677421564e9abc9 Mon Sep 17 00:00:00 2001 From: ighoshsubho Date: Wed, 5 Jul 2023 00:01:37 +0530 Subject: [PATCH 37/66] Added auth to heavy routes Co-authored-by: Nikhil Raj NikhilRaj@gmail.com --- main.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/main.py b/main.py index 97b7dcf1..21680821 100644 --- a/main.py +++ b/main.py @@ -877,7 +877,8 @@ def credit_card_equation( description="Credit Card Payoff using Debt Avalanche method", ) def credit_card_payoff( - debts: list, interest_rates: list, minimum_payments: list, monthly_payment: int + debts: list, interest_rates: list, minimum_payments: list, monthly_payment: int, + payload: dict = Depends(validate_access_token) ): return credit_card_payoff_task( debts, interest_rates, minimum_payments, monthly_payment From 1f9d994b783e5432d09e92b94be45e00eb5af6ba Mon Sep 17 00:00:00 2001 From: ighoshsubho Date: Wed, 5 Jul 2023 00:15:59 +0530 Subject: [PATCH 38/66] Added future value of annuity request validation Co-authored-by: Nikhil Raj nikhil25803@gmail.com --- main.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/main.py b/main.py index 21680821..7f8b518a 100644 --- a/main.py +++ b/main.py @@ -128,7 +128,7 @@ from tasks.portfolio_return_monte_carlo import portfolio_return_monte_carlo_task from tasks.calculate_capm import calculate_capm from tasks.debt_service_coverage_ratio import debt_service_coverage_ratio_task -from validators.request_validators import SimpleInterestRateRequest, calculatePension, compoundInterest, futureSip, paybackPeriod, capmRequest, DebtServiceCoverageRatio +from validators.request_validators import SimpleInterestRateRequest, calculatePension, compoundInterest, futureSip, paybackPeriod, capmRequest, DebtServiceCoverageRatio, futureValueOfAnnuity # Creating the app app = FastAPI( @@ -904,9 +904,9 @@ def future_value_of_ordinary_due( description="Calculating future value of annuity due", ) def future_value_of_annuity_due( - periodic_payment: float, number_of_periods: int, effective_interest_rate: float + request: futureValueOfAnnuity, ): - return future_value_of_annuity_due_task( periodic_payment, number_of_periods, effective_interest_rate) + return future_value_of_annuity_due_task(request.periodic_payment, request.number_of_periods, request.rate_per_period) # Endpoint to calculate present value of the annuity due From 21b274cb436db17798729ef6aefd4c2299d23611 Mon Sep 17 00:00:00 2001 From: Subho Ghosh Date: Wed, 5 Jul 2023 07:20:41 +0530 Subject: [PATCH 39/66] Added jwt for deployment purposes --- requirements.txt | Bin 902 -> 926 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/requirements.txt b/requirements.txt index 0b2115e33d2ff0f87bf2509c6e5a43b8806175ab..d3497202d4ca7b78d52e49ae3e55f07b7f76da31 100644 GIT binary patch delta 36 kcmZo;pU1wTiCHF#p`4+F!4?P&8T1&8f!Kh7mw^k60gbo?aR2}S delta 12 TcmbQo-p0P6iJ66$fr|kE7Pta~ From 0ec862c7f0aa7bcb30ea2cce10270d01cab224f3 Mon Sep 17 00:00:00 2001 From: Subho Ghosh Date: Wed, 5 Jul 2023 07:34:18 +0530 Subject: [PATCH 40/66] Updated Dockerfile Docker file updated for deployment. Co-Authored-By: Nikhil Raj <93156825+nikhil25803@users.noreply.github.com> --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 8530749e..9a5c7421 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,6 +1,6 @@ FROM python:3.9 -WORKDIR /usr/src/application +WORKDIR ./app COPY requirements.txt ./ From c2e65b294d802bc9db47f78df62c1c2600ac1bef Mon Sep 17 00:00:00 2001 From: Robera Negussie <47657043+roberanegussie@users.noreply.github.com> Date: Wed, 5 Jul 2023 18:56:33 +0300 Subject: [PATCH 41/66] Defensive Interval Ratio patch-1 --- DOCUMENTATION.md | 2 +- ENDPOINTS.md | 1 + main.py | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index cf3c8011..9b353a46 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -21,4 +21,4 @@ | | | - `marketable_securities` (float): The amount of marketable_securities.| | | | - `net_receivables` (float): The amount of net_receivables. | | | | - `annual_operating_expenses` (float): The amount of annual_operating_expenses.| -| | | - `non_cash_charges` (float): The amount of non cash charges.| \ No newline at end of file +| | | - `non_cash_charges` (float): The amount of non cash charges.| diff --git a/ENDPOINTS.md b/ENDPOINTS.md index 05a22365..b2bc91f2 100644 --- a/ENDPOINTS.md +++ b/ENDPOINTS.md @@ -2100,3 +2100,4 @@ Sample Output "Daily Operational Expenses": 753.42, "Defensive Interval Ratio": 92.90 } +``` diff --git a/main.py b/main.py index 3e558faa..a37232e6 100644 --- a/main.py +++ b/main.py @@ -129,7 +129,7 @@ from tasks.calculate_capm import calculate_capm from tasks.debt_service_coverage_ratio import debt_service_coverage_ratio_task from tasks.defensive_interval_ratio import defensive_interval_ratio_task -from validators.request_validators import SimpleInterestRateRequest, calculatePension, compoundInterest, futureSip, paybackPeriod, capmRequest, DebtServiceCoverageRatio, DefensiveIntervalRatio +from validators.request_validators import SimpleInterestRateRequest, calculatePension, compoundInterest, futureSip, paybackPeriod, capmRequest, DebtServiceCoverageRatio, futureValueOfAnnuity, DefensiveIntervalRatio # Creating the app app = FastAPI( From 310b156c2bc66929b91129e4612ede78b6a7c9fa Mon Sep 17 00:00:00 2001 From: Robera Negussie <47657043+roberanegussie@users.noreply.github.com> Date: Wed, 5 Jul 2023 19:23:49 +0300 Subject: [PATCH 42/66] Defensive Interval Ratio --- DOCUMENTATION.md | 2 +- ENDPOINTS.md | 3 ++- helpers/functions.py | 1 + main.py | 1 + tasks/defensive_interval_ratio.py | 1 + validators/request_validators.py | 1 + 6 files changed, 7 insertions(+), 2 deletions(-) diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 9b353a46..81abb6cd 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -19,6 +19,6 @@ | ------------------------------- | ------------------------------------ | --------------------------------------------------------- | | POST /defensive_interval_ratio | Calculate Defensive Interval Ratio | - `cash` (float): The amount of cash on hand. | | | | - `marketable_securities` (float): The amount of marketable_securities.| -| | | - `net_receivables` (float): The amount of net_receivables. | +| | | - `net_receivables` (float): The amount of net_receivables.| | | | - `annual_operating_expenses` (float): The amount of annual_operating_expenses.| | | | - `non_cash_charges` (float): The amount of non cash charges.| diff --git a/ENDPOINTS.md b/ENDPOINTS.md index b2bc91f2..dca3fb7e 100644 --- a/ENDPOINTS.md +++ b/ENDPOINTS.md @@ -2100,4 +2100,5 @@ Sample Output "Daily Operational Expenses": 753.42, "Defensive Interval Ratio": 92.90 } -``` +``` + diff --git a/helpers/functions.py b/helpers/functions.py index e3812b68..d5ce9c55 100644 --- a/helpers/functions.py +++ b/helpers/functions.py @@ -1971,3 +1971,4 @@ def defensive_interval_ratio(cash: float, marketable_securities: float, daily_operational_expenses = (annual_operating_expenses - non_cash_charges) / 365 ratio = current_assets / daily_operational_expenses return ratio + diff --git a/main.py b/main.py index 0189729c..aef1c1ec 100644 --- a/main.py +++ b/main.py @@ -1855,3 +1855,4 @@ def debt_service_coverage_ratio(request: DebtServiceCoverageRatio): def defensive_interval_ratio(request: DefensiveIntervalRatio): return defensive_interval_ratio_task(request.cash, request.marketable_securities, request.net_receivables, request.annual_operating_expenses , request.non_cash_charges) + diff --git a/tasks/defensive_interval_ratio.py b/tasks/defensive_interval_ratio.py index 28389a5c..cd122f72 100644 --- a/tasks/defensive_interval_ratio.py +++ b/tasks/defensive_interval_ratio.py @@ -20,3 +20,4 @@ def defensive_interval_ratio_task(cash: float, marketable_securities: float, net } except: return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + diff --git a/validators/request_validators.py b/validators/request_validators.py index 796761a5..31bcceee 100644 --- a/validators/request_validators.py +++ b/validators/request_validators.py @@ -875,3 +875,4 @@ class DefensiveIntervalRatio(BaseModel): net_receivables: float annual_operating_expenses: float non_cash_charges: float + From 014ec0a27050ecab468ae73fd08ca6abb2341c88 Mon Sep 17 00:00:00 2001 From: KANCHARLA SRINADH <121589808+iditocommerce@users.noreply.github.com> Date: Fri, 7 Jul 2023 13:34:27 +0530 Subject: [PATCH 43/66] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 56f0e249..34bc0fae 100644 --- a/Readme.md +++ b/Readme.md @@ -1,4 +1,4 @@ - +# THIS IS FOR TEST PURPOSE

FinTech API v2

From 43397dec8bf5b44f5d4bcfe650645998b7910470 Mon Sep 17 00:00:00 2001 From: 9492277468+-Aa Date: Fri, 7 Jul 2023 21:27:36 +0530 Subject: [PATCH 44/66] compound interest calculator modified in main --- main.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/main.py b/main.py index 7f8b518a..e45b71db 100644 --- a/main.py +++ b/main.py @@ -341,9 +341,9 @@ def payback_period( description="Calculate compound interest amount", ) def compound_interest( - request: compoundInterest, + request: compoundInterest ): - return compound_interest_task(request.principal_amount, request.interest_rate, request.time) + return compound_interest_task(request.principal_amount, request.interest_rate, request.years ,request.compounding_period) # Endpoints to calculate certificate of deposit (CD) From 58b0f895eb8056a8f654ba49f823f2af2942c5c9 Mon Sep 17 00:00:00 2001 From: OMKAR-KALEPU Date: Sat, 8 Jul 2023 00:44:19 +0530 Subject: [PATCH 45/66] Added endpoints and functions to calculate profit and loss percentage --- DOCUMENTATION.md | 8 +++++++- ENDPOINTS.md | 34 ++++++++++++++++++++++++++++++++ helpers/functions.py | 12 ++++++++++- main.py | 27 ++++++++++++++++++++++--- tasks/loss_percentage.py | 14 +++++++++++++ tasks/profit_percentage.py | 14 +++++++++++++ validators/request_validators.py | 10 +++++++++- 7 files changed, 113 insertions(+), 6 deletions(-) create mode 100644 tasks/loss_percentage.py create mode 100644 tasks/profit_percentage.py diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 4de4d8e6..888f1829 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -16,4 +16,10 @@ | | | - `interest` (float): Amount of interest to be paid | | | | - `tax_rate` (float): The tax rate applied. | | | | - `principal` (float): Amount of principal borrowed. | -| ------------------------------- | ------------------------------------ | --------------------------------------------------------- | \ No newline at end of file +| ------------------------------- | ------------------------------------ | --------------------------------------------------------- | +| POST /profit_percent | Calculate profit percentage | - `profit` (float): Total profit earned. | +| | | - `cost_price` (float): The original price of the item | +| ------------------------------- | ------------------------------------ | ------------------------------------------------------ | +| POST /loss_percent | Calculate loss percentage | - `loss` (float): Total loss occured. | +| | | - `cost_price` (float): The original price of the item | +| ------------------------------- | ------------------------------------ | ------------------------------------------------------ | \ No newline at end of file diff --git a/ENDPOINTS.md b/ENDPOINTS.md index 2da0f55d..196111eb 100644 --- a/ENDPOINTS.md +++ b/ENDPOINTS.md @@ -2076,4 +2076,38 @@ Sample Output "Total Debt Service": 64183.866, "Debt Service Coverage Ratio": 1.34 } +``` + +**POST** `/profit_percent` + +- Request body : `{ + "profit": 1560.8, + "cost_price": 7500.4 +}` +- Sample output + +```py +{ + "Tag": "Profit Percentage", + "Profit": 1560.86, + "Cost Price": 7500.47, + "Profit Percentage": 20.81, +} +``` + +**POST** `/loss_percent` + +- Request body : `{ + "loss": 500.96, + "cost_price": 7500.47 +}` +- Sample output + +```py +{ + "Tag": "Loss Percentage", + "Loss": 500.96, + "Cost Price": 7500.47, + "Loss Percentage": 6.67, +} ``` \ No newline at end of file diff --git a/helpers/functions.py b/helpers/functions.py index 2a956199..e5819193 100644 --- a/helpers/functions.py +++ b/helpers/functions.py @@ -1961,4 +1961,14 @@ def debt_service_coverage_ratio(revenue: float, operating_expenses: float, inter net_operating_income = revenue - operating_expenses total_debt_service = (interest * (1 - tax_rate)) + principal ratio = net_operating_income / total_debt_service - return ratio \ No newline at end of file + return ratio + +#Function to calculate profit percentage +def profit_percentage(profit: float, cost_price: float): + profit_percent = (profit / cost_price) * 100 + return profit_percent + +#Function to calculate loss percentage +def loss_percentage(loss: float, cost_price: float): + loss_percent = (loss / cost_price) * 100 + return loss_percent \ No newline at end of file diff --git a/main.py b/main.py index 7f8b518a..c122c314 100644 --- a/main.py +++ b/main.py @@ -128,7 +128,9 @@ from tasks.portfolio_return_monte_carlo import portfolio_return_monte_carlo_task from tasks.calculate_capm import calculate_capm from tasks.debt_service_coverage_ratio import debt_service_coverage_ratio_task -from validators.request_validators import SimpleInterestRateRequest, calculatePension, compoundInterest, futureSip, paybackPeriod, capmRequest, DebtServiceCoverageRatio, futureValueOfAnnuity +from tasks.profit_percentage import profit_percentage_task +from tasks.loss_percentage import loss_percentage_task +from validators.request_validators import SimpleInterestRateRequest, calculatePension, compoundInterest, futureSip, paybackPeriod, capmRequest, DebtServiceCoverageRatio, futureValueOfAnnuity, ProfitPercentage, LossPercentage # Creating the app app = FastAPI( @@ -258,7 +260,8 @@ def index(): "/diluted-earnings-per-share": "Calculate Diluted Earnings Per Share (EPS).", "/asdcr": "Calculate Annual Debt Service Coverage Ratio", "/portfolio_return_monte_carlo":"Calculates Portfolio returns based on Monte Carlo Simulation", - + "/profit_percent": "Calculates the profit percentage", + "/loss_percent": "Calculates the loss percentage", }, } @@ -1842,4 +1845,22 @@ def debt_service_coverage_ratio(request: DebtServiceCoverageRatio): request.operating_expenses, request.interest, request.tax_rate, - request.principal) \ No newline at end of file + request.principal) + +#Endpoint to calculate profit percentage +@app.post( + "/profit_percent", + tags=["profit_percentage"], + description="Calculates the profit percentage", +) +def profit_percent(request: ProfitPercentage): + return profit_percentage_task(request.profit, request.cost_price) + +#Endpoint to calculate loss percentage +@app.post( + "/loss_percent", + tags=["loss_percentage"], + description="Calculates the loss percentage", +) +def loss_percent(request: ProfitPercentage): + return loss_percentage_task(request.loss, request.cost_price) diff --git a/tasks/loss_percentage.py b/tasks/loss_percentage.py new file mode 100644 index 00000000..b23faab4 --- /dev/null +++ b/tasks/loss_percentage.py @@ -0,0 +1,14 @@ +from helpers import functions +from fastapi import HTTPException, status + +def loss_percentage_task(loss: float, cost_price: float): + try: + loss_percent = functions.loss_percentage(loss, cost_price) + return { + "Tag": "Loss Percentage", + "Total loss": loss, + "Cost Price": cost_price, + "Interest Rate": f"{loss_percent}%", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/tasks/profit_percentage.py b/tasks/profit_percentage.py new file mode 100644 index 00000000..a7b38fbe --- /dev/null +++ b/tasks/profit_percentage.py @@ -0,0 +1,14 @@ +from helpers import functions +from fastapi import HTTPException, status + +def profit_percentage_task(profit: float, cost_price: float): + try: + profit_percent = functions.profit_percentage(profit, cost_price) + return { + "Tag": "Profit Percentage", + "Total Profit": profit, + "Cost Price": cost_price, + "Profit Percent": f"{profit_percent}%", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/validators/request_validators.py b/validators/request_validators.py index e21ce0e6..576ffc4f 100644 --- a/validators/request_validators.py +++ b/validators/request_validators.py @@ -867,4 +867,12 @@ class DebtServiceCoverageRatio(BaseModel): operating_expenses: float interest: float tax_rate: float - principal: float \ No newline at end of file + principal: float + +class ProfitPercentage(BaseModel): + profit: float + cost_price: float + +class LossPercentage(BaseModel): + loss: float + cost_price: float \ No newline at end of file From 94239901590d2d0e1c370cfaf05108a286d49ce0 Mon Sep 17 00:00:00 2001 From: OMKAR-KALEPU Date: Sat, 8 Jul 2023 00:46:22 +0530 Subject: [PATCH 46/66] changes --- DOCUMENTATION.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 888f1829..b76e2ea8 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -19,7 +19,5 @@ | ------------------------------- | ------------------------------------ | --------------------------------------------------------- | | POST /profit_percent | Calculate profit percentage | - `profit` (float): Total profit earned. | | | | - `cost_price` (float): The original price of the item | -| ------------------------------- | ------------------------------------ | ------------------------------------------------------ | | POST /loss_percent | Calculate loss percentage | - `loss` (float): Total loss occured. | -| | | - `cost_price` (float): The original price of the item | -| ------------------------------- | ------------------------------------ | ------------------------------------------------------ | \ No newline at end of file +| | | - `cost_price` (float): The original price of the item | \ No newline at end of file From 44213ad2b98f1b3b15f88fb5be7f33a8531883c0 Mon Sep 17 00:00:00 2001 From: "deepsource-io[bot]" <42547082+deepsource-io[bot]@users.noreply.github.com> Date: Sat, 8 Jul 2023 11:04:07 +0000 Subject: [PATCH 47/66] ci: Add .deepsource.toml --- .deepsource.toml | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 .deepsource.toml diff --git a/.deepsource.toml b/.deepsource.toml new file mode 100644 index 00000000..0ac63d33 --- /dev/null +++ b/.deepsource.toml @@ -0,0 +1,7 @@ +version = 1 + +[[analyzers]] +name = "python" + + [analyzers.meta] + runtime_version = "3.x.x" \ No newline at end of file From 89162dc74bdabd6f0ae25351abed27221826a025 Mon Sep 17 00:00:00 2001 From: Shraddha Singh Date: Mon, 10 Jul 2023 22:25:46 +0530 Subject: [PATCH 48/66] Financial assest ration is added --- DOCUMENTATION.md | 9 ++++++++- ENDPOINTS.md | 28 +++++++++++++++++++++++++++- helpers/functions.py | 19 +++++++++++++++++++ main.py | 17 ++++++++++++++++- tasks/financialAssestRatio.py | 27 +++++++++++++++++++++++++++ validators/request_validators.py | 11 ++++++++++- 6 files changed, 107 insertions(+), 4 deletions(-) create mode 100644 tasks/financialAssestRatio.py diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 8004f7ee..e6e17ac9 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -25,4 +25,11 @@ | | | - `marketable_securities` (float): The amount of marketable_securities.| | | | - `net_receivables` (float): The amount of net_receivables.| | | | - `annual_operating_expenses` (float): The amount of annual_operating_expenses.| -| | | - `non_cash_charges` (float): The amount of non cash charges.| \ No newline at end of file +| | | - `non_cash_charges` (float): The amount of non cash charges.| +| GET /financial_assest_ratio | Calculate financial assest ratio | - `current_assets` (float): used up within a short period. | +| | | - `current_liabilities` (float): debts that are due . | +| | | - `total_debt` (float): aggregate amount of money. | +| | | - `total_equity`(float): residual interest in the assets. | +| | | - `net_income` (float): net earnings. | +| | | - `total_revenue` (float): sum of all sales. | +| --------------------------- | ---------------------------------------- | --------------------------------------------------------- | \ No newline at end of file diff --git a/ENDPOINTS.md b/ENDPOINTS.md index d8d581cb..7118d36a 100644 --- a/ENDPOINTS.md +++ b/ENDPOINTS.md @@ -2130,4 +2130,30 @@ Sample Output "Daily Operational Expenses": 753.42, "Defensive Interval Ratio": 92.90 } -``` \ No newline at end of file +``` + +**POST** `/financial_assest_ratio` + +- Request body : `{ + "current_assets": 500000, + "current_liabilities": 300000, + "total_debt": 200000, + "total_equity": 400000, + "net_income": 100000, + "total_revenue": 800000, +}` +- Sample output + +```py +{ + "Tag": "Financial assest ratio", + "current_ratio": 1.5, + "debt_to_equity_ratio": 0.8, + "return_on_assets": 0.1, + "return_on_equity": 0.15, + "asset_turnover_ratio": 1.8, + "gross_profit_margin": 0.35, + "net_profit_margin": 0.2, + "price_to_earnings_ratio": 20.5 +} +``` \ No newline at end of file diff --git a/helpers/functions.py b/helpers/functions.py index 97358a5b..c09005f6 100644 --- a/helpers/functions.py +++ b/helpers/functions.py @@ -1982,3 +1982,22 @@ def defensive_interval_ratio(cash: float, marketable_securities: float, ratio = current_assets / daily_operational_expenses return ratio +## Function to Calculate Financial Assest Ratio + +def calculate_financial_asset_ratios(current_assets, current_liabilities, total_debt, total_equity, net_income, total_revenue, total_assets): + + current_ratio = current_assets / current_liabilities + debt_to_equity_ratio = total_debt / total_equity + return_on_assets = net_income / total_assets + return_on_equity = net_income / total_equity + profit_margin = net_income / total_revenue + + ratios = { + "current_ratio": current_ratio, + "debt_to_equity_ratio": debt_to_equity_ratio, + "return_on_assets": return_on_assets, + "return_on_equity": return_on_equity, + "profit_margin": profit_margin + } + + return ratios diff --git a/main.py b/main.py index c4dd1afc..fa14da9e 100644 --- a/main.py +++ b/main.py @@ -131,7 +131,8 @@ from tasks.profit_percentage import profit_percentage_task from tasks.loss_percentage import loss_percentage_task from tasks.defensive_interval_ratio import defensive_interval_ratio_task -from validators.request_validators import SimpleInterestRateRequest, calculatePension, compoundInterest, futureSip, paybackPeriod, capmRequest, DebtServiceCoverageRatio, futureValueOfAnnuity, ProfitPercentage, LossPercentage, DefensiveIntervalRatio, +from validators.request_validators import SimpleInterestRateRequest, calculatePension, compoundInterest, futureSip, paybackPeriod, capmRequest, DebtServiceCoverageRatio, futureValueOfAnnuity, ProfitPercentage, LossPercentage, DefensiveIntervalRatio, financialAssestRatio +from tasks.financialAssestRatio import financial_assest_ratio # Creating the app app = FastAPI( @@ -1877,3 +1878,17 @@ def defensive_interval_ratio(request: DefensiveIntervalRatio): return defensive_interval_ratio_task(request.cash, request.marketable_securities, request.net_receivables, request.annual_operating_expenses , request.non_cash_charges) +# Endpoint to calculate Financial assest Ratio + +@app.post( + "/financial_assest_ratio", + tags=["financial_assest_ratio"], + description="Calculate financial assest Ratio", +) +def financial_assest_ratio(request: financialAssestRatio): + return financial_assest_ratio(request.current_assets, + request.current_liabilities, + request.total_debt, + request.total_equity, + request.net_income, + request.total_revenue) diff --git a/tasks/financialAssestRatio.py b/tasks/financialAssestRatio.py new file mode 100644 index 00000000..8a067ffd --- /dev/null +++ b/tasks/financialAssestRatio.py @@ -0,0 +1,27 @@ +from helpers import functions +from fastapi import HTTPException, status + +def financial_assest_ratio(current_assets: float, current_liabilities: float, total_debt: float, +total_equity: float, net_income: float, total_assets:float, total_revenue: float, gross_profit: float, stock_price: float, earnings_per_share:float): + try: + current_ratio = current_assets / current_liabilities + debt_to_equity_ratio = total_debt / total_equity + return_on_assets = net_income / total_assets + return_on_equity = net_income / total_equity + asset_turnover_ratio = total_revenue / total_assets + gross_profit_margin = gross_profit / total_revenue + net_profit_margin = net_income / total_revenue + price_to_earnings_ratio = stock_price / earnings_per_share + return { + "Tag": "financial assest ratio", + "current_ratio": current_ratio, + "debt_to_equity_ratio": debt_to_equity_ratio, + "return_on_assets": return_on_assets, + "return_on_equity": return_on_equity, + "asset_turnover_ratio": asset_turnover_ratio, + "gross_profit_margin": gross_profit_margin, + "net_profit_margin": net_profit_margin, + "price_to_earnings_ratio": price_to_earnings_ratio, + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/validators/request_validators.py b/validators/request_validators.py index 076ddd24..a39151e5 100644 --- a/validators/request_validators.py +++ b/validators/request_validators.py @@ -602,4 +602,13 @@ class DefensiveIntervalRatio(BaseModel): marketable_securities: float net_receivables: float annual_operating_expenses: float - non_cash_charges: float \ No newline at end of file + non_cash_charges: float + +class financialAssestRatio(BaseModel): + current_assets: float + current_liabilities: float + total_debt: float + total_equity: float + net_income: float + total_revenue: float + \ No newline at end of file From 797d9f316bb4bce0e7f3837175481e9f0cbad643 Mon Sep 17 00:00:00 2001 From: 9492277468+-Aa Date: Tue, 11 Jul 2023 15:27:45 +0530 Subject: [PATCH 49/66] edited the lumpsum 500 server and corrected --- tasks/lumpsum.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tasks/lumpsum.py b/tasks/lumpsum.py index dae1e6b5..48c34d03 100644 --- a/tasks/lumpsum.py +++ b/tasks/lumpsum.py @@ -1,7 +1,6 @@ from helpers import functions from fastapi import HTTPException, status - -async def calculate_lumpsum_task(principal: float, interest_rate: float, years: int): +def calculate_lumpsum_task(principal: float, interest_rate: float, years: int): try: total_amount = principal * ( From 1dafefb2c3b2e71c16ac88afcb03d6ae2e3937fb Mon Sep 17 00:00:00 2001 From: Subho Ghosh <93722719+ighoshsubho@users.noreply.github.com> Date: Tue, 11 Jul 2023 21:32:52 +0530 Subject: [PATCH 50/66] Delete .deepsource.toml --- .deepsource.toml | 7 ------- 1 file changed, 7 deletions(-) delete mode 100644 .deepsource.toml diff --git a/.deepsource.toml b/.deepsource.toml deleted file mode 100644 index 0ac63d33..00000000 --- a/.deepsource.toml +++ /dev/null @@ -1,7 +0,0 @@ -version = 1 - -[[analyzers]] -name = "python" - - [analyzers.meta] - runtime_version = "3.x.x" \ No newline at end of file From b626035f3314cd7a87fb9f91b4b1b369aee5d47c Mon Sep 17 00:00:00 2001 From: Robera Negussie <47657043+roberanegussie@users.noreply.github.com> Date: Tue, 11 Jul 2023 22:23:47 +0300 Subject: [PATCH 51/66] Cash Conversion Cycle --- DOCUMENTATION.md | 15 ++++++- ENDPOINTS.md | 71 ++++++++++++++++++++++++-------- helpers/functions.py | 14 +++++++ main.py | 16 ++++++- tasks/cash_conversion_cycle.py | 33 +++++++++++++++ validators/request_validators.py | 10 +++++ 6 files changed, 139 insertions(+), 20 deletions(-) create mode 100644 tasks/cash_conversion_cycle.py diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index e6e17ac9..8e181ff0 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -26,10 +26,23 @@ | | | - `net_receivables` (float): The amount of net_receivables.| | | | - `annual_operating_expenses` (float): The amount of annual_operating_expenses.| | | | - `non_cash_charges` (float): The amount of non cash charges.| +| --------------------------- | ---------------------------------------- | --------------------------------------------------------- | | GET /financial_assest_ratio | Calculate financial assest ratio | - `current_assets` (float): used up within a short period. | | | | - `current_liabilities` (float): debts that are due . | | | | - `total_debt` (float): aggregate amount of money. | | | | - `total_equity`(float): residual interest in the assets. | | | | - `net_income` (float): net earnings. | | | | - `total_revenue` (float): sum of all sales. | -| --------------------------- | ---------------------------------------- | --------------------------------------------------------- | \ No newline at end of file + +|----------------------------|----------------------------------------|-------------------------------------------------------------------------------| +| GET /cash_conversion_cycle | Calculate Cash Conversion Cycle | - `beginning_inventory` (float): The amount of inventory beginning the cycle. | +| | | - `ending_inventory` (float): The final amount of inventory ending the cycle. | +| | | - `beginning_receivables` (float): The amount of receivables beginning the cycle. | +| | | - `ending_receivables` (float): The final amount of receivables ending the cycle. | +| | | - `beginning_payable` (float): The amount of payable beginning the cycle. | +| | | - `ending_payable` (float): The final amount of payable ending the cycle. | +| | | - `cost_of_goods_sold` (float): The total cost related to producing goods sold by a business. | +| | | - `net_credit_sales` (float): Sales where the cash is collected at a later date. | +|----------------------------|----------------------------------------|----------------------------------------------------------------------| + + diff --git a/ENDPOINTS.md b/ENDPOINTS.md index 7118d36a..6c05f837 100644 --- a/ENDPOINTS.md +++ b/ENDPOINTS.md @@ -2083,7 +2083,16 @@ Sample Output - Request body : `{ "profit": 1560.8, "cost_price": 7500.4 -======= +}` +```py +{ + "Tag": "Profit Percentage", + "Profit": 1560.86, + "Cost Price": 7500.47, + "Profit Percentage": 20.81, +} +``` + **POST** `/defensive_interval_ratio` - Request body : `{ @@ -2094,15 +2103,19 @@ Sample Output "non_cash_charges": 25000.00 }` - Sample output - ```py { - "Tag": "Profit Percentage", - "Profit": 1560.86, - "Cost Price": 7500.47, - "Profit Percentage": 20.81, + "Tag": "Defensive Interval Ratio", + "Cash": 40000.00, + "Marketable Securites": 20000.00, + "Net Receivables": 10000.00, + "Annual Operating Expenses": 300000.00, + "Non Cash Charges": 25000.00, + "Current Assets": 70000.0, + "Daily Operational Expenses": 753.42, + "Defensive Interval Ratio": 92.90 } -``` +``` **POST** `/loss_percent` @@ -2119,17 +2132,6 @@ Sample Output "Cost Price": 7500.47, "Loss Percentage": 6.67, } -``` - "Tag": "Defensive Interval Ratio", - "Cash": 40000.00, - "Marketable Securites": 20000.00, - "Net Receivables": 10000.00, - "Annual Operating Expenses": 300000.00, - "Non Cash Charges": 25000.00, - "Current Assets": 70000.0, - "Daily Operational Expenses": 753.42, - "Defensive Interval Ratio": 92.90 -} ``` **POST** `/financial_assest_ratio` @@ -2156,4 +2158,37 @@ Sample Output "net_profit_margin": 0.2, "price_to_earnings_ratio": 20.5 } +``` + +**POST** `/cash_conversion_cycle` + +- Request body : `{ + "beginning_inventory": 1000, + "ending_inventory": 2000, + "beginning_receivables": 100 + "ending_receivables": 90, + "beginning_payable": 800, + "ending_payable": 900, + "cost_of_goods_sold": 3000, + "net_credit_sales": 3000 +}` +- Sample output + +```py +{ + "Tag": "Cash Conversion Cycle", + "Beginning Inventory": 1000, + "Ending Inventory": 2000, + "Average Inventory": 1500, + "Beginning Receivables": 100, + "Ending Receivables": 90, + "Average Receivables": 95, + "Beginning Payable": 800, + "Ending Payable": 900, + "Average Payable": 850, + "Days of inventory_outstanding": 182.5, + "Days of Sales Outstanding": 11.56, + "Days of Payables Outstanding": 103.42, + "Cash Conversion Cycle": 90.64 days", +} ``` \ No newline at end of file diff --git a/helpers/functions.py b/helpers/functions.py index c09005f6..1a3271ba 100644 --- a/helpers/functions.py +++ b/helpers/functions.py @@ -2001,3 +2001,17 @@ def calculate_financial_asset_ratios(current_assets, current_liabilities, total_ } return ratios + +# Function to Calculate Cash Conversion Cycle + +def cash_conversion_cycle(beginning_inventory: float, ending_inventory: float, beginning_receivables: float, +ending_receivables: float, beginning_payable: float, ending_payable: float, cost_of_goods_sold: float, +net_credit_sales: float): + average_inventory = beginning_inventory - ending_inventory / 2 + average_receivables = beginning_receivables - ending_receivables / 2 + average_payable = beginning_payable - ending_payable / 2 + days_of_inventory_outstanding = (average_inventory / cost_of_goods_sold) * 365 + days_of_sales_outstanding = (average_receivables / net_credit_sales) * 365 + days_of_payables_outstanding = (average_payable / cost_of_goods_sold / 365) + ccc = days_of_inventory_outstanding + days_of_sales_outstanding - days_of_payables_outstanding + return ccc diff --git a/main.py b/main.py index a2035d35..72ef1981 100644 --- a/main.py +++ b/main.py @@ -131,7 +131,8 @@ from tasks.profit_percentage import profit_percentage_task from tasks.loss_percentage import loss_percentage_task from tasks.defensive_interval_ratio import defensive_interval_ratio_task -from validators.request_validators import SimpleInterestRateRequest, calculatePension, compoundInterest, futureSip, paybackPeriod, capmRequest, DebtServiceCoverageRatio, futureValueOfAnnuity, ProfitPercentage, LossPercentage, DefensiveIntervalRatio, financialAssestRatio +from tasks.cash_conversion_cycle import cash_conversion_cycle_task +from validators.request_validators import SimpleInterestRateRequest, calculatePension, compoundInterest, futureSip, paybackPeriod, capmRequest, DebtServiceCoverageRatio, futureValueOfAnnuity, ProfitPercentage, LossPercentage, DefensiveIntervalRatio, financialAssestRatio, CashConversionCycle from tasks.financialAssestRatio import financial_assest_ratio # Creating the app @@ -1892,3 +1893,16 @@ def financial_assest_ratio(request: financialAssestRatio): request.total_equity, request.net_income, request.total_revenue) + +# Endpoint to calculate Cash Conversion Cycle + +@app.post( + "/cash_conversion_cycle", + tags=["cash_conversion_cycle"], + description="Calculate Cash Conversion Cycle", +) +def cash_conversion_cycle(request: CashConversionCycle): + return cash_conversion_cycle_task(request.beginning_inventory , request.ending_inventory , + request.beginning_receivables, request.ending_receivables , request.beginning_payable, + request.ending_payable , request.net_credit_sales , request.cost_of_goods_sold) + diff --git a/tasks/cash_conversion_cycle.py b/tasks/cash_conversion_cycle.py new file mode 100644 index 00000000..557f4dfb --- /dev/null +++ b/tasks/cash_conversion_cycle.py @@ -0,0 +1,33 @@ +from helpers import functions +from fastapi import HTTPException, status + +def cash_conversion_cycle_task(beginning_inventory: float, ending_inventory: float, beginning_receivables: float, +ending_receivables: float, beginning_payable: float, ending_payable: float, cost_of_goods_sold: float, +net_credit_sales: float): + try: + average_inventory = beginning_inventory - ending_inventory / 2 + average_receivables = beginning_receivables - ending_receivables / 2 + average_payable = beginning_payable - ending_payable / 2 + days_of_inventory_outstanding = (average_inventory / cost_of_goods_sold) * 365 + days_of_sales_outstanding = (average_receivables / net_credit_sales) * 365 + days_of_payables_outstanding = (average_payable / cost_of_goods_sold / 365) + ccc = functions.cash_conversion_cycle(beginning_inventory, ending_inventory, beginning_receivables, + ending_receivables, beginning_payable, ending_payable, cost_of_goods_sold, net_credit_sales) + return { + "Tag": "Cash Conversion Cycle", + "Beginning Inventory": beginning_inventory, + "Ending Inventory": ending_inventory, + "Average Inventory": average_inventory, + "Beginning Receivables": beginning_receivables, + "Ending Receivables": ending_receivables, + "Average Receivables": average_receivables, + "Beginning Payable": beginning_payable, + "Ending Payable": ending_payable, + "Average Payable": average_payable, + "Days of inventory_outstanding": days_of_inventory_outstanding, + "Days of Sales Outstanding": days_of_sales_outstanding, + "Days of Payables Outstanding": days_of_payables_outstanding, + "Cash Conversion Cycle": f"{ccc} days", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) diff --git a/validators/request_validators.py b/validators/request_validators.py index a39151e5..3eb5b473 100644 --- a/validators/request_validators.py +++ b/validators/request_validators.py @@ -611,4 +611,14 @@ class financialAssestRatio(BaseModel): total_equity: float net_income: float total_revenue: float + +class CashConversionCycle(BaseModel): + beginning_inventory: float + ending_inventory: float + beginning_receivables: float + ending_receivables: float + beginning_payable: float + ending_payable: float + cost_of_goods_sold: float + net_credit_sales: float \ No newline at end of file From e9f460d5d135f2f58124930c5d054768274faf8f Mon Sep 17 00:00:00 2001 From: 9492277468+-Aa Date: Wed, 12 Jul 2023 08:41:08 +0530 Subject: [PATCH 52/66] edited the calculate-pension file. for 500 not found server. --- main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main.py b/main.py index e45b71db..a1b33fcf 100644 --- a/main.py +++ b/main.py @@ -319,7 +319,7 @@ def future_sip( def calculate_pension( request: calculatePension ): - return calculate_pension_task(request.current_age, request.retirement_age, request.current_salary, request.percentage_saved, request.employer_match, request.expected_annual_raise, request.savings_goal) + return calculate_pension_task(request.monthly_investment_amount, request.no_of_years, request.annuity_rates, request.annuity_purchased, request.yearly_interest_rates) # endpoint for payback period From 23375c29a36bc002986895b8fe8ae8248333ee12 Mon Sep 17 00:00:00 2001 From: 9492277468+-Aa Date: Wed, 12 Jul 2023 12:31:04 +0530 Subject: [PATCH 53/66] resolved the calculate-vat branch. 500 server error solve --- main.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/main.py b/main.py index a1b33fcf..a88ff321 100644 --- a/main.py +++ b/main.py @@ -1550,7 +1550,9 @@ def asdcr( description="Calculate VAT for both excluding and including amounts", ) async def calculate_vat(price: float, vat_rate: float): - return calculate_vat_task(price, vat_rate) + calculate_vat_price = await calculate_vat_task(price, vat_rate) + return calculate_vat_price + # Endpoint For calculating bond equivalent yield From fe8ac3d6d397afa4f88fdba2179ac34d2c9a9224 Mon Sep 17 00:00:00 2001 From: 9492277468+-Aa Date: Wed, 12 Jul 2023 15:34:31 +0530 Subject: [PATCH 54/66] edited the future-value-annuity-due error. show ing 422 error. and solved. --- main.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/main.py b/main.py index a88ff321..6f91b044 100644 --- a/main.py +++ b/main.py @@ -128,7 +128,7 @@ from tasks.portfolio_return_monte_carlo import portfolio_return_monte_carlo_task from tasks.calculate_capm import calculate_capm from tasks.debt_service_coverage_ratio import debt_service_coverage_ratio_task -from validators.request_validators import SimpleInterestRateRequest, calculatePension, compoundInterest, futureSip, paybackPeriod, capmRequest, DebtServiceCoverageRatio, futureValueOfAnnuity +from validators.request_validators import SimpleInterestRateRequest, calculatePension, compoundInterest, futureSip, paybackPeriod, capmRequest, DebtServiceCoverageRatio, futureValueOfAnnuity, futureValueOfAnnuityDue # Creating the app app = FastAPI( @@ -898,15 +898,15 @@ def future_value_of_ordinary_due( # Endpoint to calculate future value of the annuity due -@app.get( +@app.post( "/future_value_of_annuity_due", tags=["future_value_of_annuity_due"], description="Calculating future value of annuity due", ) def future_value_of_annuity_due( - request: futureValueOfAnnuity, + request: futureValueOfAnnuity ): - return future_value_of_annuity_due_task(request.periodic_payment, request.number_of_periods, request.rate_per_period) + return future_value_of_annuity_due_task(request.periodic_payment, request.interest_rate, request.number_of_payments) # Endpoint to calculate present value of the annuity due From 2359b311c8e77246b9b4597994806542ff27f31d Mon Sep 17 00:00:00 2001 From: 9492277468+-Aa Date: Wed, 12 Jul 2023 16:15:20 +0530 Subject: [PATCH 55/66] treynor_ration getting 422 error and solved --- main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main.py b/main.py index 6f91b044..68ef56d5 100644 --- a/main.py +++ b/main.py @@ -1696,7 +1696,7 @@ def calculate_post_tax_return_percentage(tax_rate_percentage: float, # Endpoint for function Treynor Ratio -@app.get( +@app.post( "/treynor_ratio", tags=["treynor_ratio"], description="Calculate Treynor ratio", From 59dd3db4fd5e121b0205863525d15101c64fc22e Mon Sep 17 00:00:00 2001 From: Shraddha Singh Date: Wed, 12 Jul 2023 19:36:14 +0530 Subject: [PATCH 56/66] Rate of return endpoint is added --- DOCUMENTATION.md | 9 ++++++++- ENDPOINTS.md | 21 ++++++++++++++++++++- helpers/functions.py | 5 +++++ main.py | 16 +++++++++++++++- tasks/RateofReturn.py | 25 +++++++++++++++++++++++++ validators/request_validators.py | 9 ++++++++- 6 files changed, 81 insertions(+), 4 deletions(-) create mode 100644 tasks/RateofReturn.py diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 8004f7ee..eee1d9d0 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -25,4 +25,11 @@ | | | - `marketable_securities` (float): The amount of marketable_securities.| | | | - `net_receivables` (float): The amount of net_receivables.| | | | - `annual_operating_expenses` (float): The amount of annual_operating_expenses.| -| | | - `non_cash_charges` (float): The amount of non cash charges.| \ No newline at end of file +| | | - `non_cash_charges` (float): The amount of non cash charges.| +|-----------------------------|----------------------------------------------|-----------------------------------------------------------| +| post /rate_of_return | Calculate Rate of Return | - `initial_investment` (float): Initial amount invested. | +| | | - `final_value` (float): the value of the investment at the end of the investment. | +| | | - `time_period` (float): The number of months. | +| | | - `cash_flows` (float): A list of cash flows over the investment period. | +| | | - `holding_period` (float): The specific holding period of the investment. | +| --------------------------- | ---------------------------------------- | --------------------------------------------------------- | \ No newline at end of file diff --git a/ENDPOINTS.md b/ENDPOINTS.md index d8d581cb..80451a2f 100644 --- a/ENDPOINTS.md +++ b/ENDPOINTS.md @@ -2130,4 +2130,23 @@ Sample Output "Daily Operational Expenses": 753.42, "Defensive Interval Ratio": 92.90 } -``` \ No newline at end of file +``` +**POST** `/rate_return_calculator` + +- Request body : `{ + "initial_investment": 10000, + "final_value": 12500, + "time_period": 3, + "cash_flows": [500, 800, -200], + "holding_period": 2, +}` +- Sample output + +```py +{ + "Tag": "Rate of return", + "rate_of_return": 25.0, + "annualized_return": 8.333333333333334, + "holding_period_return": 50.0, +} +``` \ No newline at end of file diff --git a/helpers/functions.py b/helpers/functions.py index 97358a5b..397f42ac 100644 --- a/helpers/functions.py +++ b/helpers/functions.py @@ -1982,3 +1982,8 @@ def defensive_interval_ratio(cash: float, marketable_securities: float, ratio = current_assets / daily_operational_expenses return ratio +# Function to Calculate Debt Service Coverage Ratio. + +def rate_of_return(initial_investment: float, final_value: float ): + rate_of_return = ((final_value - initial_investment) / initial_investment) * 100 + return rate_of_return \ No newline at end of file diff --git a/main.py b/main.py index c4dd1afc..b0f13058 100644 --- a/main.py +++ b/main.py @@ -131,7 +131,8 @@ from tasks.profit_percentage import profit_percentage_task from tasks.loss_percentage import loss_percentage_task from tasks.defensive_interval_ratio import defensive_interval_ratio_task -from validators.request_validators import SimpleInterestRateRequest, calculatePension, compoundInterest, futureSip, paybackPeriod, capmRequest, DebtServiceCoverageRatio, futureValueOfAnnuity, ProfitPercentage, LossPercentage, DefensiveIntervalRatio, +from validators.request_validators import SimpleInterestRateRequest, calculatePension, compoundInterest, futureSip, paybackPeriod, capmRequest, DebtServiceCoverageRatio, futureValueOfAnnuity, ProfitPercentage, LossPercentage, DefensiveIntervalRatio, RateofReturn +from tasks.RateofReturn import calculate_rate_of_return # Creating the app app = FastAPI( @@ -1877,3 +1878,16 @@ def defensive_interval_ratio(request: DefensiveIntervalRatio): return defensive_interval_ratio_task(request.cash, request.marketable_securities, request.net_receivables, request.annual_operating_expenses , request.non_cash_charges) +# Endpoint to calculate Rate of return + +@app.post( + "/rate_of_return", + tags=["rate_of_return"], + description="Calculate Rate of return", +) +def rate_of_return(request: RateofReturn): + return calculate_rate_of_return(request.initial_investment, + request.final_value, + request.cash_flows, + request.time_period, + request.holding_period) \ No newline at end of file diff --git a/tasks/RateofReturn.py b/tasks/RateofReturn.py new file mode 100644 index 00000000..c3c04429 --- /dev/null +++ b/tasks/RateofReturn.py @@ -0,0 +1,25 @@ +from helpers import functions +from fastapi import HTTPException, status + +def calculate_rate_of_return(initial_investment: float, final_value: float, cash_flows: float, +time_period: float, holding_period: float): + try: + net_cash_flows = sum(cash_flows) + final_value += net_cash_flows + + if holding_period > 0: + rate_of_return = ((final_value - initial_investment) / (initial_investment + net_cash_flows)) * 100 + holding_period_return = ((final_value - initial_investment) / initial_investment) * 100 + else: + rate_of_return = ((final_value - initial_investment) / initial_investment) * 100 + holding_period_return = rate_of_return + + annualized_return = rate_of_return / time_period + return { + "Tag": "Rate of return", + "rate_of_return": rate_of_return, + "annualized_return": annualized_return, + "holding_period_return": holding_period_return + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/validators/request_validators.py b/validators/request_validators.py index 076ddd24..9399e1da 100644 --- a/validators/request_validators.py +++ b/validators/request_validators.py @@ -602,4 +602,11 @@ class DefensiveIntervalRatio(BaseModel): marketable_securities: float net_receivables: float annual_operating_expenses: float - non_cash_charges: float \ No newline at end of file + non_cash_charges: float + +class RateofReturn(BaseModel): + initial_investment: float + final_value: float + cash_flows: float + time_period: float + holding_period: float \ No newline at end of file From 273c2cc8520ad9046c173dc1bfdef852a752329b Mon Sep 17 00:00:00 2001 From: Subho Ghosh <93722719+ighoshsubho@users.noreply.github.com> Date: Wed, 12 Jul 2023 19:53:31 +0530 Subject: [PATCH 57/66] Update main.py --- main.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/main.py b/main.py index 14911a0b..89b4f59f 100644 --- a/main.py +++ b/main.py @@ -131,9 +131,8 @@ from tasks.profit_percentage import profit_percentage_task from tasks.loss_percentage import loss_percentage_task from tasks.defensive_interval_ratio import defensive_interval_ratio_task -from validators.request_validators import SimpleInterestRateRequest, calculatePension, compoundInterest, futureSip, paybackPeriod, capmRequest, DebtServiceCoverageRatio, futureValueOfAnnuity, ProfitPercentage, LossPercentage, DefensiveIntervalRatio, RateofReturn from tasks.RateofReturn import calculate_rate_of_return -from validators.request_validators import SimpleInterestRateRequest, calculatePension, compoundInterest, futureSip, paybackPeriod, capmRequest, DebtServiceCoverageRatio, futureValueOfAnnuity, futureValueOfAnnuityDue, ProfitPercentage, LossPercentage, DefensiveIntervalRatio, financialAssestRatio +from validators.request_validators import SimpleInterestRateRequest, calculatePension, compoundInterest, futureSip, paybackPeriod, capmRequest, DebtServiceCoverageRatio, futureValueOfAnnuity, futureValueOfAnnuityDue, ProfitPercentage, LossPercentage, DefensiveIntervalRatio, financialAssestRatio, RateofReturn from tasks.financialAssestRatio import financial_assest_ratio # Creating the app From 9da4cbd49902ff4a32fabaa9b3560d02b056fb55 Mon Sep 17 00:00:00 2001 From: Shraddha Singh Date: Thu, 13 Jul 2023 16:11:00 +0530 Subject: [PATCH 58/66] Policy premium endpoint is added --- DOCUMENTATION.md | 7 +++++ ENDPOINTS.md | 18 +++++++++++++ helpers/functions.py | 17 ++++++++++++ main.py | 18 ++++++++++++- tasks/PolicyPremium.py | 45 ++++++++++++++++++++++++++++++++ validators/request_validators.py | 9 +++++++ 6 files changed, 113 insertions(+), 1 deletion(-) create mode 100644 tasks/PolicyPremium.py diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index f0719c3d..71775848 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -50,5 +50,12 @@ | | | - `cost_of_goods_sold` (float): The total cost related to producing goods sold by a business. | | | | - `net_credit_sales` (float): Sales where the cash is collected at a later date. | |----------------------------|----------------------------------------|----------------------------------------------------------------------| +| GET /policy_premium | Calculate Policy Premium | - `policy_type` (str): The type of insurance policy. | +| | | - `age` (int): The age of the policyholder. | +| | | - `coverage_amount` (int): The desired coverage amount for the policy. | +| | | - `deductible` (int): The deductible amount for the policy.| +| | | - `num_claims` (int): The number of claims made by the policyholder. | +| | | - `num_accidents` (int): The number of accidents the policyholder has been involved in. | +|----------------------------|----------------------------------------|----------------------------------------------------------------------| diff --git a/ENDPOINTS.md b/ENDPOINTS.md index 4cdd7567..ce583036 100644 --- a/ENDPOINTS.md +++ b/ENDPOINTS.md @@ -2203,4 +2203,22 @@ Sample Output "Days of Payables Outstanding": 103.42, "Cash Conversion Cycle": 90.64 days", } +``` + +**POST** `/policy-premium` + +- Request body : `{ + "policy_type": "auto", + "age": 35, + "coverage_amount": 250000, + "deductible": 500, + "num_claims": 0, + "num_accidents": 1 +}` +- Sample output + +```py +{ + "premium_amount": 1200.50 +} ``` \ No newline at end of file diff --git a/helpers/functions.py b/helpers/functions.py index a310dd63..e75fa505 100644 --- a/helpers/functions.py +++ b/helpers/functions.py @@ -2021,3 +2021,20 @@ def cash_conversion_cycle(beginning_inventory: float, ending_inventory: float, b days_of_payables_outstanding = (average_payable / cost_of_goods_sold / 365) ccc = days_of_inventory_outstanding + days_of_sales_outstanding - days_of_payables_outstanding return ccc + +# Function to Calculate Policy Premium. + +def calculate_policy_premium_ratios(premiums_collected, claims_paid, commissions_paid, operating_expenses): + loss_ratio = (claims_paid / premiums_collected) * 100 + expense_ratio = ((commissions_paid + operating_expenses) / premiums_collected) * 100 + combined_ratio = loss_ratio + expense_ratio + profit_margin = 100 - combined_ratio + + ratios = { + "loss_ratio": loss_ratio, + "expense_ratio": expense_ratio, + "combined_ratio": combined_ratio, + "profit_margin": profit_margin + } + + return ratios diff --git a/main.py b/main.py index 95181d4d..fc905b90 100644 --- a/main.py +++ b/main.py @@ -133,8 +133,9 @@ from tasks.defensive_interval_ratio import defensive_interval_ratio_task from tasks.RateofReturn import calculate_rate_of_return from tasks.cash_conversion_cycle import cash_conversion_cycle_task -from validators.request_validators import SimpleInterestRateRequest, calculatePension, compoundInterest, futureSip, paybackPeriod, capmRequest, DebtServiceCoverageRatio, futureValueOfAnnuity, futureValueOfAnnuityDue, ProfitPercentage, LossPercentage, DefensiveIntervalRatio, CashConversionCycle, RateofReturn, financialAssestRatio +from validators.request_validators import SimpleInterestRateRequest, calculatePension, compoundInterest, futureSip, paybackPeriod, capmRequest, DebtServiceCoverageRatio, futureValueOfAnnuity, futureValueOfAnnuityDue, ProfitPercentage, LossPercentage, DefensiveIntervalRatio, CashConversionCycle, RateofReturn, financialAssestRatio, PolicyPremium from tasks.financialAssestRatio import financial_assest_ratio +from tasks.PolicyPremium import calculate_policy_premium # Creating the app app = FastAPI( @@ -1922,3 +1923,18 @@ def cash_conversion_cycle(request: CashConversionCycle): return cash_conversion_cycle_task(request.beginning_inventory , request.ending_inventory , request.beginning_receivables, request.ending_receivables , request.beginning_payable, request.ending_payable , request.net_credit_sales , request.cost_of_goods_sold) + +# Endpoint to calculate Policy Premium + +@app.post( + "/policy_premium", + tags=["policy_premium"], + description="Calculate Policy premium", +) +def policy_premium(request: PolicyPremium): + return policy_premium(request.policy_type, + request.age, + request.coverage_amount, + request.deductible, + request.num_claims, + request.num_accidents) \ No newline at end of file diff --git a/tasks/PolicyPremium.py b/tasks/PolicyPremium.py new file mode 100644 index 00000000..f5214559 --- /dev/null +++ b/tasks/PolicyPremium.py @@ -0,0 +1,45 @@ +from helpers import functions +from fastapi import HTTPException, status + +def calculate_policy_premium(policy_type: str, age: int, coverage_amount: int, deductible: int, num_claims: int, num_accidents: int): + try: + policy_factors = { + "auto": { + "age": { + "18-25": 1.5, + "26-40": 1.2, + "41-60": 1.0, + "61+": 1.3 + }, + "claims": { + "0": 1.0, + "1-3": 1.2, + "4+": 1.5 + }, + "accidents": { + "0": 1.0, + "1-2": 1.2, + "3+": 1.5 + } + }, + } + + if policy_type not in policy_factors: + return None + + factors = policy_factors[policy_type] + + base_premium = coverage_amount * 0.01 + age_multiplier = factors["age"].get(age, 1.0) + claims_multiplier = factors["claims"].get(num_claims, 1.0) + accidents_multiplier = factors["accidents"].get(num_accidents, 1.0) + deductible_factor = 1 - (deductible / coverage_amount) + + premium_amount = base_premium * age_multiplier * claims_multiplier * accidents_multiplier * deductible_factor + + return { + "Tag": "Debt Service Coverage Ratio", + "Premium Amount": premium_amount, + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/validators/request_validators.py b/validators/request_validators.py index 29d2b423..62c9997c 100644 --- a/validators/request_validators.py +++ b/validators/request_validators.py @@ -628,3 +628,12 @@ class CashConversionCycle(BaseModel): ending_payable: float cost_of_goods_sold: float net_credit_sales: float + +class PolicyPremium(BaseModel): + policy_type: str + age: int + coverage_amount: int + deductible: int + num_claims: int + num_accidents: int + From f4ee9691316073a68b1e532f1a8ca55952ea2f18 Mon Sep 17 00:00:00 2001 From: Shraddha Singh Date: Thu, 13 Jul 2023 22:31:27 +0530 Subject: [PATCH 59/66] Price Elasticity endpoint is added --- DOCUMENTATION.md | 6 ++++++ ENDPOINTS.md | 16 ++++++++++++++++ helpers/functions.py | 9 +++++++++ main.py | 16 +++++++++++++++- tasks/PriceElasticity.py | 15 +++++++++++++++ validators/request_validators.py | 6 ++++++ 6 files changed, 67 insertions(+), 1 deletion(-) create mode 100644 tasks/PriceElasticity.py diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index f0719c3d..45244cd1 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -50,5 +50,11 @@ | | | - `cost_of_goods_sold` (float): The total cost related to producing goods sold by a business. | | | | - `net_credit_sales` (float): Sales where the cash is collected at a later date. | |----------------------------|----------------------------------------|----------------------------------------------------------------------| +| GET /price_elasticity | Price Elasticity for Demand Calculator | - `initial_price` (float): +The initial price of the product or service. | +| | | - `final_price` (float): The final price of the product or service. | +| | | - `initial_quantity` (float): The initial quantity demanded of the product or service. | +| | | - `final_quantity` (float): The final quantity demanded of the product or service. | +|----------------------------|----------------------------------------|----------------------------------------------------------------------| diff --git a/ENDPOINTS.md b/ENDPOINTS.md index 4cdd7567..07b6f905 100644 --- a/ENDPOINTS.md +++ b/ENDPOINTS.md @@ -2203,4 +2203,20 @@ Sample Output "Days of Payables Outstanding": 103.42, "Cash Conversion Cycle": 90.64 days", } +``` +**POST** `/price-elasticity` + +- Request body : `{ + "initial_price": 10.0, + "final_price": 8.0, + "initial_quantity": 1000, + "final_quantity": 1200 +}` +- Sample output + +```py +{ + "Tag": "Price Elasticity for Demand Calculator", + "price_elasticity": -1.5 +} ``` \ No newline at end of file diff --git a/helpers/functions.py b/helpers/functions.py index a310dd63..7f09ff09 100644 --- a/helpers/functions.py +++ b/helpers/functions.py @@ -2021,3 +2021,12 @@ def cash_conversion_cycle(beginning_inventory: float, ending_inventory: float, b days_of_payables_outstanding = (average_payable / cost_of_goods_sold / 365) ccc = days_of_inventory_outstanding + days_of_sales_outstanding - days_of_payables_outstanding return ccc + +# Function to Calculate Price Elasticity for demand Calculator + +def calculate_price_elasticity(initial_price: float, final_price: float, initial_quantity: float, final_quantity: float): + percentage_change_price = (final_price - initial_price) / initial_price + percentage_change_quantity = (final_quantity - initial_quantity) / initial_quantity + price_elasticity = percentage_change_quantity / percentage_change_price + + return price_elasticity diff --git a/main.py b/main.py index 95181d4d..3673b28c 100644 --- a/main.py +++ b/main.py @@ -133,8 +133,9 @@ from tasks.defensive_interval_ratio import defensive_interval_ratio_task from tasks.RateofReturn import calculate_rate_of_return from tasks.cash_conversion_cycle import cash_conversion_cycle_task -from validators.request_validators import SimpleInterestRateRequest, calculatePension, compoundInterest, futureSip, paybackPeriod, capmRequest, DebtServiceCoverageRatio, futureValueOfAnnuity, futureValueOfAnnuityDue, ProfitPercentage, LossPercentage, DefensiveIntervalRatio, CashConversionCycle, RateofReturn, financialAssestRatio +from validators.request_validators import SimpleInterestRateRequest, calculatePension, compoundInterest, futureSip, paybackPeriod, capmRequest, DebtServiceCoverageRatio, futureValueOfAnnuity, futureValueOfAnnuityDue, ProfitPercentage, LossPercentage, DefensiveIntervalRatio, CashConversionCycle, RateofReturn, financialAssestRatio, PriceElasticity from tasks.financialAssestRatio import financial_assest_ratio +from tasks.PriceElasticity import calculate_price_elasticity # Creating the app app = FastAPI( @@ -1922,3 +1923,16 @@ def cash_conversion_cycle(request: CashConversionCycle): return cash_conversion_cycle_task(request.beginning_inventory , request.ending_inventory , request.beginning_receivables, request.ending_receivables , request.beginning_payable, request.ending_payable , request.net_credit_sales , request.cost_of_goods_sold) + +# Endpoint to calculate Price Elasticity + +@app.post( + "/price_elasticity", + tags=["price_elasticity"], + description="Calculate Cash Conversion Cycle", +) +def price_elasticity(request: PriceElasticity): + return calculate_price_elasticity(request.initial_price , + request.final_price , + request.initial_quantity, + request.final_quantity ) \ No newline at end of file diff --git a/tasks/PriceElasticity.py b/tasks/PriceElasticity.py new file mode 100644 index 00000000..7ada0b43 --- /dev/null +++ b/tasks/PriceElasticity.py @@ -0,0 +1,15 @@ +from helpers import functions +from fastapi import HTTPException, status + +def calculate_price_elasticity(initial_price: float, final_price: float, initial_quantity: float, final_quantity: float): + try: + percentage_change_price = (final_price - initial_price) / ((final_price + initial_price) / 2) + percentage_change_quantity = (final_quantity - initial_quantity) / ((final_quantity + initial_quantity) / 2) + price_elasticity = percentage_change_quantity / percentage_change_price + + return { + "Tag": "Price Elasticity for demand Calculator", + "Price Elasticity": price_elasticity, + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/validators/request_validators.py b/validators/request_validators.py index 29d2b423..1420bdb1 100644 --- a/validators/request_validators.py +++ b/validators/request_validators.py @@ -628,3 +628,9 @@ class CashConversionCycle(BaseModel): ending_payable: float cost_of_goods_sold: float net_credit_sales: float + +class PriceElasticity(BaseModel): + initial_price: float + final_price: float + initial_quantity: float + final_quantity: float \ No newline at end of file From 77b76e635397e2c5b87767e60437b18541d84ee0 Mon Sep 17 00:00:00 2001 From: Subho Ghosh <93722719+ighoshsubho@users.noreply.github.com> Date: Fri, 14 Jul 2023 13:37:02 +0530 Subject: [PATCH 60/66] Update main.py --- main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main.py b/main.py index 7bd8302e..dff19afa 100644 --- a/main.py +++ b/main.py @@ -1935,7 +1935,7 @@ def cash_conversion_cycle(request: CashConversionCycle): description="Calculate Policy premium", ) def policy_premium(request: PolicyPremium): - return policy_premium(request.policy_type, + return calculate_policy_premium(request.policy_type, request.age, request.coverage_amount, request.deductible, From 8ed34591d5dbd0af08680146c6d4add7f9c9b615 Mon Sep 17 00:00:00 2001 From: Subho Ghosh <93722719+ighoshsubho@users.noreply.github.com> Date: Fri, 14 Jul 2023 13:38:53 +0530 Subject: [PATCH 61/66] Update main.py --- main.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/main.py b/main.py index dff19afa..da264914 100644 --- a/main.py +++ b/main.py @@ -133,10 +133,9 @@ from tasks.defensive_interval_ratio import defensive_interval_ratio_task from tasks.RateofReturn import calculate_rate_of_return from tasks.cash_conversion_cycle import cash_conversion_cycle_task -from validators.request_validators import SimpleInterestRateRequest, calculatePension, compoundInterest, futureSip, paybackPeriod, capmRequest, DebtServiceCoverageRatio, futureValueOfAnnuity, futureValueOfAnnuityDue, ProfitPercentage, LossPercentage, DefensiveIntervalRatio, CashConversionCycle, RateofReturn, financialAssestRatio, PolicyPremium from tasks.financialAssestRatio import financial_assest_ratio from tasks.PolicyPremium import calculate_policy_premium -from validators.request_validators import SimpleInterestRateRequest, calculatePension, compoundInterest, futureSip, paybackPeriod, capmRequest, DebtServiceCoverageRatio, futureValueOfAnnuity, futureValueOfAnnuityDue, ProfitPercentage, LossPercentage, DefensiveIntervalRatio, CashConversionCycle, RateofReturn, financialAssestRatio, PriceElasticity +from validators.request_validators import SimpleInterestRateRequest, calculatePension, compoundInterest, futureSip, paybackPeriod, capmRequest, DebtServiceCoverageRatio, futureValueOfAnnuity, futureValueOfAnnuityDue, ProfitPercentage, LossPercentage, DefensiveIntervalRatio, CashConversionCycle, RateofReturn, financialAssestRatio, PriceElasticity, PolicyPremium from tasks.financialAssestRatio import financial_assest_ratio from tasks.PriceElasticity import calculate_price_elasticity From 3abc022632ff1c493bc5c1499a4cb1553df1975c Mon Sep 17 00:00:00 2001 From: Subho Ghosh <93722719+ighoshsubho@users.noreply.github.com> Date: Sat, 15 Jul 2023 15:29:35 +0530 Subject: [PATCH 62/66] Update Readme.md --- Readme.md | 1 - 1 file changed, 1 deletion(-) diff --git a/Readme.md b/Readme.md index 34bc0fae..2a11c976 100644 --- a/Readme.md +++ b/Readme.md @@ -1,4 +1,3 @@ -# THIS IS FOR TEST PURPOSE

FinTech API v2

From 446a6d239692216a22ea001682875fe8bb71a742 Mon Sep 17 00:00:00 2001 From: Robera Negussie <47657043+roberanegussie@users.noreply.github.com> Date: Wed, 19 Jul 2023 07:27:09 +0300 Subject: [PATCH 63/66] Update DOCUMENTATION.md --- DOCUMENTATION.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 14aae8b4..4429a0ec 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -62,5 +62,7 @@ The initial price of the product or service. | | | | - `initial_quantity` (float): The initial quantity demanded of the product or service. | | | | - `final_quantity` (float): The final quantity demanded of the product or service. | |----------------------------|----------------------------------------|----------------------------------------------------------------------| - - +| GET /average_payment_period | Calculate Average Payment Period | - `beginning_accounts_payable` (float): The amount of accounts payable beginning the cycle. | +| | | - `ending_inventory` (float): The final amount of accounts payable ending the cycle. | +| | | - `total_credit_purchases` (float): The amount of purchases on credit during the cycle. | +|-----------------------------|----------------------------------------|---------------------------------------------------------------------| From 75e761d9e2d1adc65f22e38a41e114d3e6e30645 Mon Sep 17 00:00:00 2001 From: Robera Negussie <47657043+roberanegussie@users.noreply.github.com> Date: Wed, 19 Jul 2023 07:27:38 +0300 Subject: [PATCH 64/66] averagePaymentPeriod --- ENDPOINTS.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/ENDPOINTS.md b/ENDPOINTS.md index a5f4f349..356104ed 100644 --- a/ENDPOINTS.md +++ b/ENDPOINTS.md @@ -2230,4 +2230,24 @@ Sample Output "Tag": "Price Elasticity for Demand Calculator", "price_elasticity": -1.5 } +``` + +**POST** `/average_payment_period` + +- Request body : `{ + "beginning_accounts_payable": 110000, + "ending_accounts_payable": 95000, + "total_credit_purchases": 1110000 +}` +- Sample output + +```py +{ + "Tag": "Average Payment Period", + "Beginning Accounts Payable": 110000, + "Ending Accounts Payable": 95000, + "Total Credit Purchases": 1110000, + "Average Accounts Payable": 102500, + "Average Payment Period": "33.7days", +} ``` \ No newline at end of file From 0a5cd1844d595342140070ae4b14313048303548 Mon Sep 17 00:00:00 2001 From: Robera Negussie <47657043+roberanegussie@users.noreply.github.com> Date: Wed, 19 Jul 2023 07:28:26 +0300 Subject: [PATCH 65/66] averagePaymentPeriod --- helpers/functions.py | 9 +++++++++ main.py | 16 +++++++++++++++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/helpers/functions.py b/helpers/functions.py index e399efe2..5c84c479 100644 --- a/helpers/functions.py +++ b/helpers/functions.py @@ -2046,3 +2046,12 @@ def calculate_price_elasticity(initial_price: float, final_price: float, initial price_elasticity = percentage_change_quantity / percentage_change_price return price_elasticity + +# Function to Calculate Average Payment Period + +def average_payment_period(beginning_accounts_payable: float, ending_accounts_payable: float, +total_credit_purchases: float): + average_accounts_payable = (beginning_accounts_payable + ending_accounts_payable) / 2 + app = average_accounts_payable / (total_credit_purchases / 365) + return app + diff --git a/main.py b/main.py index da264914..e387738b 100644 --- a/main.py +++ b/main.py @@ -135,9 +135,10 @@ from tasks.cash_conversion_cycle import cash_conversion_cycle_task from tasks.financialAssestRatio import financial_assest_ratio from tasks.PolicyPremium import calculate_policy_premium -from validators.request_validators import SimpleInterestRateRequest, calculatePension, compoundInterest, futureSip, paybackPeriod, capmRequest, DebtServiceCoverageRatio, futureValueOfAnnuity, futureValueOfAnnuityDue, ProfitPercentage, LossPercentage, DefensiveIntervalRatio, CashConversionCycle, RateofReturn, financialAssestRatio, PriceElasticity, PolicyPremium +from validators.request_validators import SimpleInterestRateRequest, calculatePension, compoundInterest, futureSip, paybackPeriod, capmRequest, DebtServiceCoverageRatio, futureValueOfAnnuity, futureValueOfAnnuityDue, ProfitPercentage, LossPercentage, DefensiveIntervalRatio, CashConversionCycle, RateofReturn, financialAssestRatio, PriceElasticity, PolicyPremium, AveragePaymentPeriod from tasks.financialAssestRatio import financial_assest_ratio from tasks.PriceElasticity import calculate_price_elasticity +from tasks.average_payment_period import average_payment_period_task # Creating the app app = FastAPI( @@ -269,6 +270,7 @@ def index(): "/portfolio_return_monte_carlo":"Calculates Portfolio returns based on Monte Carlo Simulation", "/profit_percent": "Calculates the profit percentage", "/loss_percent": "Calculates the loss percentage", + "/average_payment_period": "Calculate Average Payment Period a metric that allows a business to see how long it takes on average to pay its vendors." }, } @@ -1952,3 +1954,15 @@ def price_elasticity(request: PriceElasticity): request.final_price , request.initial_quantity, request.final_quantity ) + + +# Endpoint to calculate Average Payment Period +@app.post( + "/average_payment_period", + tags=["average_payment_period"], + description="Calculate Average Payment Period", +) +def average_payment_period(request: AveragePaymentPeriod): + return average_payment_period_task(request.beginning_accounts_payable , + request.ending_accounts_payable , request.total_credit_purchases) + From c6a912c98f927978ff1af766cb1887fcb53ad51e Mon Sep 17 00:00:00 2001 From: Robera Negussie <47657043+roberanegussie@users.noreply.github.com> Date: Wed, 19 Jul 2023 07:28:53 +0300 Subject: [PATCH 66/66] averagePaymentPeriod --- tasks/average_payment_period.py | 20 ++++++++++++++++++++ validators/request_validators.py | 5 +++++ 2 files changed, 25 insertions(+) create mode 100644 tasks/average_payment_period.py diff --git a/tasks/average_payment_period.py b/tasks/average_payment_period.py new file mode 100644 index 00000000..799adc26 --- /dev/null +++ b/tasks/average_payment_period.py @@ -0,0 +1,20 @@ +from helpers import functions +from fastapi import HTTPException, status + + +def average_payment_period_task(beginning_accounts_payable: float, ending_accounts_payable: float, +total_credit_purchases: float): + try: + average_accounts_payable = (beginning_accounts_payable + ending_accounts_payable) / 2 + app = functions.average_payment_period(beginning_accounts_payable, ending_accounts_payable, total_credit_purchases) + return { + "Tag": "Average Payment Period", + "Beginning Accounts Payable": beginning_accounts_payable, + "Ending Accounts Payable": ending_accounts_payable, + "Total Credit Purchases": total_credit_purchases, + "Average Accounts Payable": average_accounts_payable, + "Average Payment Period": f"{app} days", + } + except: + return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + diff --git a/validators/request_validators.py b/validators/request_validators.py index 6d224033..cd4f5867 100644 --- a/validators/request_validators.py +++ b/validators/request_validators.py @@ -643,3 +643,8 @@ class PriceElasticity(BaseModel): final_price: float initial_quantity: float final_quantity: float + +class AveragePaymentPeriod(BaseModel): + beginning_accounts_payable: float + ending_accounts_payable: float + total_credit_purchases: float \ No newline at end of file