Last active
January 3, 2023 12:03
-
-
Save thomasms/1cc7f6923bbafaca039d389ced782b30 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import print_function | |
import json | |
from typing import Any, Optional, Union | |
def get_interest_per_month(interest_rate_per_year: float) -> float: | |
interest_rate_per_month = (1.0 + interest_rate_per_year) ** (1.0 / 12.0) | |
# we do not consider anything more than 1e-5 for rate | |
interest_rate_per_month = round(interest_rate_per_month, 5) | |
return interest_rate_per_month - 1 | |
def get_monthly_payment( | |
principle: float, interest_rate_per_year: float, period_in_years: int | |
) -> float: | |
""" | |
Takes the interest rate per year and the number of years and calculates the monthly payment. | |
The interest rate is converted to a monthly rate. | |
""" | |
period_in_months = period_in_years * 12 | |
interest_rate_per_month = get_interest_per_month(interest_rate_per_year) + 1.0 | |
d = sum(interest_rate_per_month**i for i in range(period_in_months)) | |
# anything less than a penny is dropped | |
return ( | |
int((principle * (interest_rate_per_month**period_in_months) / d) * 100) / 100 | |
) | |
def try_numeric( | |
numstr: str, | |
default: Optional[Union[int, float]] = 0, | |
ntype: Optional[Union[int, float]] = int, | |
) -> Union[int, float]: | |
try: | |
return ntype(numstr) | |
except ValueError: | |
return default | |
def lambda_handler(event: Any, context: Any) -> Any: | |
qs_params = event.get("queryStringParameters", {}) | |
principle = try_numeric(qs_params.get("principle", 300_000), default=300_000) | |
rate_per_year = try_numeric( | |
qs_params.get("rate_per_year", 0.03), default=0.03, ntype=float | |
) | |
period_in_years = try_numeric(qs_params.get("period_in_years", 25), default=25) | |
return { | |
"statusCode": 200, | |
"body": json.dumps( | |
{ | |
"principle": principle, | |
"rate_per_year": rate_per_year, | |
"period_in_years": period_in_years, | |
"cost_per_month": get_monthly_payment( | |
principle, rate_per_year, period_in_years | |
), | |
} | |
), | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment