# SIP Calculator — Generated Backend

## Overview

This is a FastAPI backend for the **SIP Calculator**, a financial planning tool that calculates and visualizes potential returns from Systematic Investment Plans (SIP) in mutual funds.

The application provides:
- **Real-time SIP calculations** using standard compound interest formulas
- **Investment projection** with year-by-year growth visualization
- **Validation** of investment parameters (₹500-₹100,000 monthly, 1%-30% returns, 1-40 years)
- **Chart data generation** for interactive frontend visualization
- **Stateless operation** with no authentication required

### Key Features

- Calculate maturity value using SIP formula: `M = P × ({[1 + i]^n – 1} / i) × (1 + i)`
- Generate yearly chart data points showing invested amount vs. projected value
- Validate inputs against business rules (investment range, return rate, time period)
- Support cascading deletion of calculations with results and chart data
- All currency amounts in Indian Rupees (₹) with 2 decimal place precision

## Requirements

- **Python 3.11+**
- **uv** (Python package installer and environment manager)
- **PostgreSQL** (or SQLite for development)

## Install uv

Install `uv` to manage dependencies and run the application:

```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
```

After installation, restart your terminal or run:

```bash
source $HOME/.cargo/env
```

## Install Dependencies

Clone the repository and install dependencies:

```bash
cd sip-calculator-backend
uv sync
```

This will create a virtual environment and install all required packages including:
- FastAPI
- Uvicorn
- SQLAlchemy
- Pydantic
- Python-Decimal

## Run the Backend

Start the development server with auto-reload:

```bash
uv run uvicorn main:app --reload
```

The API will be available at: **http://localhost:8000**

### Environment Variables

Create a `.env` file in the project root:

```env
DATABASE_URL=postgresql://user:password@localhost:5432/sip_calculator
# Or for development with SQLite:
# DATABASE_URL=sqlite:///./sip_calculator.db
```

## API Docs

Once the server is running, access interactive API documentation:

- **Swagger UI**: http://localhost:8000/docs
- **ReDoc**: http://localhost:8000/redoc

## OpenAPI JSON

Download the OpenAPI specification:

```bash
curl http://localhost:8000/openapi.json > openapi.json
```

## Project Files

```
sip-calculator-backend/
├── main.py                    # FastAPI application entry point
├── models.py                  # SQLAlchemy database models
├── schemas.py                 # Pydantic request/response schemas
├── database.py                # Database connection and session
├── services.py                # Business logic and SIP calculations
├── pyproject.toml             # Project dependencies (uv managed)
├── .env                       # Environment configuration
└── README.md                  # This file
```

## Example Workflow

### 1. Create a New SIP Calculation

Calculate returns for ₹10,000 monthly investment at 12% annual return for 10 years:

```bash
curl -X POST http://localhost:8000/calculations \
  -H "Content-Type: application/json" \
  -d '{
    "monthly_investment": 10000,
    "expected_return_rate": 12,
    "time_period": 10
  }'
```

**Response:**

```json
{
  "id": "calc_abc123",
  "monthly_investment": 10000.00,
  "expected_return_rate": 12.00,
  "time_period": 10,
  "timestamp": "2024-01-15T10:30:00Z",
  "calculation_result": {
    "id": "result_xyz789",
    "total_investment": 1200000.00,
    "estimated_returns": 1120000.50,
    "maturity_value": 2320000.50
  },
  "chart_data_points": [
    {
      "year": 1,
      "invested_amount": 120000.00,
      "projected_value": 127628.40
    },
    {
      "year": 2,
      "invested_amount": 240000.00,
      "projected_value": 270954.30
    }
    // ... more years
  ]
}
```

### 2. Retrieve Calculation Details

Get full details including result and chart data:

```bash
curl http://localhost:8000/calculations/calc_abc123/details
```

### 3. List All Calculations

Retrieve all stored calculations:

```bash
curl http://localhost:8000/calculations
```

### 4. Delete a Calculation

Remove a calculation (cascades to results and chart data):

```bash
curl -X DELETE http://localhost:8000/calculations/calc_abc123
```

## Next Steps

This generated backend is a starting point. Consider these improvements for production:

### 1. **Database Persistence**
   - Configure PostgreSQL connection
   - Run migrations with Alembic
   - Add database indexes for performance
   - Implement connection pooling

### 2. **Authentication & Authorization**
   - Add user authentication (JWT tokens)
   - Implement user-specific calculation history
   - Add rate limiting and API key management

### 3. **Code Organization**
   - Split into separate modules: `routers/`, `services/`, `models/`, `schemas/`
   - Create `calculations.py` router for endpoint organization
   - Move SIP formula logic to dedicated `sip_service.py`
   - Separate database models from business logic

### 4. **Testing**
   - Add unit tests with `pytest`
   - Test SIP calculation accuracy with known values
   - Add integration tests for API endpoints
   - Implement validation test cases for boundary conditions

### 5. **Production Readiness**
   - Add logging and monitoring (structured logs)
   - Implement error handling and custom exceptions
   - Add CORS middleware configuration
   - Set up Docker containerization
   - Configure CI/CD pipeline

### 6. **Feature Enhancements**
   - Implement step-up SIP (annual increment)
   - Add tax calculation (LTCG/STCG)
   - Support multiple currencies
   - Generate PDF reports
   - Add comparison mode for multiple scenarios

### 7. **Performance Optimization**
   - Cache frequently used calculations
   - Optimize chart data generation for large time periods
   - Add database query optimization
   - Implement async background tasks for heavy calculations

---

**Need help?** Check the API documentation at `/docs` or review the business rules in the source analysis document.
