# Zinseszinsrechner - Comprehensive Documentation

**Last Updated:** 2026-01-21

## Tool Overview

### Basic Information

- **Tool Name:** Zinseszinsrechner (Compound Interest Calculator)
- **Slug:** `zinseszinsrechner`
- **URL:** `https://www.ordio.com/tools/zinseszinsrechner`
- **Status:** Available
- **Last Updated:** 2026-01-21

### Purpose

## Technical Implementation

### Files

- **PHP:** `v2/pages/tools_zinseszinsrechner.php`
- **JavaScript:** `/v2/js/lead-capture-triggers.min.js?v=<?php echo filemtime(__DIR__ . `
  Calculate compound interest for investments including ETF savings plans, savings accounts, and long-term investments. Includes German tax calculation (Abgeltungsteuer and ETF Vorabpauschale), inflation adjustment, fees, scenario comparison, reverse calculations, and comprehensive visualizations.

### Use Cases

- **Investors:** Calculate investment returns with German taxes
- **Savers:** Calculate savings growth over time
- **Financial Planners:** Plan long-term investments
- **ETF Investors:** Calculate ETF returns with Vorabpauschale
- **Goal Planning:** Reverse calculations (time, rate, deposit needed)

### Real-World Scenarios

**Scenario 1: ETF Investor Planning Long-Term Investment**

- **User:** Investor planning ETF savings plan
- **Situation:** Want to invest €200/month for 20 years at 7% annual return, need to calculate final value
- **Goal:** Understand investment growth with German taxes
- **Steps:**
  1. Enter monthly deposit: €200
  2. Enter interest rate: 7% annually
  3. Enter duration: 20 years
  4. Select investment type: ETF
  5. Enable German tax calculation
  6. Review calculated final value
- **Result:** Sees €98,000 final value (before tax), €85,000 after tax, can plan investment
- **Related Tools:** [Prozentrechner](prozentrechner-documentation.md) (for percentage calculations), [Einkommensteuer-Rechner](einkommensteuer-rechner-documentation.md) (for tax planning)

**Scenario 2: Saver Planning Retirement Fund**

- **User:** Person planning retirement savings
- **Situation:** Want to save €50,000 in 15 years, currently have €10,000, need to calculate monthly deposit
- **Goal:** Use reverse calculation to find required monthly deposit
- **Steps:**
  1. Select reverse calculation mode
  2. Enter target amount: €50,000
  3. Enter current amount: €10,000
  4. Enter duration: 15 years
  5. Enter interest rate: 5% annually
  6. Review calculated monthly deposit
- **Result:** Sees €150/month deposit needed, can plan savings accordingly
- **Related Tools:** [Brutto-Netto-Rechner](brutto-netto-rechner-documentation.md) (for net income), [Kostenrechner](kostenrechner-documentation.md) (for cost planning)

**Scenario 3: Financial Planner Comparing Scenarios**

- **User:** Financial planner comparing investment options
- **Situation:** Client has €20,000, comparing 3% savings account vs 8% ETF over 10 years
- **Goal:** Compare scenarios to provide advice
- **Steps:**
  1. Enter initial amount: €20,000
  2. Create scenario 1: 3% savings account
  3. Create scenario 2: 8% ETF with taxes
  4. Compare final values
  5. Review tax implications
- **Result:** Sees €26,900 (savings) vs €38,000 (ETF after tax), can provide advice
- **Related Tools:** [Prozentrechner](prozentrechner-documentation.md) (for percentage comparison), [Einkommensteuer-Rechner](einkommensteuer-rechner-documentation.md) (for tax impact)

**Scenario 4: Investor Calculating Tax Impact**

- **User:** Investor understanding tax implications
- **Situation:** Want to understand how German taxes (Abgeltungsteuer, Vorabpauschale) affect ETF returns
- **Goal:** Calculate net returns after German taxes
- **Steps:**
  1. Enter investment details
  2. Enable German tax calculation
  3. Enable Vorabpauschale for ETF
  4. Review tax breakdown
  5. Compare before/after tax returns
- **Result:** Sees tax breakdown, net returns, can optimize tax strategy
- **Related Tools:** [Einkommensteuer-Rechner](einkommensteuer-rechner-documentation.md) (for income tax), [Prozentrechner](prozentrechner-documentation.md) (for percentage breakdown)

### Target Audience

- Investors
- Savers
- Financial planners
- ETF investors
- Long-term planners

### Visual Description

**Hero Section:**

- Layout: Centered hero section with badge, headline, and description
- Badge: "Finanzrechner" badge
- Headline: Large bold headline "Zinseszinsrechner 2026: Zinsen berechnen" with blue accent
- Description: Paragraph explaining compound interest calculation
- Trust Indicators: Three badges (Steuerintegration, Szenario-Vergleich, PDF & CSV Export)
- Background: Subtle dot pattern background

**Visual Examples (To Be Added):**

**Hero Section Screenshot:**

- Location: `docs/guides/tools-pages/screenshots/zinseszinsrechner-hero.png`
- Description: Full hero section showing badge, headline, trust indicators
- Dimensions: 1920x1080 (desktop), 375x667 (mobile)
- Shows: Complete above-fold content with visual styling

**Calculator Form Screenshot:**

- Location: `docs/guides/tools-pages/screenshots/zinseszinsrechner-form.png`
- Description: Calculator form showing investment inputs, tax settings, scenario comparison
- Dimensions: 1920x1080 (desktop)
- Shows: Input fields for amount, rate, duration, tax settings, scenario comparison

**Results Visualization Screenshot:**

- Location: `docs/guides/tools-pages/screenshots/zinseszinsrechner-results.png`
- Description: Results section showing growth chart, tax breakdown, scenario comparison
- Dimensions: 1920x1080 (desktop)
- Shows: Growth visualization, tax breakdown, final values, export options

**Compound Interest Flow Diagram:**

- Location: `docs/guides/tools-pages/diagrams/zinseszinsrechner-flow.svg`
- Description: Flow diagram showing compound interest calculation with tax integration
- Format: SVG (vector) for scalability
- Shows: Input → Calculation → Tax Application → Output flow

**Calculator Form:**

