Skip to content

monatemedia/python-streamlit-mortgage-calculator

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

15 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Mortgage Calculator

An interactive Streamlit application for mortgage amortization calculations

Python Streamlit License

Mortgage Calculator Screenshot


πŸ”Ή About The Project

An interactive mortgage calculator built with Python and Streamlit that provides real-time amortization calculations, payment breakdowns, and cost of credit visualizations. Calculate your monthly payments and understand the true cost of your mortgage with detailed amortization schedules.

Key Features

  • Real-Time Calculations - Instant updates as you adjust loan parameters
  • Interactive Visualizations - Line charts showing payment breakdown and cost accumulation
  • Complete Amortization Table - Period-by-period breakdown of principal, interest, and balance
  • Flexible Parameters - Support for loan amounts from R50,000 to R50,000,000
  • Date-Based Scheduling - Actual payment dates based on your purchase date
  • Cost of Credit Analysis - Total interest paid over the life of the loan

πŸ”Ή Tech Stack

  • Python 3.12 - Core programming language
  • Streamlit 1.42 - Interactive web application framework
  • Pandas 2.2 - Data manipulation and table generation
  • NumPy Financial 1.0 - Financial mathematics functions
  • NumPy 2.2 - Numerical computing
  • Docker - Containerization for deployment
  • GitHub Actions - CI/CD pipeline

πŸ”Ή Getting Started

Prerequisites

  • Python 3.12 or higher
  • pip or pipenv
  • Docker & Docker Compose (for containerized deployment)

Local Installation

  1. Clone the repository

    git clone https://github.com/monatemedia/python-streamlit-mortgage-calculator.git
    cd python-streamlit-mortgage-calculator
  2. Create a virtual environment

    python -m venv venv
  3. Activate the virtual environment

    Windows (PowerShell):

    venv\Scripts\Activate

    Windows (Git Bash / MINGW64):

    source venv/Scripts/activate

    macOS/Linux/WSL:

    source venv/bin/activate
  4. Install dependencies

    pip install -r requirements.txt
  5. Run the application

    streamlit run homeLoanApp.py
  6. Access the application

    Open your browser to: http://localhost:8501

Using Pipenv

Alternatively, if you prefer Pipenv:

pipenv install
pipenv shell
streamlit run homeLoanApp.py

πŸ”Ή Docker Deployment

Local Docker

  1. Build the Docker image

    docker build -t mortgage-calculator .
  2. Run the container

    docker run -p 8501:8501 mortgage-calculator
  3. Access the application

    Open your browser to: http://localhost:8501

Docker Compose (Production)

  1. Start the application

    docker-compose up -d
  2. View logs

    docker-compose logs -f
  3. Stop the application

    docker-compose down

πŸ”Ή Usage

Input Parameters

Use the sidebar to configure your mortgage:

Parameter Range Default Description
Loan Amount R50,000 - R50,000,000 R1,250,000 Principal amount borrowed
Interest Rate % 0.0% - 20.0% 9.5% Annual interest rate
Term of Loan 5 - 30 years 20 years Loan repayment period
Purchase Date Any date Today Start date for payment schedule

Output Sections

1. Mortgage Parameters Summary

  • Quick reference table of your loan details

2. Monthly Payment Breakdown

  • Interactive line chart showing:
    • Total monthly payment
    • Principal paid per month
    • Interest paid per month
  • Summary table comparing first and final payments

3. Cost of Credit

  • Interactive line chart showing:
    • Remaining loan balance over time
    • Cumulative interest paid
  • Summary table showing:
    • Capital borrowed
    • Total interest paid
    • Total repayment amount

4. Amortization Table

  • Complete period-by-period breakdown:
    • Payment date
    • Monthly payment amount
    • Principal paid
    • Interest paid
    • Ending balance
    • Cumulative interest

πŸ”Ή Financial Calculations

Formulas Used

The calculator uses the NumPy Financial library for accurate time-value-of-money calculations:

Monthly Payment (PMT)

pmt = -1 * npf.pmt(interest / 12, years * 12, mortgage)

Principal Payment (PPMT)

principal_paid = -1 * npf.ppmt(interest / 12, period, years * 12, mortgage)

Interest Payment (IPMT)

interest_paid = -1 * npf.ipmt(interest / 12, period, years * 12, mortgage)

Ending Balance

ending_balance = previous_balance - principal_paid

Cumulative Interest

cumulative_interest = previous_cumulative + interest_paid

Edge Case Handling

The calculator includes logic to handle zero balances:

  • Prevents negative balances
  • Stops calculations when loan is fully paid
  • Sets all values to zero for periods after payoff

