Spaces:
Sleeping
Sleeping
| # app.py — Simple Loan EMI Calculator (Hugging Face Gradio) | |
| import math | |
| import pandas as pd | |
| import gradio as gr | |
| def emi_calc(principal, annual_rate, tenure_years): | |
| # Input validation | |
| if principal is None or principal <= 0: | |
| return "Enter a valid principal (> 0).", None | |
| if annual_rate is None or annual_rate < 0: | |
| return "Enter a valid annual interest rate (>= 0).", None | |
| if tenure_years is None or tenure_years <= 0: | |
| return "Enter a valid tenure in years (> 0).", None | |
| P = float(principal) | |
| r_annual = float(annual_rate) | |
| years = float(tenure_years) | |
| n = int(round(years * 12)) | |
| r = (r_annual / 100.0) / 12.0 # monthly rate | |
| if n <= 0: | |
| return "Tenure is too small. Increase tenure.", None | |
| # EMI formula | |
| if r == 0: | |
| emi = P / n | |
| else: | |
| emi = P * r * ((1 + r) ** n) / (((1 + r) ** n) - 1) | |
| total_payable = emi * n | |
| total_interest = total_payable - P | |
| summary = ( | |
| f"### Results\n" | |
| f"- **Monthly EMI:** ₹{emi:,.2f}\n" | |
| f"- **Total Interest:** ₹{total_interest:,.2f}\n" | |
| f"- **Total Amount Payable:** ₹{total_payable:,.2f}\n" | |
| f"- **Tenure:** {n} months\n" | |
| ) | |
| # Build amortization schedule | |
| balance = P | |
| rows = [] | |
| for m in range(1, n + 1): | |
| interest = balance * r | |
| principal_paid = emi - interest | |
| if r == 0: | |
| interest = 0.0 | |
| principal_paid = emi | |
| # last month adjustment (avoid tiny negative balance due to rounding) | |
| if m == n: | |
| principal_paid = balance | |
| emi_last = principal_paid + interest | |
| balance = 0.0 | |
| rows.append([m, round(emi_last, 2), round(principal_paid, 2), round(interest, 2), round(balance, 2)]) | |
| break | |
| balance -= principal_paid | |
| rows.append([m, round(emi, 2), round(principal_paid, 2), round(interest, 2), round(balance, 2)]) | |
| df = pd.DataFrame(rows, columns=["Month", "EMI", "Principal Paid", "Interest Paid", "Balance"]) | |
| return summary, df | |
| with gr.Blocks(title="Loan EMI Calculator") as demo: | |
| gr.Markdown( | |
| "<div style='text-align:center;'>" | |
| "<h2>Simple Loan EMI Calculator</h2>" | |
| "<p>Enter loan amount, interest rate, and tenure to compute EMI and schedule.</p>" | |
| "</div>" | |
| ) | |
| with gr.Row(): | |
| principal = gr.Number(label="Loan Amount (₹)", value=500000, precision=0) | |
| annual_rate = gr.Number(label="Annual Interest Rate (%)", value=9.0, precision=2) | |
| tenure_years = gr.Number(label="Tenure (Years)", value=5, precision=2) | |
| calc_btn = gr.Button("Calculate EMI") | |
| out_md = gr.Markdown() | |
| out_table = gr.Dataframe(label="Amortization Schedule", interactive=False) | |
| calc_btn.click( | |
| fn=emi_calc, | |
| inputs=[principal, annual_rate, tenure_years], | |
| outputs=[out_md, out_table] | |
| ) | |
| demo.launch() |