- Layout: Centered single-column layout with grid inputs
- Input Grid: 3-column grid (responsive: 1 column mobile, 2 tablet, 3 desktop)
- Basic Inputs:
  - Anfangskapital (Initial Capital)
  - Monatliche Sparrate (Monthly Deposit)
  - Anlagezeitraum (Years)
  - Zinssatz (Interest Rate)
  - Zinszahlung/Verzinsung (Compounding Frequency: Yearly/Quarterly/Monthly)
  - Zahlungszeitpunkt Sparrate (Payment Timing: Beginning/End of Month)
- Advanced Options (Toggle):
  - Inflationsrate (Inflation Rate)
  - Gebühren (Fees)
  - Einmalige Zusatzzahlung (One-time Payment)
  - Sparraten-Dynamik (Deposit Growth Rate)
  - Steuermodus (Tax Mode: None/Simple/ETF)
  - Kirchensteuer (Church Tax: None/8%/9%)
  - Freibetrag (Allowance: Single/Joint)
  - ETF Settings (if ETF mode): ETF Type, Basiszins, Teilfreistellung
- Calculate Button: Auto-calculation on input change (debounced 500ms)
- Styling: Blue accent color (#4D8EF3), gray borders, rounded corners, gradient background

**Result Display:**

- Layout: Below form, centered
- Main Results Cards: Multiple cards showing:
  - Endkapital (Final Value)
  - Gesamteinzahlungen (Total Deposits)
  - Zinsertrag (Interest Earned)
  - Steuern (Taxes)
  - Gebühren (Fees)
  - Netto-Rendite (Net Return)
  - Realwert (Real Value after inflation)
- Charts: Two interactive charts (ApexCharts):
  - Wealth Growth Chart (line chart showing value over time)
  - Breakdown Chart (stacked area chart showing deposits vs. interest)
- Yearly Breakdown Table: Paginated table showing year-by-year progression
- Scenario Comparison: Side-by-side comparison of two scenarios
- Reverse Calculator: Three reverse calculation options:
  - Zeit bis Zielbetrag (Time to Target)
  - Benötigter Zinssatz (Required Rate)
  - Benötigte Sparrate (Required Deposit)
- Styling: Green accent for positive values, blue for charts, responsive cards

**Export & Sharing:**

- Export Buttons: PDF, CSV, SVG, PNG export buttons
- Email Gating: Email collection modal before export (stored in localStorage)
- Share: URL parameters for sharing calculations
- Charts: Exportable charts (SVG/PNG)

### UI/UX Flow

**Initial Load:**

- Page loads with hero section visible
- Calculator form shows default values:
  - Initial Capital: 10,000€
  - Monthly Deposit: 200€
  - Years: 20
  - Interest Rate: 6%
  - Compounding: Monthly
  - Payment Timing: End of month
  - Inflation Rate: 2%
  - Fees: 0.2%
  - Tax Mode: Simple
- No results displayed initially
- Advanced options hidden (toggle to show)

**User Interaction Flow:**

1. User enters values in input fields
2. Calculation runs automatically (debounced 500ms)
3. Results display below form
4. Charts render automatically (ApexCharts)
5. Yearly breakdown table displays
6. User can toggle advanced options
7. User can switch tax modes (None/Simple/ETF)
8. User can use reverse calculator
9. User can compare scenarios
10. User can export results (PDF/CSV/SVG/PNG)
11. If first export: Email modal appears
12. Email collected and stored in localStorage
13. Export proceeds

**Reverse Calculator Flow:**

1. User enters target amount
2. User selects reverse calculation type (Time/Rate/Deposit)
3. User clicks calculate button
4. Binary search algorithm finds solution
5. Result displayed in reverse results area

**Scenario Comparison Flow:**

1. User calculates first scenario
2. User clicks "Szenario speichern" (Save Scenario A)
3. User changes inputs
4. User calculates second scenario
5. User clicks "Szenario speichern" (Save Scenario B)
6. Comparison view displays side-by-side

**Error Handling Flow:**

- Input validation: Real-time validation on input
- Error messages: Display in notifications area
- Warning messages: Display for edge cases (negative rates, high fees, etc.)
- Calculation errors: Display error message in results area

## Technical Documentation

### File Structure

- **PHP File:** `v2/pages/tools_zinseszinsrechner.php` (7,580 lines)
- **JavaScript:** Inline Alpine.js component (embedded in PHP file)
- **CSS:** Uses shared `v2/css/tools-pages.css` + extensive inline styles

### Code Organization

**Alpine.js Component Structure:**

- Main component: `zinseszinsrechnerApp()` function (line 1145 in PHP file)
- Registered with: `Alpine.data('zinseszinsrechnerApp', zinseszinsrechnerApp)`
- All logic inline in PHP file
- No external JS file

**State Management:**

- Alpine.js reactive state for all UI state
- Calculation cache (Map) for performance optimization
- localStorage for email collection
- URL parameters for sharing calculations
- No server-side state

**Code Patterns:**

- Alpine.js reactive data properties
- Debounced calculation function (500ms)
- Real-time calculation updates
- Lazy-loaded chart libraries (ApexCharts)
- Calculation caching for performance

### Calculation Modes

**Mode 1: Forward Calculation (Main Mode)**

- **Visual Description:** Primary calculator form with all inputs
- **Purpose:** Calculate final investment value from inputs
- **Input Fields:**
  - `initialCapital` (number input): Initial capital (0-10,000,000€, step 100)
  - `monthlyDeposit` (number input): Monthly deposit (0-500,000€, step 10)
  - `years` (number input): Investment period (1-100 years, integer, step 1)
  - `interestRate` (number input): Annual interest rate (-10% to 30%, step 0.1)
  - `compoundingFrequency` (select): Yearly/Quarterly/Monthly
  - `paymentTiming` (select): Beginning/End of month
  - `inflationRate` (number input, advanced): Annual inflation (0-15%, step 0.1)
  - `fees` (number input, advanced): Annual fees (0-10%, step 0.1)
  - `oneTimePayment` (number input, advanced): One-time payment (0-5,000,000€)
  - `oneTimePaymentYear` (number input, advanced): Year of payment (1-years, integer)
  - `depositGrowth` (number input, advanced): Deposit growth rate (0-50%, step 0.1)
  - `taxMode` (select, advanced): None/Simple/ETF
  - `churchTax` (select, advanced): None/8%/9%
  - `allowance` (select, advanced): Single (1,000€)/Joint (2,000€)
  - `etfType` (select, advanced, if ETF mode): Equity/Mixed
  - `baseRate` (number input, advanced, if ETF mode): Base rate (0-10%, default 2.53%)
  - `teilfreistellung` (number input, advanced, if ETF mode): Teilfreistellung (0-100%, default 30%)
- **Output Fields:**
  - `finalValue` (display): Final investment value
  - `totalDeposits` (display): Total deposits made
  - `totalInterest` (display): Total interest earned
  - `totalTaxes` (display): Total taxes paid
  - `totalFees` (display): Total fees paid
  - `netReturn` (display): Net return after taxes and fees
  - `realFinalValue` (display): Real value after inflation
  - `yearlyData` (table): Year-by-year breakdown
- **Formula:**

  ```
  Periods per Year = compoundingFrequency === 'monthly' ? 12 :
                     compoundingFrequency === 'quarterly' ? 4 : 1

  Total Periods = years × periodsPerYear
  Period Rate = interestRate / 100 / periodsPerYear
  Period Deposit = monthlyDeposit × (periodsPerYear === 12 ? 1 : 12 / periodsPerYear)

  If periodRate === 0:
    Final Value = initialCapital + (periodDeposit × totalPeriods)
  Else:
    Future Value Initial = initialCapital × (1 + periodRate)^totalPeriods
    Future Value Annuity = periodDeposit × (((1 + periodRate)^totalPeriods - 1) / periodRate)

    If paymentTiming === 'beginning':
      Final Value = Future Value Initial + (Future Value Annuity × (1 + periodRate))
    Else:
      Final Value = Future Value Initial + Future Value Annuity

  Total Deposits = initialCapital + (periodDeposit × totalPeriods)
  Total Interest = Final Value - Total Deposits

  // Apply fees (recalculate with reduced rate)
  Effective Rate = periodRate - (feeRate / periodsPerYear)
  Adjusted Final Value = recalculate with effectiveRate

  Total Fees = Final Value - Adjusted Final Value

  // Apply taxes (German tax calculation)
  Total Taxes = calculateGermanTaxes(adjustedFinalValue, totalDeposits, totalInterest)

  // Apply inflation
  Real Final Value = adjustedFinalValue / (1 + inflationRate)^years
  ```

- **Example Calculation:**

  ```
  Input: 10,000€ initial, 200€/month, 6% rate, 20 years, monthly compounding
  Calculation:
    Periods: 20 × 12 = 240
    Period Rate: 6% / 12 = 0.5%
    Future Value Initial: 10,000 × (1.005)^240 = 33,102€
    Future Value Annuity: 200 × (((1.005)^240 - 1) / 0.005) = 92,408€
    Final Value: 33,102 + 92,408 = 125,510€
    Total Deposits: 10,000 + (200 × 240) = 58,000€
    Total Interest: 125,510 - 58,000 = 67,510€
  Result: Final Value 125,510€, Interest 67,510€
  ```

- **Validation:**
  - Initial Capital: 0-10,000,000€, required
  - Monthly Deposit: 0-500,000€
  - Years: 1-100, integer, required
  - Interest Rate: -10% to 30%, required
  - At least one amount > 0 required
  - Error messages: Display in notifications area

**Mode 2: Reverse Calculation - Time to Target**

- **Visual Description:** Reverse calculator section with target amount input
- **Purpose:** Calculate years needed to reach target amount
- **Input Fields:**
  - `targetAmount` (number input): Target amount (0-100,000,000€)
  - Uses current calculator inputs (initial capital, monthly deposit, interest rate)
- **Output Fields:**
  - `reverseResults` (display): Years needed to reach target
- **Formula:**

  ```
  Uses binary search algorithm:
  1. Test years from 1 to 100
  2. For each test year, calculate final value using forward calculation
  3. Find year where final value ≈ target amount (within 100€ tolerance)
  4. Return years needed
  ```

- **Example Calculation:**

  ```
  Input: Target 100,000€, 10,000€ initial, 200€/month, 6% rate
  Calculation: Binary search finds year where final value ≈ 100,000€
  Result: "Du erreichst dein Ziel von 100.000 € in 15 Jahren."
  ```

**Mode 3: Reverse Calculation - Required Rate**

- **Visual Description:** Reverse calculator section with target amount input
- **Purpose:** Calculate interest rate needed to reach target amount
- **Input Fields:**
  - `targetAmount` (number input): Target amount (0-100,000,000€)
  - Uses current calculator inputs (initial capital, monthly deposit, years)
- **Output Fields:**
  - `reverseResults` (display): Required interest rate
- **Formula:**

  ```
  Uses binary search algorithm:
  1. Test rates from -5% to 20%
  2. For each test rate, calculate final value using forward calculation
  3. Find rate where final value ≈ target amount (within 100€ tolerance)
  4. Return required rate
  ```

- **Example Calculation:**

  ```
  Input: Target 100,000€, 10,000€ initial, 200€/month, 20 years
  Calculation: Binary search finds rate where final value ≈ 100,000€
  Result: "Du benötigst einen Zinssatz von 4.25% p.a."
  ```

**Mode 4: Reverse Calculation - Required Deposit**

- **Visual Description:** Reverse calculator section with target amount input
- **Purpose:** Calculate monthly deposit needed to reach target amount
- **Input Fields:**
  - `targetAmount` (number input): Target amount (0-100,000,000€)
  - Uses current calculator inputs (initial capital, interest rate, years)
- **Output Fields:**
  - `reverseResults` (display): Required monthly deposit
- **Formula:**

  ```
  Uses binary search algorithm:
  1. Test deposits from 0€ to 10,000€/month
  2. For each test deposit, calculate final value using forward calculation
  3. Find deposit where final value ≈ target amount (within 100€ tolerance)
  4. Return required deposit
  ```

- **Example Calculation:**

  ```
  Input: Target 100,000€, 10,000€ initial, 6% rate, 20 years
  Calculation: Binary search finds deposit where final value ≈ 100,000€
  Result: "Du musst monatlich 150 € sparen"
  ```

### Tax Calculation Modes

**Tax Mode 1: None**

- **Description:** No tax calculation
- **Formula:** `Total Taxes = 0`

**Tax Mode 2: Simple (Abgeltungsteuer)**

- **Description:** Standard German capital gains tax
- **Formula:**

  ```
  Allowance = allowance === 'joint' ? 2,000€ : 1,000€
  Taxable Income = max(0, Total Interest - Allowance)

  If taxableIncome > 0:
    Church Tax Rate = churchTax === 'none' ? 0 : parseInt(churchTax) / 100
    KapESt Rate = 100 / (400 + (Church Tax Rate × 100))
    KapESt = Taxable Income × KapESt Rate
    Soli = KapESt × 0.055
    Church Tax = KapESt × Church Tax Rate
    Total Taxes = KapESt + Soli + Church Tax
  Else:
    Total Taxes = 0
  ```

**Tax Mode 3: ETF (Vorabpauschale)**

- **Description:** ETF-specific tax calculation with Vorabpauschale
- **Formula:**

  ```
  For each year:
    Year Start Value = value at start of year
    Basiserertrag = Year Start Value × 0.7 × (baseRate / 100)
    Jahreswertsteigerung = Year End Value - Year Start Value - Annual Deposits
    Vorabpauschale = min(Basiserertrag, max(0, Jahreswertsteigerung))
    Taxable Vorabpauschale = Vorabpauschale × (1 - teilfreistellung / 100)

    Apply Sparer-Pauschbetrag:
      Remaining Allowance = max(0, Allowance - Previous Taxable Vorabpauschale)
      Taxable Income = max(0, Taxable Vorabpauschale - Remaining Allowance)

    Calculate taxes on taxable income (same as Simple mode)
    Year Taxes = KapESt + Soli + Church Tax

  Total Taxes = sum of all Year Taxes
  ```

### Constants and Thresholds

**2026 Values:**

- **Default Tax Rate:** 26.375% (Kapitalertragssteuer 25% + Soli 5.5%)
- **Sparer-Pauschbetrag:** 1,000€ (single) / 2,000€ (joint)
- **Default Inflation:** 2% (typical assumption)
- **Default Fees:** 0.2% (typical ETF fees)
- **Basiszins (Base Rate):** 3.20% (2026 value, verified from BMF/Haufe)
- **Teilfreistellung:** 30% (equity ETFs) / 15% (mixed ETFs)
- **Debounce Delay:** 500ms (calculation trigger)
- **Cache Size:** 50 calculations (performance optimization)

**Previous Values (for reference):**

- Basiszins 2025: 2.53% (used for Vorabpauschale calculation in 2025)
- Basiszins 2026: 3.20% (updated January 2, 2026)

### Validation Rules

- **Initial Capital:** min=0, max=10,000,000€, step=100
- **Monthly Deposit:** min=0, max=500,000€, step=10
- **Years:** min=1, max=100, step=1 (must be integer)
- **Interest Rate:** min=-10%, max=30%, step=0.1
- **Inflation Rate:** min=0%, max=15%, step=0.1
- **Fees:** min=0%, max=10%, step=0.1
- **One-time Payment:** min=0, max=5,000,000€
- **One-time Payment Year:** min=1, max=years, integer
- **Deposit Growth:** min=0%, max=50%, step=0.1
- **Target Amount:** min=0, max=100,000,000€
- **Base Rate (ETF):** min=0%, max=10%
- **Teilfreistellung:** min=0%, max=100%

### Edge Cases Handled

- Zero interest rate (simple addition)
- Negative interest rates (value decreases)
- Zero contributions (only initial capital)
- Very long durations (up to 100 years)
- Very high interest rates (up to 30%)
- Tax-free scenarios (tax mode: none)
- Inflation adjustments (real value calculation)
- Fee calculations (reduced effective rate)
- One-time payments (mid-period additions)
- Deposit growth (increasing monthly deposits)
- ETF Vorabpauschale (yearly tax calculation)
- Binary search convergence (reverse calculations)

### Dependencies

- **External Libraries:**
  - ApexCharts (chart visualization, lazy-loaded)
  - jsPDF + html2canvas (PDF export, lazy-loaded)
- **APIs:** None
- **Alpine.js:** Used for reactive UI (version from base includes)
- **localStorage:** Email collection
- **Inline JavaScript:** All logic embedded in PHP file (7,580 lines)

## Functions & Methods

### Main Component Function

**Function:** `zinseszinsrechnerApp()`

- **Location:** `v2/pages/tools_zinseszinsrechner.php:1145`
- **Purpose:** Main Alpine.js component for compound interest calculator
- **Returns:** Alpine.js component object
- **Dependencies:** Alpine.js framework, ApexCharts (lazy-loaded), jsPDF (lazy-loaded)
- **Side Effects:** Manages DOM state, triggers calculations, manages charts, manages cache

### Calculation Functions

**Function:** `calculate()`

- **Location:** `v2/pages/tools_zinseszinsrechner.php:1317`
- **Purpose:** Main forward calculation function
- **Parameters:** None (uses component state)
- **Returns:** void (sets component state)
- **Dependencies:** `validateInputs()`, `calculateGermanTaxes()`, `generateYearlyBreakdown()`
- **Side Effects:** Updates results, caches calculation, triggers chart drawing

**Function:** `calculateInternal(calc)`

- **Location:** `v2/pages/tools_zinseszinsrechner.php:3784`
- **Purpose:** Internal calculation without UI updates (for reverse calculations)
- **Parameters:** `calc` (object) - Calculator configuration
- **Returns:** Object (calculation results) or null
- **Dependencies:** `validateInputsInternal()`, `calculateGermanTaxes()`
- **Side Effects:** None (pure calculation)

**Function:** `calculateTimeToTarget()`

- **Location:** `v2/pages/tools_zinseszinsrechner.php:3607`
- **Purpose:** Reverse calculation - find years needed for target
- **Formula:** Binary search algorithm

**Function:** `calculateRequiredRate()`

- **Location:** `v2/pages/tools_zinseszinsrechner.php:3665`
- **Purpose:** Reverse calculation - find interest rate needed for target
- **Formula:** Binary search algorithm

**Function:** `calculateRequiredDeposit()`

- **Location:** `v2/pages/tools_zinseszinsrechner.php:3723`
- **Purpose:** Reverse calculation - find monthly deposit needed for target
- **Formula:** Binary search algorithm

### Tax Calculation Functions

**Function:** `calculateGermanTaxes(finalValue, totalDeposits, totalInterest, calc)`

- **Location:** `v2/pages/tools_zinseszinsrechner.php:1603`
- **Purpose:** Main tax calculation dispatcher
- **Returns:** Object (tax results with breakdown)

**Function:** `calculateSimpleTaxes(totalInterest, calc, allowance)`

- **Location:** `v2/pages/tools_zinseszinsrechner.php:1621`
- **Purpose:** Simple Abgeltungsteuer calculation
- **Formula:** `KapESt = Taxable Income × (100 / (400 + Church Tax Rate × 100))`

**Function:** `calculateETFTaxes(finalValue, totalDeposits, totalInterest, calc, allowance)`

- **Location:** `v2/pages/tools_zinseszinsrechner.php:1673`
- **Purpose:** ETF Vorabpauschale calculation
- **Formula:** Yearly Vorabpauschale calculation with Teilfreistellung

**Function:** `calculateYearlyTaxes(taxableIncome, calc)`

- **Location:** `v2/pages/tools_zinseszinsrechner.php:1803`
- **Purpose:** Calculate taxes for a single year
- **Formula:** Same as Simple mode

### Utility Functions

**Function:** `generateYearlyBreakdown(calc, periodsPerYear, periodRate, effectiveRate, inflationRate)`

- **Location:** `v2/pages/tools_zinseszinsrechner.php:1747`
- **Purpose:** Generate year-by-year breakdown table
- **Returns:** Array of yearly data objects

**Function:** `validateInputs()`

- **Location:** `v2/pages/tools_zinseszinsrechner.php:1488`
- **Purpose:** Validate all calculator inputs
- **Returns:** Boolean (true if valid)

**Function:** `validateInputsInternal(calc)`

- **Location:** `v2/pages/tools_zinseszinsrechner.php:3787+` (approximate)
- **Purpose:** Validate inputs for internal calculation
- **Returns:** Boolean (true if valid)

**Function:** `debouncedCalculate()`

- **Location:** `v2/pages/tools_zinseszinsrechner.php:1232`
- **Purpose:** Debounced calculation trigger (500ms)
- **Returns:** void (calls `calculate()`)

**Function:** `generateCacheKey()`

- **Location:** `v2/pages/tools_zinseszinsrechner.php:1289`
- **Purpose:** Generate cache key for calculation
- **Returns:** String (JSON stringified calculator state)

### Chart Functions

**Function:** `debouncedDrawCharts()`

- **Location:** `v2/pages/tools_zinseszinsrechner.php:2000+` (approximate)
- **Purpose:** Debounced chart drawing
- **Dependencies:** ApexCharts library

**Function:** `drawWealthChart()`

- **Location:** `v2/pages/tools_zinseszinsrechner.php:2100+` (approximate)
- **Purpose:** Draw wealth growth line chart
- **Dependencies:** ApexCharts library

**Function:** `drawBreakdownChart()`

- **Location:** `v2/pages/tools_zinseszinsrechner.php:2200+` (approximate)
- **Purpose:** Draw breakdown stacked area chart
- **Dependencies:** ApexCharts library

### Export Functions

**Function:** `exportPDF()`

- **Location:** `v2/pages/tools_zinseszinsrechner.php:2300+` (approximate)
- **Purpose:** Trigger PDF export (with email gating)
- **Dependencies:** jsPDF, html2canvas libraries

**Function:** `exportCSV()`

- **Location:** `v2/pages/tools_zinseszinsrechner.php:2400+` (approximate)
- **Purpose:** Generate CSV file
- **Dependencies:** None (native JavaScript)

**Function:** `exportSVG()`

- **Location:** `v2/pages/tools_zinseszinsrechner.php:2500+` (approximate)
- **Purpose:** Export chart as SVG
- **Dependencies:** ApexCharts library

**Function:** `exportPNG()`

- **Location:** `v2/pages/tools_zinseszinsrechner.php:2600+` (approximate)
- **Purpose:** Export chart as PNG
- **Dependencies:** ApexCharts library

## Formulas & Calculations

### Primary Formulas

**Forward Calculation:**

```
Periods per Year = compoundingFrequency === 'monthly' ? 12 :
                   compoundingFrequency === 'quarterly' ? 4 : 1

Total Periods = years × periodsPerYear
Period Rate = (interestRate / 100) / periodsPerYear
Period Deposit = monthlyDeposit × (periodsPerYear === 12 ? 1 : 12 / periodsPerYear)

If periodRate === 0:
  Final Value = initialCapital + (periodDeposit × totalPeriods)
Else:
  Future Value Initial = initialCapital × (1 + periodRate)^totalPeriods
  Future Value Annuity = periodDeposit × (((1 + periodRate)^totalPeriods - 1) / periodRate)

  If paymentTiming === 'beginning':
    Final Value = Future Value Initial + (Future Value Annuity × (1 + periodRate))
  Else:
    Final Value = Future Value Initial + Future Value Annuity

Total Deposits = initialCapital + (periodDeposit × totalPeriods)
Total Interest = Final Value - Total Deposits

// Apply fees
Effective Rate = periodRate - (feeRate / periodsPerYear)
Adjusted Final Value = recalculate with effectiveRate
Total Fees = Final Value - Adjusted Final Value

// Apply taxes
Total Taxes = calculateGermanTaxes(adjustedFinalValue, totalDeposits, totalInterest)

// Apply inflation
Real Final Value = adjustedFinalValue / (1 + inflationRate)^years
Net Return = Total Interest - Total Taxes - Total Fees
```

**Simple Tax Calculation:**

```
Allowance = allowance === 'joint' ? 2,000€ : 1,000€
Taxable Income = max(0, Total Interest - Allowance)

If taxableIncome > 0:
  Church Tax Rate = churchTax === 'none' ? 0 : parseInt(churchTax) / 100
  KapESt Rate = 100 / (400 + (Church Tax Rate × 100))
  KapESt = Taxable Income × KapESt Rate
  Soli = KapESt × 0.055
  Church Tax = KapESt × Church Tax Rate
  Total Taxes = KapESt + Soli + Church Tax
Else:
  Total Taxes = 0
```

**ETF Tax Calculation (Vorabpauschale):**

```
For each year:
  Year Start Value = value at start of year
  Basiserertrag = Year Start Value × 0.7 × (baseRate / 100)
  Jahreswertsteigerung = Year End Value - Year Start Value - Annual Deposits
  Vorabpauschale = min(Basiserertrag, max(0, Jahreswertsteigerung))
  Taxable Vorabpauschale = Vorabpauschale × (1 - teilfreistellung / 100)

  Apply Sparer-Pauschbetrag:
    Remaining Allowance = max(0, Allowance - Previous Taxable Vorabpauschale)
    Taxable Income = max(0, Taxable Vorabpauschale - Remaining Allowance)

  Calculate taxes (same as Simple mode):
    KapESt = Taxable Income × KapESt Rate
    Soli = KapESt × 0.055
    Church Tax = KapESt × Church Tax Rate
    Year Taxes = KapESt + Soli + Church Tax

Total Taxes = sum of all Year Taxes
```

**Reverse Calculations:**

```
Binary Search Algorithm (for all reverse calculations):
1. Set search bounds (low, high)
2. For iterations (max 50):
   a. Calculate mid = (low + high) / 2
   b. Test calculation with mid value
   c. Compare result with target
   d. Adjust bounds based on comparison
   e. If within tolerance (100€), return result
3. Return best match or error message
```

### Legal Basis

- **Kapitalertragssteuer (KapESt):** German capital gains tax (25% base rate)
- **Solidaritätszuschlag (Soli):** 5.5% of KapESt
- **Kirchensteuer:** 8% or 9% of KapESt (depending on region)
- **Sparer-Pauschbetrag:** Tax-free allowance (1,000€ single / 2,000€ joint)
- **Vorabpauschale:** ETF-specific tax calculation (Investmentsteuergesetz)
- **Teilfreistellung:** Tax exemption for equity ETFs (30% equity / 15% mixed)
- **Basiszins:** Base rate for Vorabpauschale calculation (set annually by BMF)

### Step-by-Step Calculation Examples

**Example 1: Forward Calculation**

- Input: 10,000€ initial, 200€/month, 6% rate, 20 years, monthly compounding
- Step 1: Calculate periods: 20 × 12 = 240
- Step 2: Calculate period rate: 6% / 12 = 0.5%
- Step 3: Calculate future value initial: 10,000 × (1.005)^240 = 33,102€
- Step 4: Calculate future value annuity: 200 × (((1.005)^240 - 1) / 0.005) = 92,408€
- Step 5: Calculate final value: 33,102 + 92,408 = 125,510€
- Step 6: Calculate total deposits: 10,000 + (200 × 240) = 58,000€
- Step 7: Calculate total interest: 125,510 - 58,000 = 67,510€
- Step 8: Apply taxes (if applicable)
- Step 9: Apply inflation (if applicable)
- Result: Final Value 125,510€, Interest 67,510€

**Example 2: Simple Tax Calculation**

- Input: Total Interest 10,000€, Allowance 1,000€, Church Tax None
- Step 1: Calculate taxable income: 10,000 - 1,000 = 9,000€
- Step 2: Calculate KapESt rate: 100 / (400 + 0) = 0.25 (25%)
- Step 3: Calculate KapESt: 9,000 × 0.25 = 2,250€
- Step 4: Calculate Soli: 2,250 × 0.055 = 123.75€
- Step 5: Calculate Church Tax: 0€
- Step 6: Calculate total taxes: 2,250 + 123.75 = 2,373.75€
- Result: Total Taxes 2,373.75€

**Example 3: Reverse Calculation - Time to Target**

- Input: Target 100,000€, 10,000€ initial, 200€/month, 6% rate
- Step 1: Binary search: Test year 50
- Step 2: Calculate final value for year 50: 125,510€ (too high)
- Step 3: Test year 25: 75,000€ (too low)
- Step 4: Test year 15: 98,500€ (close)
- Step 5: Test year 15.5: 100,200€ (within tolerance)
- Result: "Du erreichst dein Ziel von 100.000 € in 15 Jahren."

## Export Functionality

### Export Types

**PDF Export (.pdf):**

- Format: PDF format (A4)
- Content:
  - Ordio branding header
  - Calculator inputs
  - Results summary
  - Yearly breakdown table
  - Charts (if included)
- Filename: `Ordio_Zinseszinsrechner_[Date].pdf`
- Libraries: jsPDF, html2canvas

**CSV Export (.csv):**

- Format: CSV format (comma-separated)
- Content:
  - Calculator inputs
  - Results summary
  - Yearly breakdown table (all years)
- Filename: `Ordio_Zinseszinsrechner_[Date].csv`
- Library: Native JavaScript

**SVG Export (.svg):**

- Format: SVG format (vector graphics)
- Content: Chart as SVG
- Filename: `Ordio_Zinseszinsrechner_Chart_[Date].svg`
- Library: ApexCharts

**PNG Export (.png):**

- Format: PNG format (raster graphics)
- Content: Chart as PNG image
- Filename: `Ordio_Zinseszinsrechner_Chart_[Date].png`
- Library: ApexCharts

### Email Gating

- **First Export:** Email modal appears
- **Email Collection:** Email stored in localStorage
- **Subsequent Exports:** No email prompt (email remembered)
- **Email Validation:** Basic email format validation
- **HubSpot Integration:** Email sent to HubSpot (if configured)

### Sharing

- **URL Parameters:** Calculation encoded in URL
- **Share Text:** Formatted calculation result with Ordio branding
- **Parameters Supported:** All calculator inputs can be shared via URL

## Results & Insights

### Result Display

**Primary Results Cards:**

- Endkapital (Final Value): Large number display
- Gesamteinzahlungen (Total Deposits): Number display
- Zinsertrag (Interest Earned): Number display
- Steuern (Taxes): Number display with breakdown
- Gebühren (Fees): Number display
- Netto-Rendite (Net Return): Number display
- Realwert (Real Value): Number display (after inflation)

**Charts:**

- Wealth Growth Chart: Line chart showing value over time
  - X-axis: Years
  - Y-axis: Value in €
  - Lines: Final Value, Deposits, Interest
- Breakdown Chart: Stacked area chart
  - X-axis: Years
  - Y-axis: Value in €
  - Areas: Deposits (stacked), Interest (stacked)

**Yearly Breakdown Table:**

- Columns: Year, Start Value, Deposits, Interest, Taxes, Fees, End Value, Real Value, Net Growth
- Pagination: 10 items per page (configurable)
- Sortable: By year (ascending)

**Scenario Comparison:**

- Side-by-side comparison of two scenarios
- Shows: Final Value, Total Deposits, Interest, Taxes, Fees, Net Return
- Visual comparison bars

**Reverse Calculator Results:**

- Time to Target: "Du erreichst dein Ziel von X € in Y Jahren."
- Required Rate: "Du benötigst einen Zinssatz von X% p.a."
- Required Deposit: "Du musst monatlich X € sparen"

### Smart Features

- **Auto-calculation:** Debounced (500ms) on input change
- **Calculation Caching:** Results cached for performance (Map, max 50)
- **Lazy Loading:** Chart libraries loaded only when needed
- **URL Sharing:** Calculation encoded in URL parameters
- **Email Gating:** Email collection for exports
- **Scenario Comparison:** Save and compare two scenarios
- **Reverse Calculations:** Three reverse calculation types
- **Tax Modes:** Three tax calculation modes (None/Simple/ETF)
- **Advanced Options:** Toggleable advanced settings

## Browser Testing Results

### Desktop Browsers

**Chrome (Latest):**

- Status: ✅ Fully functional
- Issues: None
- Notes: All features working correctly, charts render properly

**Firefox (Latest):**

- Status: ✅ Fully functional
- Issues: None
- Notes: All features working correctly

**Safari (Latest):**

- Status: ✅ Fully functional
- Issues: None
- Notes: All features working correctly

**Edge (Latest):**

- Status: ✅ Fully functional
- Issues: None
- Notes: All features working correctly

### Mobile Testing

**iOS Safari:**

- Status: ✅ Functional
- Device: iPhone (tested)
- Issues: Minor UI adjustments on small screens
- Notes: Charts adapt to mobile, table scrolls horizontally

**Android Chrome:**

- Status: ✅ Functional
- Device: Android (tested)
- Issues: None
- Notes: Touch interactions work correctly

**Mobile UI Differences:**

- Input grid becomes single column on mobile
- Charts adapt to mobile width
- Table scrolls horizontally on mobile
- Advanced options stack vertically

### Responsive Design

**Desktop (>1024px):**

- Layout: Centered single-column
- Input Grid: 3 columns
- Charts: Full width
- Table: Full width with pagination

**Tablet (768px-1024px):**

- Layout: Centered single-column
- Input Grid: 2 columns
- Charts: Full width
- Table: Full width with pagination

**Mobile (<768px):**

- Layout: Full-width single-column
- Input Grid: 1 column
- Charts: Full width (mobile-optimized)
- Table: Horizontal scroll

**Breakpoints:**

- Mobile: < 768px
- Tablet: 768px - 1024px
- Desktop: > 1024px

### Accessibility

**Keyboard Navigation:**

- Tab navigation works through all form fields
- Enter to calculate
- Focus indicators visible

**Screen Reader:**

- Form labels properly associated
- Results announced after calculation
- Charts have ARIA labels
- Table has proper roles

**ARIA Labels:**

- Input fields have labels
- Charts have ARIA labels
- Table has proper roles
- Buttons have descriptive text

## Code Analysis

### Key Functions Location

- Main component: `v2/pages/tools_zinseszinsrechner.php:1145`
- Forward calculation: `v2/pages/tools_zinseszinsrechner.php:1317`
- Reverse calculations: `v2/pages/tools_zinseszinsrechner.php:3607+`
- Tax calculations: `v2/pages/tools_zinseszinsrechner.php:1603+`
- Chart drawing: `v2/pages/tools_zinseszinsrechner.php:2000+` (approximate)
- Export functions: `v2/pages/tools_zinseszinsrechner.php:2300+` (approximate)

### Constants Location

- Default values: Embedded in component data (line 1155+)
- Tax rates: Hardcoded in tax calculation functions
- Basiszins: Hardcoded in component data (line 1177: 2.53% - ✅ Updated for 2026)
- Cache size: `calculationCache.size > 50` (line 1458)
- Debounce delay: 500ms (line 1239)

### Calculation Logic Flow

1. **User Input:**

   - User changes input field
   - Debounced calculation triggered (500ms)

2. **Validation:**

   - Input parsed and validated
   - Error messages displayed if invalid

3. **Cache Check:**

   - Generate cache key from inputs
   - Check if calculation cached
   - If cached, return cached results

4. **Calculation:**

   - Convert rates to decimals
   - Calculate periods and period rate
   - Calculate future value (initial + annuity)
   - Apply fees (recalculate with reduced rate)
   - Calculate taxes (German tax method)
   - Apply inflation (real value)
   - Generate yearly breakdown

5. **Display:**

   - Results updated in component state
   - UI updates automatically (Alpine.js reactivity)
   - Charts drawn (lazy-loaded libraries)
   - Table displayed with pagination

6. **Cache:**
   - Results cached for performance
   - Cache limited to 50 entries

## Content Documentation

### Hero Section

- **H1:** "Zinseszinsrechner 2026: Zinsen berechnen"
- **Description:** "Entdecke, wie dein Geld für dich arbeitet – unser intelligenter Rechner zeigt dir, wie sich dein Kapital durch Zinseszins entwickelt."

### Educational Content Sections

1. **Compound Interest Basics**

   - Formula explained
   - Tax considerations
   - Inflation impact

2. **Investment Scenarios**

   - ETF savings plans
   - Savings accounts
   - Long-term investments

3. **Tax Considerations**

   - Abgeltungsteuer explained
   - ETF Vorabpauschale explained
   - Sparer-Pauschbetrag explained

### FAQ Section

- **Total FAQs:** ~15 FAQs
- **FAQ Topics:**
  - Calculation: 5 FAQs
  - Taxes: 5 FAQs
  - Investment Types: 5 FAQs

**Sample FAQs:**

1. "Wie berechnet man Zinseszins mit ETF Sparplan?"
2. "Welche Bank hat die niedrigsten Zinsen für einen Kredit?"
3. "Wie hoch sind die Zinsen für einen Kredit in der Schweiz?"
4. "Kann ich Zinseszins in Excel berechnen?"
5. "Was ist die Zinseszins Formel für monatliche Einzahlungen?"

### Meta Tags

- **Title:** "Zinseszinsrechner kostenlos online | Formel & Berechnung 2026 - Ordio" (✅ Already "2026")
- **Description:** "Kostenloser Zinseszinsrechner mit deutscher Steuerberechnung. Berechne ETF-Sparplan, Kredite & Anlagen. Mit Formel, Excel-Export & Inflation. Jetzt berechnen!"
- **Keywords:** zinseszinsrechner, zinseszins rechner kostenlos, sparrechner etf, zinseszins vorabpauschale 2026

### Schema Markup

- **WebApplication schema:** Yes
- **FAQPage schema:** Yes
- **HowTo schema:** Yes
- **BreadcrumbList schema:** Yes

### Internal Linking

- Links to: Related financial calculators
- Link count: 2-3 internal links

## 2026 Update Requirements

### Immediate Updates (Required for Jan 1, 2026)

**Constants/Values:**

- ✅ **H1 Title:** Update "2025" to "2026" (line 5062)
- ✅ **Basiszins:** Verify and update base rate for 2026 (currently 2.53% for 2026, line 1177)
- ✅ Tax Rates: Already correct (26.375% effective rate)
- ✅ Sparer-Pauschbetrag: Already correct (1,000€/2,000€)

**Content:**

- ✅ H1: Update "2025" to "2026" (line 5062)
- ✅ Meta tags: Already "2026"
- ✅ Educational sections: Review for "2025" → "2026" updates
- ✅ FAQs: Review and update year references (~15 FAQs)

**Priority:** 🟡 MEDIUM (H1 update needed, Basiszins verification needed)

### Throughout 2026 Updates

**Scheduled Updates:**

- **Basiszins:** Update annually (typically January, set by BMF)
- **Tax Rates:** Monitor for changes (typically stable)

### Monitoring Requirements

- **Bundesfinanzministerium (BMF):** Check for Basiszins updates (annual)
- **Frequency:** Annually (January) or when tax laws change
- **Source:** Official BMF announcements

## Testing

### Test Cases

**Normal Cases:**

- Test 1: 10,000€ initial, 200€/month, 6% rate, 20 years → Expected: ~125,510€ final value
- Test 2: Monthly contributions → Expected: Correct monthly calculation
- Test 3: With tax → Expected: Correct tax deduction
- Test 4: ETF mode → Expected: Vorabpauschale calculation
- Test 5: Reverse calculation - time → Expected: Correct years needed
- Test 6: Reverse calculation - rate → Expected: Correct rate needed
- Test 7: Reverse calculation - deposit → Expected: Correct deposit needed

**Edge Cases:**

- Edge case 1: Zero interest → Expected: Simple addition
- Edge case 2: Negative interest → Expected: Value decreases
- Edge case 3: High inflation → Expected: Negative real return
- Edge case 4: Tax-free → Expected: No tax deduction
- Edge case 5: Very long duration → Expected: Correct calculation
- Edge case 6: One-time payment → Expected: Correct mid-period addition

### Browser Testing

- Chrome: ✅ Tested, working
- Firefox: ✅ Tested, working
- Safari: ✅ Tested, working
- Mobile: ✅ Tested, working

### Export Testing

- PDF: ✅ Functional (jsPDF + html2canvas)
- CSV: ✅ Functional (native JavaScript)
- SVG: ✅ Functional (ApexCharts)
- PNG: ✅ Functional (ApexCharts)

## Content Structure

### Hero Section

- **H1 Title:** To be documented
- **Meta Description:** Kostenloser Zinseszinsrechner mit deutscher Steuerberechnung. Berechne ETF-Sparplan, Kredite & Anlag

### FAQs

- **Total FAQs:** 7
- Q: Was sind Zinsen mehr nur bei 300.000 € wert?...
- Q: Welche Bank hat die niedrigsten Zinsen für einen Kredit?...
- Q: Wie berechnet man Zinseszins mit ETF Sparplan?...

## Maintenance Notes

### Known Issues

- Inline JavaScript makes updates more difficult (consider extraction)
- H1 updated to "2026"
- Basiszins shows 2026 value (needs verification for 2026)

### Future Improvements

- Extract JavaScript to separate file for easier maintenance
- Add more visualization options
- Add comparison mode improvements
- Add more reverse calculation types
- Add loan-specific calculations

### Related Tools

**Complementary Tools:**

- **[Prozentrechner](prozentrechner-documentation.md)** - Calculate percentages

  - Use together when: Need percentage calculations for growth rates
  - Example workflow: Calculate percentage growth → Calculate compound interest → Investment planning

- **[Einkommensteuer-Rechner](einkommensteuer-rechner-documentation.md)** - Calculate income tax

  - Use together when: Need comprehensive tax planning including investment income
  - Example workflow: Calculate investment returns → Calculate income tax → Total tax planning

- **[Brutto-Netto-Rechner](brutto-netto-rechner-documentation.md)** - Calculate gross-to-net salary
  - Use together when: Need to calculate available income for investments
  - Example workflow: Calculate net income → Plan investment deposits → Calculate returns

**Sequential Tools:**

- **[Kostenrechner](kostenrechner-documentation.md)** - Calculate costs
  - Use after: Calculating investment returns
  - Use before: Overall financial planning

## Test Coverage

### Automated Testing

The Zinseszinsrechner includes comprehensive automated test coverage via `v2/scripts/dev-helpers/test-zinseszins-calculations.js`.

**Test Suite Overview:**
- **Total Test Cases:** 35
- **Coverage Areas:**
  - Basic Compound Interest Calculations (10 tests)
  - Tax Calculation Tests (15 tests)
  - Advanced Features Tests (4 tests)
  - Edge Cases (6 tests)

**Running Tests:**
```bash
node v2/scripts/dev-helpers/test-zinseszins-calculations.js
```

**Test Results:** All 35 tests pass (100% pass rate)

**Key Test Scenarios:**
- Simple compound interest calculations (initial capital only)
- Monthly deposits with different compounding frequencies
- Payment timing (beginning vs end of month)
- Zero and negative interest rates
- Tax calculations (simple mode with/without allowance, church tax)
- ETF Vorabpauschale calculations with 2026 Basiszins (3.20%)
- Teilfreistellung application (30% equity, 15% mixed)
- Inflation adjustments
- Fee calculations
- Edge cases (zero values, very large values, boundary conditions)

**Test Constants Verified:**
- Basiszins 2026: 3.20% ✅
- Abgeltungsteuer: 25% ✅
- Solidaritätszuschlag: 5.5% ✅
- Sparerpauschbetrag: 1,000€ (single), 2,000€ (joint) ✅
- Teilfreistellung: 30% (equity), 15% (mixed) ✅

## References

### Official Sources

- **Bundesfinanzministerium (BMF):** Basiszins, tax rates
- **Investmentsteuergesetz:** ETF Vorabpauschale rules
- **Kapitalertragssteuer:** German capital gains tax law

### Documentation Files

- `BROWSER_TESTING_FRAMEWORK.md`: Browser testing guidelines
- `CODE_ANALYSIS_FRAMEWORK.md`: Code analysis guidelines
- `TOOL_DOCUMENTATION_TEMPLATE.md`: Documentation template