πŸ”Ή Project Structure

python-streamlit-mortgage-calculator/
β”œβ”€β”€ .github/
β”‚   └── workflows/
β”‚       └── docker-publish.yml    # CI/CD pipeline
β”œβ”€β”€ .dockerignore                 # Docker ignore rules
β”œβ”€β”€ .gitignore                    # Git ignore rules
β”œβ”€β”€ Dockerfile                    # Multi-stage Docker build
β”œβ”€β”€ docker-compose.yml            # Production deployment config
β”œβ”€β”€ homeLoanApp.py                # Main Streamlit application
β”œβ”€β”€ requirements.txt              # Python dependencies
β”œβ”€β”€ Pipfile                       # Pipenv dependencies
└── Pipfile.lock                  # Pipenv lock file

Code Architecture

Main Application (homeLoanApp.py)

  1. User Input Function

    • Sidebar controls for loan parameters
    • Returns pandas DataFrame with user selections
  2. Financial Calculations

    • Monthly payment using npf.pmt()
    • Principal and interest breakdown
    • Balance tracking over time
  3. Data Frame Generation

    • Date range creation using pd.date_range()
    • Period-by-period calculations
    • Cumulative interest tracking
  4. Visualizations

    • Streamlit line charts for trends
    • Markdown tables for summaries
    • Interactive data table for full schedule

πŸ”Ή Deployment

CI/CD Pipeline

The project includes a GitHub Actions workflow that:

  1. Builds Docker image on push to main branch
  2. Publishes to GitHub Container Registry (ghcr.io)
  3. Deploys to VPS via SSH
  4. Pulls and restarts container using Docker Compose

Environment Variables (Secrets)

Configure these in your GitHub repository secrets:

  • PAT - GitHub Personal Access Token for container registry
  • SSH_PRIVATE_KEY - SSH key for VPS access
  • SSH_USER - VPS username
  • SSH_HOST - VPS IP address or hostname
  • WORK_DIR - Directory containing docker-compose.yml

Nginx Reverse Proxy

The docker-compose.yml is configured to work with nginx-proxy:

environment:
  VIRTUAL_HOST: mortgage-calculator.monatemedia.com
  LETSENCRYPT_HOST: mortgage-calculator.monatemedia.com
  VIRTUAL_PORT: 8501
networks:
  - proxy-network

πŸ”Ή Demo

Status: Offline by default (resource optimization)
Available: On request via Docker Compose

To run the demo on the VPS:

docker-compose up -d

Live Demo: (when active) https://mortgage-calculator.monatemedia.com


πŸ”Ή Example Calculations

Scenario 1: Standard Home Loan

  • Loan Amount: R1,250,000
  • Interest Rate: 9.5%
  • Term: 20 years
  • Monthly Payment: ~R11,658
  • Total Interest: ~R1,548,000
  • Total Repayment: ~R2,798,000

Scenario 2: Business Property

  • Loan Amount: R5,000,000
  • Interest Rate: 12.0%
  • Term: 15 years
  • Monthly Payment: ~R60,010
  • Total Interest: ~R5,801,800
  • Total Repayment: ~R10,801,800

πŸ”Ή Development Notes

Key Implementation Details

Multi-stage Dockerfile

  • Stage 1: Build dependencies in Python 3.12-slim
  • Stage 2: Production image with non-root user (appuser)
  • Optimizations: No cache for pip, separate dependency layer

Security Features

  • Non-root user execution
  • Environment variables for Python optimization
  • Minimal base image (slim variant)

Data Validation

  • Period-by-period balance verification
  • Zero balance handling to prevent calculation errors
  • Type casting to ensure float64 precision

πŸ”Ή Future Enhancements

  • Add extra payment scenarios (lump sum, increased monthly)
  • Support for bi-weekly payment schedules
  • Comparison mode (multiple loan scenarios side-by-side)
  • Export to PDF/Excel functionality
  • Tax deduction calculations
  • Refinancing analysis tools
  • Mobile-responsive optimizations
  • Multi-currency support
  • Inflation adjustment calculator

πŸ”Ή Contributing

Contributions are welcome! Please follow these steps:

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

πŸ”Ή License

Distributed under the MIT License. See LICENSE for more information.


πŸ”Ή Contact

Edward Baitsewe
πŸ“§ edward@monatemedia.com
πŸ”— LinkedIn
🌐 Portfolio
πŸ™ GitHub

Project Link: https://github.com/monatemedia/python-streamlit-mortgage-calculator


πŸ”Ή Acknowledgments

About

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors