Skip to content

Commit

Permalink
Merge branch 'main' into StockPrice
Browse files Browse the repository at this point in the history
  • Loading branch information
Killer2OP authored Aug 8, 2023
2 parents 817de5a + af39857 commit 1482af7
Show file tree
Hide file tree
Showing 11 changed files with 272 additions and 13 deletions.
13 changes: 11 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,25 @@ fintect-api
└───📂tasks
│ │ { Python functions for different tasks }
|
└───📂tests
│ | { Python functions for different tests }
|
└───📂validators
│ │ { Pydantic Models for different validations }
📄.dockerfile
📄.gitignore
📄CODE_OF_CONDUCT.md
📄CONTRIBUTING.md
📄docker-compose.yml
📄Dockerfile
📄DOCUMENTATION.md
📄ENDPOINTS.md
📄LICENSE.md
📄main.py
📄README.md
📄requirements.txt
📄test_main.py
```


Expand Down
13 changes: 12 additions & 1 deletion DOCUMENTATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,17 @@ The initial price of the product or service. |
| | | - `interest_rate` (float): The annual interest rate on the savings. |
| | | - `goal_amount ` (float): The desired savings goal amount. |
|-----------------------------|----------------------------------------|----------------------------------------------------------------------|
| POST /interest_coverage_ratio | Calculate interest coverage ratio | - `revenue` (float): The amount of income generated through business operations. |
| | | - `cost_of_goods_services` (float): Total amount of costs spent on goods and services.|
| | | - `operating_expenses` (int): The amount of operating expenses. |
| | | - `interest_expense` (int): The cost incurred by an entity for borrowed funds. |
|-------------------------------|----------------------------------------|---------------------------------------------------------|
| POST /tax_bracket_calculator | Calculate Tax Bracket Calculator | - `income` (float): The total income earned by the individual. |
| | | - `filing_status` (String): The tax filing status of the individual.|
|-------------------------------|----------------------------------------|---------------------------------------------------------|
| POST /margin_of_safety | Calculate margin of safety | - `current_sales` (float): The amount of current sales. |
| | | - `break_even_point` (float): The break_even_point amount. |
|--------------------------- ---|----------------------------------------|---------------------------------------------------------|
| GET /predict_stock_price | Calculate Stock Price | - `Historical_Price_Data` (int): A list or numpy array containing historical stock prices, used as input for stock price prediction. |
| | | - `Time_Horizon` (int): The number of days in the future for which the stock price is to be predicted. |
|-----------------------------|----------------------------------------|---------------------------------------------------------------------|
|-----------------------------|----------------------------------------|---------------------------------------------------------------------|
57 changes: 57 additions & 0 deletions ENDPOINTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -2306,6 +2306,63 @@ Sample Output
"total_contributions": 3600,
"interest_earned": 315.27777777777777
}
```
**POST** `/interest_coverage_ratio`
- Request body : `{
"revenue": 150000,
"cost_of_goods_services": 50000,
"operating_expenses": 40000
"interest_expense": 16000
}`
- Sample output
```py
{
"Tag": "Interest Coverage Ratio"
"Revenue": 150000,
"Cost of Goods and Services": 50000,
"Operating Expenses": 40000,
"Interest Expenses": 16000,
"Earnings Before Interest and Taxes": 60000,
"Interest Coverage Ratio": "3.75%",
}
```
**POST** `/tax_bracket_calculator`
- Request body : `{
"income": 50000,
"filing_status": single,
}`
- Sample output
```py
{
"Tag": "Tax Bracket Calculator"
"applicable_tax_bracket": 12.00%,
"tax_liability": 6000.00,
}
```
**POST** `/margin_of_safety`
- Request body : `{
"current_sales": 50000,
"break_even_point": 46000
}`
- Sample output
```py
{
"Tag": "Margin Of Safety",
"Current Sales": 50000,
"Break Even Point": 46000,
"Margin Of Safety": 8%,
}
```
```
*POST* `/stock_price_prediction`
Expand Down
8 changes: 4 additions & 4 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ Welcome to FinTech API, our powerful API is designed to simplify your life by of

## 💻 Tech Stack

![Python](https://img.shields.io/badge/python-3670A0?style=for-the-badge&logo=python&logoColor=ffdd54)
![FastAPI](https://img.shields.io/badge/FastAPI-005571?style=for-the-badge&logo=fastapi)
[![Python](https://img.shields.io/badge/python-3670A0?style=for-the-badge&logo=python&logoColor=ffdd54)](https://www.python.org/doc/)
[![FastAPI](https://img.shields.io/badge/FastAPI-005571?style=for-the-badge&logo=fastapi)](https://fastapi.tiangolo.com/)


## ✨ How to use it?
Expand Down Expand Up @@ -75,8 +75,8 @@ Join our growing community of developers who have already discovered the power o

This project is a part of these Open Source Programs

- [Diversion 2K33](https://diversion.tech/)
- [GSSoC 2K33](https://gssoc.girlscript.tech/)
- [Diversion 2K23](https://diversion.tech/)
- [GSSoC 2K23](https://gssoc.girlscript.tech/)


## ✨ Thank You for Your Contribution!
Expand Down
1 change: 0 additions & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
version: "3"
services:
api:
build: .
Expand Down
46 changes: 45 additions & 1 deletion helpers/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -2069,6 +2069,50 @@ def calculate_modified_internal_rate_of_return(ending_cash_flow: float,
mirr = ((ending_cash_flow / initial_cash_flow) ** (1 / number_of_periods)) - 1
return mirr*100

# Function to Calculate Interest Coverage Ratio

def interest_coverage_ratio(revenue:float, cost_of_goods_services:float, operating_expenses:float,
interest_expense:float):
EBIT = revenue - cost_of_goods_services - operating_expenses
ratio = EBIT / interest_expense
return ratio


# Function to Calculate Tax Bracket Calculator

def tax_bracket_calculator(income:float, filing_status:str):
tax_brackets = {
'single': {0: 0.10, 9875: 0.12, 40125: 0.22, 85525: 0.24, 163300: 0.32, 207350: 0.35, 518400: 0.37},
'married_joint': {0: 0.10, 19750: 0.12, 80250: 0.22, 171050: 0.24, 326600: 0.32, 414700: 0.35, 622050: 0.37},
'head_of_household': {0: 0.10, 14100: 0.12, 53700: 0.22, 85500: 0.24, 163300: 0.32, 207350: 0.35, 518400: 0.37}
}

if filing_status not in tax_brackets:
raise ValueError("Invalid filing status.")

applicable_brackets = tax_brackets[filing_status]
tax_liability = 0
remaining_income = income

for bracket, tax_rate in applicable_brackets.items():
if remaining_income <= bracket:
tax_liability += remaining_income * tax_rate
break
else:
taxable_income_in_bracket = bracket - max(0, income - remaining_income)
tax_liability += taxable_income_in_bracket * tax_rate
remaining_income -= taxable_income_in_bracket

tax_ratio = tax_liability / income

return {"Tax Ratio": "{:.2%}".format(tax_ratio)}

# Function to Calculate Margin of Safety

def margin_of_safety(current_sales:float, break_even_point: float):
margin = ((current_sales - break_even_point) / current_sales) * 100
return margin

# Function to Calculate Stock Price

def predict_stock_price(historical_prices: int, time_horizon: int):
Expand All @@ -2082,4 +2126,4 @@ def predict_stock_price(historical_prices: int, time_horizon: int):
Returns:
predicted_price (float): The predicted stock price for the specified time horizon.
"""
return historical_prices[-1]
return historical_prices[-1]
46 changes: 43 additions & 3 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,12 +135,16 @@
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 SavingGoal, SimpleInterestRateRequest, StockPricePrediction, calculatePension, compoundInterest, futureSip, paybackPeriod, capmRequest, DebtServiceCoverageRatio, futureValueOfAnnuity, futureValueOfAnnuityDue, ProfitPercentage, LossPercentage, DefensiveIntervalRatio, CashConversionCycle, RateofReturn, financialAssestRatio, PriceElasticity, PolicyPremium, AveragePaymentPeriod, ModifiedInternalRateOfReturn
from tasks.financialAssestRatio import financial_assest_ratio
from tasks.PriceElasticity import calculate_price_elasticity
from tasks.average_payment_period import average_payment_period_task
from tasks.Saving_Goal import saving_goal
from tasks.modified_internal_rate_of_return import calculate_modified_internal_rate_of_return_task
from tasks.interest_coverage_ratio import interest_coverage_ratio_task
from tasks.tax_bracket_calculator import tax_bracket_calculator
from tasks.margin_of_safety import margin_of_safety_task
from validators.request_validators import SavingGoal, SimpleInterestRateRequest, StockPricePrediction, calculatePension, compoundInterest, futureSip, paybackPeriod, capmRequest, DebtServiceCoverageRatio, futureValueOfAnnuity, futureValueOfAnnuityDue, ProfitPercentage, LossPercentage, DefensiveIntervalRatio, CashConversionCycle, RateofReturn, financialAssestRatio, PriceElasticity, PolicyPremium, AveragePaymentPeriod, ModifiedInternalRateOfReturn
from validators.request_validators import SimpleInterestRateRequest, calculatePension, compoundInterest, futureSip, paybackPeriod, capmRequest, DebtServiceCoverageRatio, futureValueOfAnnuity, futureValueOfAnnuityDue, ProfitPercentage, LossPercentage, DefensiveIntervalRatio, CashConversionCycle, RateofReturn, financialAssestRatio, PriceElasticity, PolicyPremium, AveragePaymentPeriod, ModifiedInternalRateOfReturn, SavingGoal, InterestCoverageRatio, MarginOfSafety, TaxBracketCalculator

# Creating the app
app = FastAPI(
Expand Down Expand Up @@ -274,6 +278,9 @@ def index():
"/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.",
"/modified_internal_rate_of_return": "Calculate modified internal rate of return",
"/interest_coverage_ratio": "Calculates interest coverage ratio",
"/margin_of_safety": "Calculates margin of safety",

},
}

Expand Down Expand Up @@ -1996,6 +2003,40 @@ def saving_goal(request:SavingGoal):
request.monthly_contributions ,
request.interest_rate,
request.goal_amount )
request.Historical_Price_Data ,
request.Time_Horizon)

# Endpoint to calculate Interest Coverage Ratio

@app.post(
"/interest_coverage_ratio",
tags=["interest_coverage_ratio"],
description="Calculates interest coverage ratio",
)
def interest_coverage_ratio(request: InterestCoverageRatio):
return interest_coverage_ratio_task(request.revenue, request.cost_of_goods_services,
request.operating_expenses, request.interest_expense)

# Endpoint to calculate Tax Bracket Calculator

@app.post(
"/tax_bracket_calculator",
tags=["tax_bracket_calculator"],
description="Calculates Tax Bracket Calculator",
)
def tax_bracket_calculator(request: TaxBracketCalculator):
return interest_coverage_ratio_task(request.income, request.filing_status)

# Endpoint to calculate Margin of Safety

@app.post(
"/margin_of_safety",
tags=["margin_of_safety"],
description="Calculates margin of safety",
)
def margin_of_safety(request: MarginOfSafety):
return margin_of_safety_task(request.current_sales, request.break_even_point)


# Endpoint to calculate Stock Price
@app.post(
Expand All @@ -2004,5 +2045,4 @@ def saving_goal(request:SavingGoal):
description="Calculate Stock Price",
)
def predict_stock_price(request:StockPricePrediction):
return predict_stock_price(request.Historical_Price_Data ,
request.Time_Horizon)
return predict_stock_price(
21 changes: 21 additions & 0 deletions tasks/interest_coverage_ratio.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@

from helpers import functions
from fastapi import HTTPException, status


def interest_coverage_ratio_task(revenue:float, cost_of_goods_services:float, operating_expenses:float, interest_expense:float):
try:
EBIT = revenue - cost_of_goods_services - operating_expenses
ratio = functions.interest_coverage_ratio(revenue, cost_of_goods_services, operating_expenses, interest_expense)
return{
"Tag": "Interest Coverage Ratio",
"Revenue": revenue,
"Cost of Goods and Services": cost_of_goods_services,
"Operating Expenses": operating_expenses,
"Interest Expenses": interest_expense,
"Earnings Before Interest and Taxes": EBIT,
"Interest Coverage Ratio": f"{ratio}%",
}

except:
return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR)
16 changes: 16 additions & 0 deletions tasks/margin_of_safety.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@

from helpers import functions
from fastapi import HTTPException, status


def margin_of_safety_task(current_sales:float, break_even_point: float):
try:
margin = functions.margin_of_safety (current_sales, break_even_point)
return{
"Tag": "Margin Of Safety",
"Current Sales": current_sales,
"Break Even Point": break_even_point,
"Margin Of Safety": f"{margin}%",
}
except:
return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR)
48 changes: 48 additions & 0 deletions tasks/tax_bracket_calculator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
from helpers import functions
from fastapi import HTTPException, status

def tax_bracket_calculator(income: float, filing_status: str,):
try:
"""
Calculate the applicable tax bracket and tax liability based on a user's income and tax filing status (United States, 2021 tax brackets for single filers).
Parameters:
income (float): The user's total income.
filing_status (str): The user's tax filing status ('single', 'married_joint', 'married_separate', 'head_of_household').
Returns:
dict: A dictionary containing the applicable tax bracket and tax liability.
- 'Tax Bracket': The user's applicable tax bracket as a percentage.
- 'Tax Liability': The calculated tax liability amount.
"""
# Tax brackets and their corresponding tax rates (United States, 2021 tax brackets for single filers)
tax_brackets = {
0: 0.10,
9875: 0.12,
40125: 0.22,
85525: 0.24,
163300: 0.32,
207350: 0.35,
518400: 0.37,
}

# Find the applicable tax bracket and calculate the tax liability
tax_liability = 0
remaining_income = income

for bracket, tax_rate in tax_brackets.items():
if remaining_income <= bracket:
tax_liability += remaining_income * tax_rate
break
else:
taxable_income_in_bracket = bracket - max(0, income - remaining_income)
tax_liability += taxable_income_in_bracket * tax_rate
remaining_income -= taxable_income_in_bracket

return {
"Tag": "Accrued Interest",
'Tax Bracket': "{:.2%}".format(tax_rate),
'Tax Liability': tax_liability,
}
except:
return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR)
16 changes: 15 additions & 1 deletion validators/request_validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -660,6 +660,20 @@ class ModifiedInternalRateOfReturn(BaseModel):
initial_cash_flow: float
number_of_periods: int

class InterestCoverageRatio(BaseModel):
revenue:float
cost_of_goods_services:float
operating_expenses:float
interest_expense:float

class TaxBracketCalculator(BaseModel):
income:float
filing_status:str

class MarginOfSafety(BaseModel):
current_sales:float
break_even_point: float

class StockPricePrediction(BaseModel):
Historical_Price_Data: int
Time_Horizon:int
Time_Horizon:int

0 comments on commit 1482af7

Please sign in to comment.