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 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. πŸ‘ + + 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 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 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/CONTRIBUTING.md b/CONTRIBUTING.md index 2a9daa9d..f7d9f1f7 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,22 +144,45 @@ 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.post( + "/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` +**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%" } ``` ++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. diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md new file mode 100644 index 00000000..4429a0ec --- /dev/null +++ b/DOCUMENTATION.md @@ -0,0 +1,68 @@ +| 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. | +| --------------------------- | ---------------------------------------- | --------------------------------------------------------- | +| 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. | +| ------------------------------- | ------------------------------------ | --------------------------------------------------------- | +| 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 | +| 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.| +|-----------------------------|----------------------------------------------|-----------------------------------------------------------| +| 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. | +| --------------------------- | ---------------------------------------- | --------------------------------------------------------- | +| 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. | + +|----------------------------|----------------------------------------|-------------------------------------------------------------------------------| +| 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. | +|----------------------------|----------------------------------------|----------------------------------------------------------------------| +| 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. | +| 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. | +|----------------------------|----------------------------------------|----------------------------------------------------------------------| +| 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. | +|-----------------------------|----------------------------------------|---------------------------------------------------------------------| diff --git a/Dockerfile b/Dockerfile index 2f09842f..9a5c7421 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,7 +1,6 @@ FROM python:3.9 - -WORKDIR /usr/src/application +WORKDIR ./app COPY requirements.txt ./ diff --git a/ENDPOINTS.md b/ENDPOINTS.md index cbccb721..356104ed 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` @@ -1751,6 +1737,34 @@ 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 + +Sample Output +```py +{ + "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 +```py +[ + "The monthly benefits are 20833.333333333332 and future benefits are 55349.83286723857" +] +``` + **GET** `/calculate_net_profit_margin` -Required parameters: `revenue`, `cost_of_goods_sold`, `operating_expenses`, `other_expenses`, `interest`, `taxes` -Sample Output @@ -1782,7 +1796,6 @@ Add-function-and-endpoint-to-calculate-lump-sum-mutual-fund-investment } ``` -``` **GET** `/calculate_sharpe_ratio_function` @@ -1796,6 +1809,7 @@ Add-function-and-endpoint-to-calculate-lump-sum-mutual-fund-investment "risk_free_rate": 0.03, "sharpe_ratio": 1.25 } +``` **GET** `/calculate_post_tax_return_percentage` -Required parameters: `tax_rate_percentage`, `annual_net_income`, `initial_cost_of_investment` @@ -1857,3 +1871,383 @@ 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 + } +``` + +**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 +} +``` + +**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%, +} +``` + +**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 + } +} +``` + +**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 +} + +``` + +**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 + } +} + +``` + +**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 +} +``` + +**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% +} +``` +**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%" +} +``` + +**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 +} +``` + +**POST** `/profit_percent` + +- 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 : `{ + "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 +} +``` + +**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, +} +``` +**POST** `/rate_return_calculator` + +- Request body : `{ + "initial_investment": 10000, + "final_value": 12500, + "time_period": 3, + "cash_flows": [500, 800, -200], + "holding_period": 2, + +**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": "Rate of return", + "rate_of_return": 25.0, + "annualized_return": 8.333333333333334, + "holding_period_return": 50.0, + "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 +} +``` + +**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", +} +``` + +**POST** `/policy-premium` + +- Request body : `{ + "policy_type": "auto", + "age": 35, + "coverage_amount": 250000, + "deductible": 500, + "num_claims": 0, + "num_accidents": 1 +**POST** `/price-elasticity` + +- Request body : `{ + "initial_price": 10.0, + "final_price": 8.0, + "initial_quantity": 1000, + "final_quantity": 1200 +}` +- Sample output + +```py +{ + "premium_amount": 1200.50 + "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 diff --git a/Readme.md b/Readme.md index f9bbc7a6..2a11c976 100644 --- a/Readme.md +++ b/Readme.md @@ -1,5 +1,4 @@ - -

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 +21,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. diff --git a/helpers/functions.py b/helpers/functions.py index 11cdb95f..5c84c479 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,19 +96,11 @@ 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) -# 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, @@ -111,7 +109,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,8 +241,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 @@ -321,7 +320,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 +333,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 +347,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) @@ -402,7 +405,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) @@ -412,11 +414,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 +455,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 +475,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 +537,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 @@ -546,9 +554,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, @@ -560,7 +568,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 +579,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, ) @@ -629,15 +639,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 @@ -689,8 +690,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 @@ -744,7 +745,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 +812,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 +869,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 +940,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 +967,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 +999,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 +1164,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 +1174,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 +1191,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 +1354,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 +1369,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 +1382,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 +1414,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 +1425,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 +1514,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 +1570,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 @@ -1578,22 +1596,128 @@ def accrint( 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 + + +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: + # 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 + + # 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 + + # 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] @@ -1604,70 +1728,50 @@ 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] - - 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 - return ctc - -#function to calculate the Sharpe ratio in Python + expected_return_of_portfolio += weight_of_investment[i] * \ + rate_of_return[i] -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 + return expected_return_of_portfolio -#You can use this function by passing your investment/portfolio returns and the risk-free rate to it. For example: +# Function to calculate net annual salary -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}") +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 Loan to Value Ratio +# function to calculate the Sharpe ratio in Python 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): """ @@ -1685,7 +1789,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 @@ -1698,3 +1803,255 @@ 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 + +#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 + +#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) + +# 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 + +# 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 + +# 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 + + +# 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 + +#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, + } + + +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 + +# 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 + +#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 + +## 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 + +# 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 + + ## 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 + +# 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 + +# 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 +# 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 + +# 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 f6857cec..e387738b 100644 --- a/main.py +++ b/main.py @@ -1,15 +1,153 @@ -from fastapi import FastAPI, HTTPException, status -from helpers import functions - - +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 +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.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.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 tasks.calculate_capm import calculate_capm +from tasks.debt_service_coverage_ratio import debt_service_coverage_ratio_task +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 tasks.RateofReturn import calculate_rate_of_return +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, 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( 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 +155,7 @@ }, ) +# Adding the routes @app.get("/") def index(): @@ -27,7 +166,6 @@ def index(): "contact": { "name": "Clueless Community", "url": "https://www.clueless.tech/", - "email": "https://www.clueless.tech/contact-us", }, "license_info": { "name": " MIT license", @@ -43,7 +181,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", @@ -130,130 +267,95 @@ 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", + "/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." }, } +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", ) -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( +@app.post( "/future_sip", tags=["future_sip"], description="Calculate Future Value of SIP", ) def future_sip( - interval_investment: float, rate_of_return: float, number_of_payments: int + request: futureSip, + payload: dict = Depends(validate_access_token) ): - 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( +@app.post( "/calculate_pension", tags=["calculate_pension"], 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.monthly_investment_amount, request.no_of_years, request.annuity_rates, request.annuity_purchased, request.yearly_interest_rates) # endpoint for payback period -@app.get( +@app.post( "/payback_period", tags=["payback_period_years"], 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. -@app.get( +@app.post( "/compound_interest", tags=["compound_interest_amount"], 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.years ,request.compounding_period) # Endpoints to calculate certificate of deposit (CD) @@ -265,36 +367,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 @@ -304,63 +383,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) - - -# 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 -): - 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 return_on_investment_task(current_value_of_investment, cost_of_investment) # Endpoint to calculate Jensen's Alpha @@ -375,23 +404,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 @@ -403,21 +416,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( @@ -426,20 +425,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 @@ -457,25 +443,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 @@ -485,17 +455,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 @@ -505,19 +465,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 @@ -535,24 +483,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 @@ -562,16 +495,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 @@ -583,17 +507,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( @@ -602,18 +516,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 @@ -623,16 +526,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: @@ -646,19 +540,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 @@ -668,21 +552,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 @@ -692,16 +562,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 @@ -715,19 +576,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 @@ -737,19 +586,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 @@ -759,19 +596,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 @@ -781,34 +606,17 @@ 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 -@app.get( +@app.post( "/weighted_average", tags=["weighted_average"], 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 @@ -822,20 +630,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( @@ -846,19 +643,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 @@ -870,19 +655,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 @@ -892,15 +665,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 @@ -915,20 +680,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 @@ -944,24 +698,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 @@ -973,18 +716,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 @@ -998,21 +730,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( @@ -1021,18 +741,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( @@ -1046,20 +755,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( @@ -1068,22 +764,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 @@ -1093,16 +774,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 @@ -1114,17 +786,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 @@ -1134,17 +798,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 @@ -1154,15 +808,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( @@ -1171,17 +817,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( @@ -1190,19 +826,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( @@ -1211,16 +835,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( @@ -1229,16 +844,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( @@ -1252,20 +858,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( @@ -1274,16 +869,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( @@ -1294,45 +880,21 @@ 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( +@app.post( "/credit_card_payoff", tags=["credit_card_payoff"], 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) ): - 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 @@ -1344,43 +906,19 @@ 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 -@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( - periodic_payment: float, number_of_periods: int, effective_interest_rate: float + request: futureValueOfAnnuity ): - 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(request.periodic_payment, request.interest_rate, request.number_of_payments) # Endpoint to calculate present value of the annuity due @@ -1392,42 +930,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) - - -@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 -): - 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 present_value_of_annuity_due_task( periodic_payment, number_of_periods, rate_per_period) # Endpoint to calculate loan to value @@ -1437,16 +940,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 @@ -1456,16 +950,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 @@ -1475,16 +960,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 @@ -1494,14 +970,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( @@ -1512,19 +981,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 @@ -1539,20 +998,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 @@ -1566,19 +1014,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 @@ -1588,18 +1026,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 @@ -1609,19 +1036,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 @@ -1633,18 +1048,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 @@ -1654,15 +1060,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 @@ -1674,18 +1072,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 @@ -1697,19 +1086,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 @@ -1719,18 +1096,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 @@ -1742,19 +1108,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 @@ -1764,18 +1118,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( @@ -1789,23 +1132,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 @@ -1815,19 +1147,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 @@ -1837,17 +1157,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 @@ -1857,17 +1167,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 @@ -1877,41 +1177,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"], @@ -1920,20 +1199,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 @@ -1943,16 +1209,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( @@ -1961,16 +1218,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( @@ -1984,21 +1232,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( @@ -2011,19 +1247,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 @@ -2041,30 +1267,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( @@ -2079,22 +1282,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 @@ -2109,21 +1297,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 @@ -2139,44 +1313,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 @@ -2193,26 +1330,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 @@ -2227,19 +1345,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( @@ -2250,37 +1356,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 @@ -2292,26 +1375,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 @@ -2329,35 +1399,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. @@ -2369,32 +1419,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 @@ -2414,29 +1439,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 @@ -2450,19 +1461,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. @@ -2480,20 +1479,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 @@ -2505,19 +1495,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", @@ -2525,17 +1503,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 @@ -2551,25 +1519,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 @@ -2582,18 +1538,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) @@ -2608,21 +1553,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( @@ -2631,21 +1562,9 @@ 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", - ) + calculate_vat_price = await calculate_vat_task(price, vat_rate) + return calculate_vat_price + # Endpoint For calculating bond equivalent yield @@ -2657,19 +1576,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") @@ -2679,40 +1586,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( @@ -2721,19 +1597,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( @@ -2742,31 +1606,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) - - -# Endpoint to calculate Personal Savings + return calculate_gratuity_task(last_salary, tenure_years, tenure_months) @app.get( @@ -2774,15 +1614,10 @@ def calculate_gratuity(last_salary: float, tenure_years: int, tenure_months: int 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): + return personal_savings_task(init, monthly, tenure) @app.get( @@ -2798,145 +1633,82 @@ 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): + + return mortrage_task(princial, interest_rate, years, down_payment, property_tax_rate, insurance_rate) + + @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): - 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) - +) +def calculate_net_profit_margin(revenue: float, + cost_of_goods_sold: float, + operating_expenses: float, + other_expenses: float, + interest: float, + taxes: float): + return calculate_net_profit_margin_task(revenue, cost_of_goods_sold, operating_expenses, other_expenses, interest, taxes) + + @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): - 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) - -#Endpoint to calculate Net annual salary of an employee +) +def calculate_expected_return_of_portfolio(no_of_investments: int, + investment_amount: list, + rate_of_return: list): + return calculate_expected_return_of_portfolio_task(no_of_investments, investment_amount, rate_of_return) + +# 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, - "ctc calculated": f"{ctc}", - } - 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): - 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) +) +def calculate_salary(base: int, + jb: int, + stock: int, + pb: int, + bonus: int, + ptax: int, + deduction: int): + return calculate_salary_task(base, jb, stock, pb, bonus, ptax, deduction) -#Endpoint for function Sharpe ratio @app.get( - "/sharpe_ratio", - tags=["sharpe_ratio"], - description="Calculate Sharpe ratio", + '/social_securities', + tags=['Social Security'], + description="Endpoint to calculate Social securities" ) -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 +def ss(birth_date: str, earnings: int, retirement_age: int): + + return ss_task(birth_date, earnings, retirement_age) + @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): + return calculate_post_tax_return_percentage_task(tax_rate_percentage, annual_net_income, initial_cost_of_investment) + +# Endpoint for function Treynor Ratio + +@app.post( "/treynor_ratio", tags=["treynor_ratio"], description="Calculate Treynor ratio", @@ -2944,33 +1716,253 @@ def sharpe_ratio( 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 -#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): - 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 +def loan_to_value_ratio(loan_amount: float, value_of_collateral: float): + return loan_to_value_ratio_task(loan_amount, value_of_collateral) + +# 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): + 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", + tags=["net_worth"], + description="Calculate net worth", +) +def net_worth_calculation(assets: float, liabilities: float, loans: float, mortgages: float): + return net_worth_calculation_task(assets, liabilities, loans, mortgages) + + +## 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): + return capital_gains_yield_task(inital_price, price_after_first_period) + +@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 + ''' + return calculate_macaulay_duration_task(face_value, coupon_rate, dt, month, year, coupon_frequency, discount_rate) + +@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 + ): + return calculate_financial_leverage_task(total_assets, total_liabilities, short_term_debt, long_term_debt) + + +@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): + 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( + "/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): + return capitalization_rate_task(rental_income, amenities, propertyManagement, propertyTaxes, insurance, current_market_value) + +@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): + 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) + +# 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) + +#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) + +# 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) + +# 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) +# 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) + + +# 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) + +# Endpoint to calculate Policy Premium + +@app.post( + "/policy_premium", + tags=["policy_premium"], + description="Calculate Policy premium", +) +def policy_premium(request: PolicyPremium): + return calculate_policy_premium(request.policy_type, + request.age, + request.coverage_amount, + request.deductible, + request.num_claims, + request.num_accidents) +# 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 ) + + +# 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) + diff --git a/requirements.txt b/requirements.txt index 0b2115e3..d3497202 100644 Binary files a/requirements.txt and b/requirements.txt differ 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/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/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/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/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/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_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/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/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/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_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/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..54d68c9d --- /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_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/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/defensive_interval_ratio.py b/tasks/defensive_interval_ratio.py new file mode 100644 index 00000000..cd122f72 --- /dev/null +++ b/tasks/defensive_interval_ratio.py @@ -0,0 +1,23 @@ +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/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/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/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/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/lumpsum.py b/tasks/lumpsum.py new file mode 100644 index 00000000..48c34d03 --- /dev/null +++ b/tasks/lumpsum.py @@ -0,0 +1,15 @@ +from helpers import functions +from fastapi import HTTPException, status +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..3d764007 --- /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_ratio(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/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/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..fb55c765 --- /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_val = 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_val}", + } + 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/test_main.py deleted file mode 100644 index c08ad8fa..00000000 --- a/test_main.py +++ /dev/null @@ -1,108 +0,0 @@ -from main import app -from fastapi import FastAPI -from fastapi.testclient import TestClient -import json - - -@app.get("/") -async def read_main(): - return {"msg": "Hello World"} - - -client = TestClient(app) - - -def test_certificate_of_deposit(): - response = client.get( - "/certificate_of_deposit/?principal_amount=5000.0&interest_rate=5.0&yrs=3&compounding_per_yr=1" - ) - assert response.status_code == 200 - - assert response.json() == { - "Tag": "Certificate of Deposit (CD)", - "Principal amount": 5000.0, - "Interest Rate": 5.0, - "Time in Years": 3, - "Number of Compounding per Year": 1, - "Certificate of Deposit (CD)": "5788.125000000001", - } - - -# Compounding per year cannot be 0, as it is division by 0 error -def test_certificate_of_deposit_invalid_value(): - response = client.get( - "/certificate_of_deposit/?principal_amount=5000.0&interest_rate=5.0&yrs=3&compounding_per_yr=0" - ) - assert response.json()["status_code"] == 500 - - -# Years cannot be a float, as it is a type error -def test_certificate_of_deposit_invalid_type(): - response = client.get( - "/certificate_of_deposit/?principal_amount=5000.0&interest_rate=5.0&yrs=3.5&compounding_per_yr=1" - ) - assert response.json() == { - "detail": [ - { - "loc": ["query", "yrs"], - "msg": "value is not a valid integer", - "type": "type_error.integer", - } - ] - } - - -def test_simple_interest_rate_main(): - response = client.get( - "/simple_interest_rate/?amount_paid=5000&principle_amount=4500&months=12" - ) - 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%", - } - - -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 - } diff --git a/tests/test_main.py b/tests/test_main.py new file mode 100644 index 00000000..6c44a0b6 --- /dev/null +++ b/tests/test_main.py @@ -0,0 +1,1425 @@ +from main import app +from fastapi import status +from fastapi.testclient import TestClient +import json + + +@app.get("/") +async def read_main(): + return {"msg": "Hello World"} + + +client = TestClient(app) + + +def test_certificate_of_deposit(): + response = client.get( + "/certificate_of_deposit/?principal_amount=5000.0&interest_rate=5.0&yrs=3&compounding_per_yr=1" + ) + assert response.status_code == 200 + + assert response.json() == { + "Tag": "Certificate of Deposit (CD)", + "Principal amount": 5000.0, + "Interest Rate": 5.0, + "Time in Years": 3, + "Number of Compounding per Year": 1, + "Certificate of Deposit (CD)": "5788.125000000001", + } + + +# Compounding per year cannot be 0, as it is division by 0 error +def test_certificate_of_deposit_invalid_value(): + response = client.get( + "/certificate_of_deposit/?principal_amount=5000.0&interest_rate=5.0&yrs=3&compounding_per_yr=0" + ) + assert response.json()["status_code"] == 500 + + +# Years cannot be a float, as it is a type error +def test_certificate_of_deposit_invalid_type(): + response = client.get( + "/certificate_of_deposit/?principal_amount=5000.0&interest_rate=5.0&yrs=3.5&compounding_per_yr=1" + ) + assert response.json() == { + "detail": [ + { + "loc": ["query", "yrs"], + "msg": "value is not a valid integer", + "type": "type_error.integer", + } + ] + } + + +def test_simple_interest_rate_main(): + response = client.get( + "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": 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 + + 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() == { + "status_code": 500, + "detail": "Internal Server Error", + "headers": None +} + + +def test_payback_period_years(): + response = client.get( + "http://127.0.0.1:8000/payback_period?years_before_recovery=2&unrecovered_cost=2456&cash_flow=21" + ) + assert response.status_code == status.HTTP_200_OK + + assert response.json() == { + "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_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": "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_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_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%" +} + + +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%" +} + 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..cd4f5867 --- /dev/null +++ b/validators/request_validators.py @@ -0,0 +1,650 @@ +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 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 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 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 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 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 personalLoan(BaseModel): + loan_amount: float + interest_rate: float + number_of_payments: int + +class calculateBvps(BaseModel): + total_equity: float + number_of_shares: float + +class capmRequest(BaseModel): + risk_free_return:float + sensitivity:float + expected_market_return:float + +class DebtServiceCoverageRatio(BaseModel): + revenue: float + operating_expenses: float + interest: float + tax_rate: float + principal: float + +class ProfitPercentage(BaseModel): + profit: float + cost_price: float + +class LossPercentage(BaseModel): + loss: float + cost_price: float + +class DefensiveIntervalRatio(BaseModel): + cash: float + marketable_securities: float + net_receivables: float + annual_operating_expenses: float + non_cash_charges: float + +class RateofReturn(BaseModel): + initial_investment: float + final_value: float + cash_flows: float + time_period: float + holding_period: float + +class financialAssestRatio(BaseModel): + current_assets: float + current_liabilities: float + total_debt: float + 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 + +class PolicyPremium(BaseModel): + policy_type: str + age: int + coverage_amount: int + deductible: int + num_claims: int + num_accidents: int + + +class PriceElasticity(BaseModel): + initial_price: float + 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