Skip to content

Instantly share code, notes, and snippets.

@thomasms
Last active January 3, 2023 12:03
Show Gist options
  • Save thomasms/1cc7f6923bbafaca039d389ced782b30 to your computer and use it in GitHub Desktop.
Save thomasms/1cc7f6923bbafaca039d389ced782b30 to your computer and use it in GitHub Desktop.
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