diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 0000000000000000000000000000000000000000..b68cdab27d2952a4c27d757dab090537bbb0767a --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,46 @@ +# Configuration file for the Sphinx documentation builder. +# +# For the full list of built-in configuration values, see the documentation: +# https://www.sphinx-doc.org/en/master/usage/configuration.html + +import os +import sys + +sys.path.insert(0, os.path.abspath("..")) + +# -- Project information ----------------------------------------------------- +# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information + +project = "netto" +copyright = "2025, Martin Klein" +author = "Martin Klein" +release = "0.2.0" + +# -- General configuration --------------------------------------------------- +# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration + +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.coverage", + "sphinx.ext.viewcode", + "sphinx.ext.napoleon", + "myst_parser", + "autoapi.extension", +] + +templates_path = ["_templates"] +exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] + +source_suffix = { + ".rst": "restructuredtext", + ".txt": "markdown", + ".md": "markdown", +} + +# -- Options for HTML output ------------------------------------------------- +# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output + +html_theme = "sphinx_rtd_theme" +html_static_path = ["_static"] + +autoapi_dirs = ["../netto"] diff --git a/examples/examples.py b/examples/examples.py new file mode 100644 index 0000000000000000000000000000000000000000..fd6b8df369bf501747bcab432b6a1c04fb1f18ef --- /dev/null +++ b/examples/examples.py @@ -0,0 +1,72 @@ +from netto import TaxConfig, calc_inverse_netto, calc_netto + +# ============================================================================ +# Basic Usage (using default configuration) +# ============================================================================ + +# Calculate net income for a salary of 50,000 with no additional deductibles +calc_netto(50000) + +# Calculate net income for a salary of 50,000 with additional deductibles of 10,000 +calc_netto(50000, deductibles=10000) + +# Calculate net income for a salary of 50,000 and print additional information +calc_netto(50000, deductibles=10000, verbose=True) + +# Calculate gross salary needed to reach a net income of 50,000 with no additional deductibles +calc_inverse_netto(50000) + +# Calculate gross salary needed to reach a net income of 50,000 with additional deductibles of 5,000 +calc_inverse_netto(50000, deductibles=5000) + + +# ============================================================================ +# Advanced Usage (using custom configuration) +# ============================================================================ + +# Create a custom configuration for a married person with children in 2025 +config_2025_married = TaxConfig( + year=2025, + is_married=True, + has_children=True, + church_tax=0.0, # No church tax + extra_health_insurance=0.015, # Slightly higher health insurance +) + +# Calculate with custom configuration +net_income = calc_netto(60000, config=config_2025_married) +print(f"Net income for married person with children in 2025: {net_income}") + +# Calculate inverse with custom configuration +gross_needed = calc_inverse_netto(45000, config=config_2025_married) +print(f"Gross salary needed to reach 45,000 net: {gross_needed}") + + +# Create a configuration for a single person without church tax in 2024 +config_2024_single = TaxConfig( + year=2024, is_married=False, has_children=False, church_tax=0.0 +) + +# Calculate with different configuration +net_income_single = calc_netto(50000, config=config_2024_single, verbose=True) + + +# Multiple scenarios comparison +scenarios = [ + ("Single, 2024, no church tax", TaxConfig(year=2024, church_tax=0.0)), + ( + "Married, 2024, with church tax", + TaxConfig(year=2024, is_married=True, church_tax=0.09), + ), + ( + "Single with children, 2025", + TaxConfig(year=2025, has_children=True, church_tax=0.0), + ), +] + +salary = 70000 +print(f"\nComparison for {salary} EUR gross salary:") +print("-" * 60) +for description, config in scenarios: + net = calc_netto(salary, config=config) + print(f"{description:40} -> {net:10.2f} EUR") diff --git a/netto/__init__.py b/netto/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b532b42d0994ccb47b57a510c72f85b5bf9444aa --- /dev/null +++ b/netto/__init__.py @@ -0,0 +1,59 @@ +from netto.config import TaxConfig +from netto.main import calc_inverse_netto, calc_netto +from netto.social_security import ( + calc_deductible_social_security, + calc_insurance_health, + calc_insurance_nursing, + calc_insurance_pension, + calc_insurance_unemployment, + calc_social_security, + calc_social_security_by_integration, + get_rate_health, + get_rate_nursing, + get_rate_pension, + get_rate_unemployment, +) +from netto.taxes_children import ( + apply_guenstigerpruefung, + calc_child_allowance_per_child, + calc_kindergeld, +) +from netto.taxes_income import ( + calc_income_tax, + calc_income_tax_by_integration, + calc_taxable_income, + get_marginal_tax_rate, +) +from netto.taxes_other import calc_church_tax, calc_soli + +__all__ = [ + # Main API + "calc_netto", + "calc_inverse_netto", + # Configuration + "TaxConfig", + # Social Security + "calc_social_security", + "calc_deductible_social_security", + "calc_social_security_by_integration", + "calc_insurance_pension", + "calc_insurance_health", + "calc_insurance_nursing", + "calc_insurance_unemployment", + "get_rate_pension", + "get_rate_health", + "get_rate_nursing", + "get_rate_unemployment", + # Income Tax + "calc_income_tax", + "calc_income_tax_by_integration", + "calc_taxable_income", + "get_marginal_tax_rate", + # Other Taxes + "calc_soli", + "calc_church_tax", + # Child Benefits + "calc_kindergeld", + "calc_child_allowance_per_child", + "apply_guenstigerpruefung", +] diff --git a/netto/config.py b/netto/config.py new file mode 100644 index 0000000000000000000000000000000000000000..d5747ed79b8d3f4c11434256988909bf36cf3d53 --- /dev/null +++ b/netto/config.py @@ -0,0 +1,73 @@ +from dataclasses import dataclass + + +@dataclass(slots=True) +class TaxConfig: + """ + Configuration for tax and social security calculations. + + Parameters + ---------- + year : int + Tax year (2018-2032, default: 2025). Years 2018-2025 use enacted + law, 2026 uses preliminary official data, 2027-2032 are forecasts + (see data/README.md for assumptions). + has_children : bool + Has (or ever had) children - removes the childless surcharge on + nursing insurance. Automatically set to True if num_children > 0. + num_children : int + Number of children entitled to Kindergeld / child allowances. + When > 0, calc_netto includes Kindergeld in the result and applies + the Günstigerprüfung (Kindergeld vs. Kinderfreibetrag). + is_married : bool + Married status (doubles tax brackets) + extra_health_insurance : float or None + Total health insurance Zusatzbeitrag (e.g. 0.029 for 2.9%; the + employee pays half). Defaults to None, which uses the official + year-specific average rate from the data files. Set explicitly to + match your Krankenkasse. + church_tax : float + Church tax rate (set to 0.0 for none) + + Examples + -------- + >>> TaxConfig() + >>> TaxConfig(year=2025, is_married=True, has_children=True) + >>> TaxConfig(year=2026, is_married=True, num_children=2) + >>> TaxConfig(church_tax=0.0) + >>> TaxConfig(extra_health_insurance=0.019) # cheap Krankenkasse + """ + + year: int = 2025 + has_children: bool = False + num_children: int = 0 + is_married: bool = False + extra_health_insurance: float | None = None + church_tax: float = 0.09 + + def __post_init__(self): + """Validate configuration values.""" + if not isinstance(self.year, int): + raise TypeError(f"year must be int, got {type(self.year)}") + if self.year < 2018 or self.year > 2032: + raise ValueError(f"year must be between 2018 and 2032, got {self.year}") + if not isinstance(self.has_children, bool): + raise TypeError(f"has_children must be bool, got {type(self.has_children)}") + if not isinstance(self.num_children, int) or isinstance( + self.num_children, bool + ): + raise TypeError(f"num_children must be int, got {type(self.num_children)}") + if self.num_children < 0: + raise ValueError( + f"num_children must be non-negative, got {self.num_children}" + ) + if self.num_children > 0: + self.has_children = True + if not isinstance(self.is_married, bool): + raise TypeError(f"is_married must be bool, got {type(self.is_married)}") + if self.extra_health_insurance is not None and self.extra_health_insurance < 0: + raise ValueError( + f"extra_health_insurance must be non-negative, got {self.extra_health_insurance}" + ) + if self.church_tax < 0: + raise ValueError(f"church_tax must be non-negative, got {self.church_tax}") diff --git a/netto/data_loader.py b/netto/data_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..7c5df4d54642e60e1eb9eabaa195e6770ffc1d9a --- /dev/null +++ b/netto/data_loader.py @@ -0,0 +1,427 @@ +""" +Data loader for tax and social security data. + +This module loads tax data from JSON files and provides validation +using Pydantic models. All data is organized in individual yearly files +for better maintainability and auditability. + +The loaded data is exposed as module-level variables for easy import: +- tax_curve: Tax brackets by year +- social_security_curve: Social security rates by year +- soli_curve: Solidarity tax parameters by year +- correction_factor_pensions: Pension deduction factors by year +- deductions: Lump-sum deductions (Pauschbeträge) by year +- child_benefits: Kindergeld and Kinderfreibetrag by year +""" + +import json +from pathlib import Path + +from pydantic import BaseModel, Field, field_validator + +DATA_DIR = Path(__file__).parent.parent / "data" + + +class TaxBracket(BaseModel): + step: float = Field(gt=0, description="Income threshold for this bracket") + rate: float = Field(ge=0, le=1, description="Tax rate for this bracket") + const: list[float] | None = Field( + default=None, description="Polynomial coefficients" + ) + + @field_validator("const") + @classmethod + def validate_const_length(cls, v, info): + if v is not None and len(v) == 0: + raise ValueError("const array cannot be empty") + return v + + +class TaxCurve(BaseModel): + year: int = Field(ge=2018, le=2035, description="Tax year") + brackets: dict[str, TaxBracket] = Field(description="Tax brackets (0-3)") + + @field_validator("brackets") + @classmethod + def validate_brackets(cls, v): + if set(v.keys()) != {"0", "1", "2", "3"}: + raise ValueError("Tax curve must have exactly 4 brackets (0-3)") + return v + + +class SocialSecurityEntry(BaseModel): + limit: float = Field(gt=0, description="Income limit for this contribution") + rate: float = Field(ge=0, le=1, description="Contribution rate") + extra: float | None = Field( + default=None, + ge=0, + le=1, + description="Extra rate (average Zusatzbeitrag for health, " + "childless surcharge for nursing)", + ) + + +class SocialSecurity(BaseModel): + year: int = Field(ge=2018, le=2035, description="Tax year") + pension: SocialSecurityEntry + unemployment: SocialSecurityEntry + health: SocialSecurityEntry + nursing: SocialSecurityEntry + + +class SoliCurve(BaseModel): + year: int = Field(ge=2018, le=2035, description="Tax year") + start_taxable_income: float = Field( + gt=0, description="Income threshold where soli starts" + ) + start_fraction: float = Field( + ge=0, le=1, description="Starting fraction for progressive phase-in" + ) + end_rate: float = Field(ge=0, le=1, description="Maximum soli rate") + + +class PensionFactor(BaseModel): + year: int = Field(ge=2018, le=2035, description="Tax year") + factor: float = Field(ge=0, le=1, description="Pension deduction factor") + + +class Deductions(BaseModel): + year: int = Field(ge=2018, le=2035, description="Tax year") + werbungskosten_pauschbetrag: float = Field( + ge=0, description="Employee lump-sum deduction (Arbeitnehmer-Pauschbetrag)" + ) + sonderausgaben_pauschbetrag: float = Field( + ge=0, description="Special expenses lump sum per person" + ) + + +class ChildBenefits(BaseModel): + year: int = Field(ge=2018, le=2035, description="Tax year") + kindergeld_per_child: float = Field( + ge=0, description="Yearly Kindergeld per child (first/second child rate)" + ) + kinderfreibetrag_per_child: float = Field( + ge=0, + description="Yearly child allowance per child incl. BEA, both parents", + ) + + +def load_tax_curve(year: int) -> dict[int, dict]: + """ + Load tax curve for a specific year. + + Parameters + ---------- + year : int + Tax year to load + + Returns + ------- + dict + Tax curve data as dictionary with integer keys (0-3) + + Examples + -------- + >>> curve = load_tax_curve(2022) + >>> curve[0]['step'] + 10347 + """ + file_path = DATA_DIR / "tax_curves" / f"{year}.json" + + if not file_path.exists(): + raise FileNotFoundError(f"Tax curve data not found for year {year}") + + with open(file_path) as f: + data = json.load(f) + + tax_curve = TaxCurve(**data) + + # Convert string keys to integers for backward compatibility + return {int(k): v.model_dump() for k, v in tax_curve.brackets.items()} + + +def load_social_security(year: int) -> dict: + """ + Load social security data for a specific year. + + Parameters + ---------- + year : int + Tax year to load + + Returns + ------- + dict + Social security data + + Examples + -------- + >>> social_sec = load_social_security(2022) + >>> social_sec['pension']['limit'] + 84600 + """ + file_path = DATA_DIR / "social_security" / f"{year}.json" + + if not file_path.exists(): + if year >= 2033: + raise NotImplementedError( + f"Social security data not yet available for {year}" + ) + raise FileNotFoundError(f"Social security data not found for year {year}") + + with open(file_path) as f: + data = json.load(f) + + social_security = SocialSecurity(**data) + + return social_security.model_dump(exclude={"year"}) + + +def load_soli(year: int) -> dict: + """ + Load solidarity tax data for a specific year. + + Parameters + ---------- + year : int + Tax year to load + + Returns + ------- + dict + Soli data + + Examples + -------- + >>> soli = load_soli(2022) + >>> soli['end_rate'] + 0.055 + """ + file_path = DATA_DIR / "soli" / f"{year}.json" + + if not file_path.exists(): + raise FileNotFoundError(f"Soli data not found for year {year}") + + with open(file_path) as f: + data = json.load(f) + + soli_curve = SoliCurve(**data) + + return soli_curve.model_dump(exclude={"year"}) + + +def load_pension_factor(year: int) -> float: + """ + Load pension correction factor for a specific year. + + Parameters + ---------- + year : int + Tax year to load + + Returns + ------- + float + Pension correction factor + + Examples + -------- + >>> factor = load_pension_factor(2022) + >>> factor + 0.88 + """ + file_path = DATA_DIR / "pension_factors" / f"{year}.json" + + if not file_path.exists(): + raise FileNotFoundError(f"Pension factor not found for year {year}") + + with open(file_path) as f: + data = json.load(f) + + pension_factor = PensionFactor(**data) + + return pension_factor.factor + + +def load_deductions(year: int) -> dict: + """ + Load lump-sum deductions (Pauschbeträge) for a specific year. + + Parameters + ---------- + year : int + Tax year to load + + Returns + ------- + dict + Deductions data + + Examples + -------- + >>> deductions = load_deductions(2022) + >>> deductions['werbungskosten_pauschbetrag'] + 1200.0 + """ + file_path = DATA_DIR / "deductions" / f"{year}.json" + + if not file_path.exists(): + raise FileNotFoundError(f"Deductions data not found for year {year}") + + with open(file_path) as f: + data = json.load(f) + + deductions_data = Deductions(**data) + + return deductions_data.model_dump(exclude={"year"}) + + +def load_child_benefits(year: int) -> dict: + """ + Load child benefits data (Kindergeld, Kinderfreibetrag) for a specific year. + + Parameters + ---------- + year : int + Tax year to load + + Returns + ------- + dict + Child benefits data + + Examples + -------- + >>> benefits = load_child_benefits(2026) + >>> benefits['kindergeld_per_child'] + 3108.0 + """ + file_path = DATA_DIR / "children" / f"{year}.json" + + if not file_path.exists(): + raise FileNotFoundError(f"Child benefits data not found for year {year}") + + with open(file_path) as f: + data = json.load(f) + + child_benefits_data = ChildBenefits(**data) + + return child_benefits_data.model_dump(exclude={"year"}) + + +def load_all_tax_curves() -> dict[int, dict[int, dict]]: + """ + Load tax curves for all available years. + + Returns + ------- + dict + Tax curves for all years + """ + tax_curves = {} + for year in range(2018, 2033): # 2018-2032 + try: + tax_curves[year] = load_tax_curve(year) + except FileNotFoundError: + pass + return tax_curves + + +def load_all_social_security() -> dict[int, dict]: + """ + Load social security data for all available years. + + Returns + ------- + dict + Social security data for all years + """ + social_security = {} + for year in range(2018, 2033): # 2018-2032 + try: + social_security[year] = load_social_security(year) + except (FileNotFoundError, NotImplementedError): + pass + + return social_security + + +def load_all_soli() -> dict[int, dict]: + """ + Load solidarity tax data for all available years. + + Returns + ------- + dict + Soli data for all years + """ + soli_data = {} + for year in range(2018, 2033): # 2018-2032 + try: + soli_data[year] = load_soli(year) + except FileNotFoundError: + pass + return soli_data + + +def load_all_pension_factors() -> dict[int, float]: + """ + Load pension correction factors for all available years. + + Returns + ------- + dict + Pension correction factors for all years + """ + pension_factors = {} + for year in range(2018, 2033): # 2018-2032 + try: + pension_factors[year] = load_pension_factor(year) + except FileNotFoundError: + pass + return pension_factors + + +def load_all_deductions() -> dict[int, dict]: + """ + Load lump-sum deductions for all available years. + + Returns + ------- + dict + Deductions data for all years + """ + deductions_data = {} + for year in range(2018, 2033): # 2018-2032 + try: + deductions_data[year] = load_deductions(year) + except FileNotFoundError: + pass + return deductions_data + + +def load_all_child_benefits() -> dict[int, dict]: + """ + Load child benefits data for all available years. + + Returns + ------- + dict + Child benefits data for all years + """ + child_benefits_data = {} + for year in range(2018, 2033): # 2018-2032 + try: + child_benefits_data[year] = load_child_benefits(year) + except FileNotFoundError: + pass + return child_benefits_data + + +# Load all data at module import time and expose as module-level variables +tax_curve = load_all_tax_curves() +social_security_curve = load_all_social_security() +soli_curve = load_all_soli() +correction_factor_pensions = load_all_pension_factors() +deductions = load_all_deductions() +child_benefits = load_all_child_benefits() diff --git a/netto/main.py b/netto/main.py new file mode 100644 index 0000000000000000000000000000000000000000..8d1aed3e3a6997d8696aadffb8125d75b240556f --- /dev/null +++ b/netto/main.py @@ -0,0 +1,177 @@ +from scipy.optimize import newton + +from netto.config import TaxConfig +from netto.social_security import calc_deductible_social_security, calc_social_security +from netto.taxes_children import apply_guenstigerpruefung, calc_kindergeld +from netto.taxes_income import calc_income_tax_by_integration, calc_taxable_income +from netto.taxes_other import calc_church_tax, calc_soli + + +def calc_netto( + salary: float, + deductibles: float = 0, + verbose: bool = False, + config: TaxConfig | None = None, + partner_salary: float = 0, +) -> float: + """ + Calculate net income from gross salary. + + For dual-income married couples, pass the spouse's salary as + ``partner_salary``. Income tax is then assessed jointly + (Ehegattensplitting) while social security contributions are calculated + per person against the individual contribution ceilings. The returned + value is the combined household net income. + + With ``num_children`` set in the config, the result includes the yearly + Kindergeld and applies the Günstigerprüfung: if the Kinderfreibetrag + yields more tax relief than the Kindergeld, the allowance is deducted + and the Kindergeld added back to the tax (§ 31 EStG). Solidarity + surcharge and church tax are always based on the income tax with child + allowances deducted. + + Parameters + ---------- + salary: float + Yearly gross salary + deductibles: float, optional + Additional deductibles that reduce taxable income + verbose: bool, optional + Print detailed calculation breakdown + config : TaxConfig, optional + Tax configuration (uses defaults if not provided) + partner_salary: float, optional + Yearly gross salary of the spouse (requires is_married=True). + Default is 0 (single-earner household). + + Returns + ------- + float + Net income (household net income if partner_salary is given; + includes Kindergeld if num_children is set) + + Examples + -------- + >>> calc_netto(50000) + >>> calc_netto(50000, deductibles=10000) + >>> calc_netto(50000, verbose=True) + >>> config = TaxConfig(year=2025, is_married=True) + >>> calc_netto(50000, config=config) + >>> calc_netto(50000, config=config, partner_salary=40000) + """ + if config is None: + config = TaxConfig() + if partner_salary < 0: + raise ValueError(f"partner_salary must be non-negative, got {partner_salary}") + if partner_salary > 0 and not config.is_married: + raise ValueError( + "partner_salary requires is_married=True, as only jointly " + "assessed couples are taxed on their combined income" + ) + + deductible_social_security = calc_deductible_social_security(salary, config) + social_security = calc_social_security(salary, config) + if partner_salary > 0: + deductible_social_security += calc_deductible_social_security( + partner_salary, config + ) + social_security += calc_social_security(partner_salary, config) + taxable_income = calc_taxable_income( + salary=salary, + deductible_social_security=deductible_social_security, + deductibles_other=deductibles, + config=config, + partner_salary=partner_salary, + ) + income_tax = calc_income_tax_by_integration(taxable_income, config) + kindergeld = calc_kindergeld(config) + income_tax, fictitious_tax = apply_guenstigerpruefung( + taxable_income, income_tax, config + ) + soli = calc_soli(fictitious_tax, config) + church_tax = calc_church_tax(fictitious_tax, config) + if verbose: + repr = ( + "Yearly Evaluation:\n" + + f"Income Tax: {round(income_tax, 2):>12}\n" + + f"Soli: {round(soli, 2):>12}\n" + + f"Church Tax: {round(church_tax, 2):>12}\n" + + f"Social Security: {round(social_security, 2):>12}" + ) + if config.num_children > 0: + repr += f"\nKindergeld: {round(kindergeld, 2):>12}" + print(repr) + return round( + salary + + partner_salary + + kindergeld + - income_tax + - soli + - church_tax + - social_security, + 2, + ) + + +def calc_inverse_netto( + desired_netto: float, + deductibles: float = 0, + config: TaxConfig | None = None, + partner_salary: float = 0, +) -> float: + """ + Calculate required gross salary to reach desired net income. + + If ``partner_salary`` is given, it is kept fixed and the primary salary + required to reach the desired household net income is calculated. + + Parameters + ---------- + desired_netto: float + Desired net income + deductibles: float, optional + Additional deductibles that reduce taxable income + config : TaxConfig, optional + Tax configuration (uses defaults if not provided) + partner_salary: float, optional + Fixed yearly gross salary of the spouse (requires is_married=True) + + Returns + ------- + float + Required gross salary + + Examples + -------- + >>> calc_inverse_netto(50000) + >>> calc_inverse_netto(50000, deductibles=5000) + >>> config = TaxConfig(year=2025, is_married=True) + >>> calc_inverse_netto(50000, config=config) + >>> calc_inverse_netto(70000, config=config, partner_salary=40000) + """ + if config is None: + config = TaxConfig() + + if partner_salary > 0: + netto_without_primary = calc_netto( + 0, deductibles=deductibles, config=config, partner_salary=partner_salary + ) + if desired_netto <= netto_without_primary: + raise ValueError( + f"desired_netto {desired_netto} is already reached by the " + f"partner salary alone (household netto without primary " + f"salary: {netto_without_primary})" + ) + + def f(salary): + return ( + calc_netto( + salary, + deductibles=deductibles, + config=config, + partner_salary=partner_salary, + ) + - desired_netto + ) + + return round(newton(f, x0=max(desired_netto - partner_salary, 1)), 0) diff --git a/netto/social_security.py b/netto/social_security.py new file mode 100644 index 0000000000000000000000000000000000000000..1f99aa4ce8c2d14bcf20b2d1cdff5037a5f5cf11 --- /dev/null +++ b/netto/social_security.py @@ -0,0 +1,138 @@ +import math + +from scipy.integrate import quad + +from netto.config import TaxConfig +from netto.data_loader import correction_factor_pensions, social_security_curve + + +def get_rate_pension(salary: float, config: TaxConfig | None = None) -> float: + return __get_rate(salary, "pension", config=config) + + +def __get_extra_health_insurance(config: TaxConfig) -> float: + """Total Zusatzbeitrag: explicit config value, or the official + year-specific average from the data files if the config leaves it None.""" + if config.extra_health_insurance is not None: + return config.extra_health_insurance + return social_security_curve[config.year]["health"]["extra"] + + +def __get_rate( + salary: float, type: str, extra: float = 0, config: TaxConfig | None = None +) -> float: + if config is None: + config = TaxConfig() + return ( + social_security_curve[config.year][type]["rate"] + extra + if 0 < salary <= social_security_curve[config.year][type]["limit"] + else 0 + ) + + +def get_rate_unemployment(salary: float, config: TaxConfig | None = None) -> float: + return __get_rate(salary, "unemployment", config=config) + + +def get_rate_health(salary: float, config: TaxConfig | None = None) -> float: + if config is None: + config = TaxConfig() + extra = __get_extra_health_insurance(config) / 2 + return __get_rate(salary, "health", extra, config=config) + + +def get_rate_nursing(salary: float, config: TaxConfig | None = None) -> float: + if config is None: + config = TaxConfig() + extra = ( + 0 + if config.has_children + else social_security_curve[config.year]["nursing"]["extra"] + ) + return __get_rate(salary, "nursing", extra, config=config) + + +def calc_insurance_pension(salary: float, config: TaxConfig | None = None) -> float: + return __get_value(salary, "pension", config=config) + + +def __get_value( + salary: float, type: str, extra: float = 0, config: TaxConfig | None = None +) -> float: + if config is None: + config = TaxConfig() + return min( + salary * (social_security_curve[config.year][type]["rate"] + extra), + social_security_curve[config.year][type]["limit"] + * (social_security_curve[config.year][type]["rate"] + extra), + ) + + +def calc_insurance_unemployment( + salary: float, config: TaxConfig | None = None +) -> float: + return __get_value(salary, "unemployment", config=config) + + +def calc_insurance_health(salary: float, config: TaxConfig | None = None) -> float: + if config is None: + config = TaxConfig() + extra = __get_extra_health_insurance(config) / 2 + return __get_value(salary, "health", extra, config=config) + + +def calc_insurance_health_deductable( + salary: float, config: TaxConfig | None = None +) -> float: + if config is None: + config = TaxConfig() + extra = __get_extra_health_insurance(config) / 2 + return __get_value(salary, "health", extra - 0.003, config=config) + + +def calc_insurance_nursing(salary: float, config: TaxConfig | None = None) -> float: + if config is None: + config = TaxConfig() + extra = ( + 0 + if config.has_children + else social_security_curve[config.year]["nursing"]["extra"] + ) + return __get_value(salary, "nursing", extra, config=config) + + +def calc_deductible_social_security( + salary: float, config: TaxConfig | None = None +) -> float: + if config is None: + config = TaxConfig() + return ( + math.ceil( + calc_insurance_pension(salary, config) + * correction_factor_pensions[config.year] + ) + + math.ceil(calc_insurance_health_deductable(salary, config)) + + math.ceil(calc_insurance_nursing(salary, config)) + ) + + +def calc_social_security(salary: float, config: TaxConfig | None = None) -> float: + return round( + calc_insurance_pension(salary, config) + + calc_insurance_health(salary, config) + + calc_insurance_nursing(salary, config) + + calc_insurance_unemployment(salary, config), + 2, + ) + + +def calc_social_security_by_integration( + salary: float, config: TaxConfig | None = None +) -> float: + if config is None: + config = TaxConfig() + pension, _ = quad(lambda s: get_rate_pension(s, config), 0, salary) + health, _ = quad(lambda s: get_rate_health(s, config), 0, salary) + nursing, _ = quad(lambda s: get_rate_nursing(s, config), 0, salary) + unemployment, _ = quad(lambda s: get_rate_unemployment(s, config), 0, salary) + return round(pension + health + nursing + unemployment, 2) diff --git a/netto/taxes_children.py b/netto/taxes_children.py new file mode 100644 index 0000000000000000000000000000000000000000..e5b17de250404a071e3fc0dfec0b61435585089b --- /dev/null +++ b/netto/taxes_children.py @@ -0,0 +1,120 @@ +from netto.config import TaxConfig +from netto.data_loader import child_benefits as CHILD_BENEFITS_DATA +from netto.taxes_income import calc_income_tax_by_integration + + +def calc_kindergeld(config: TaxConfig | None = None) -> float: + """ + Calculate the yearly Kindergeld for all children in the configuration. + + Uses the first/second-child rate for every child (before 2023 the third + and further children received slightly more; one-off Corona bonuses are + not included). + + Parameters + ---------- + config : TaxConfig, optional + Tax configuration (uses default if not provided) + + Returns + ------- + float + Total yearly Kindergeld + + Examples + -------- + >>> calc_kindergeld(TaxConfig(year=2026, num_children=2)) + 6216.0 + """ + if config is None: + config = TaxConfig() + + return ( + CHILD_BENEFITS_DATA[config.year]["kindergeld_per_child"] * config.num_children + ) + + +def calc_child_allowance_per_child(config: TaxConfig | None = None) -> float: + """ + Yearly child allowance (Kinderfreibetrag incl. BEA) per child. + + Married couples under joint assessment receive the full allowance; a + single parent receives half (the other half belongs to the other + parent). The Übertragung of the other parent's half is not modeled. + + Parameters + ---------- + config : TaxConfig, optional + Tax configuration (uses default if not provided) + + Returns + ------- + float + Yearly child allowance per child + """ + if config is None: + config = TaxConfig() + + full = CHILD_BENEFITS_DATA[config.year]["kinderfreibetrag_per_child"] + return full if config.is_married else full / 2 + + +def apply_guenstigerpruefung( + taxable_income: float, income_tax: float, config: TaxConfig | None = None +) -> tuple[float, float]: + """ + Apply the per-child Günstigerprüfung (Kindergeld vs. Kinderfreibetrag). + + For each child (checked sequentially against a taxable income already + reduced by the previous children's allowances), the tax relief of the + child allowance is compared with the Kindergeld entitlement. If the + relief is larger, the allowance is deducted and the Kindergeld is added + back to the tax liability (Hinzurechnung, § 31 EStG) - so together with + the Kindergeld paid out, the family keeps the full allowance benefit. + + Solidarity surcharge and church tax are always based on the fictitious + income tax with ALL child allowances deducted (§ 3 SolzG, § 51a EStG), + regardless of the Günstigerprüfung outcome. + + Parameters + ---------- + taxable_income : float + Taxable income before child allowances + income_tax : float + Income tax on taxable_income (before child allowances) + config : TaxConfig, optional + Tax configuration (uses default if not provided) + + Returns + ------- + tuple[float, float] + (assessed income tax after the Günstigerprüfung including the + Kindergeld Hinzurechnung, fictitious income tax with all child + allowances deducted - the base for soli and church tax) + """ + if config is None: + config = TaxConfig() + + if config.num_children == 0: + return income_tax, income_tax + + allowance = calc_child_allowance_per_child(config) + # A single parent claims half the allowance, so only half the + # Kindergeld is counted against it (§ 31 S. 4 EStG). + kindergeld_per_child = CHILD_BENEFITS_DATA[config.year]["kindergeld_per_child"] * ( + 1 if config.is_married else 0.5 + ) + + assessed_tax = income_tax + remaining_income = taxable_income + tax_before_child = income_tax + for _ in range(config.num_children): + remaining_income = max(0, remaining_income - allowance) + tax_after_child = calc_income_tax_by_integration(remaining_income, config) + relief = tax_before_child - tax_after_child + if relief > kindergeld_per_child: + assessed_tax += kindergeld_per_child - relief + tax_before_child = tax_after_child + + fictitious_tax = tax_before_child + return assessed_tax, fictitious_tax diff --git a/netto/taxes_income.py b/netto/taxes_income.py new file mode 100644 index 0000000000000000000000000000000000000000..3254d3eb29c4e8782c2eec5fb31279b4e8875ff7 --- /dev/null +++ b/netto/taxes_income.py @@ -0,0 +1,220 @@ +import math +from dataclasses import replace + +from scipy.integrate import quad + +from netto.config import TaxConfig +from netto.data_loader import deductions as DEDUCTIONS_DATA +from netto.data_loader import tax_curve as TAX_CURVE_DATA + + +def get_marginal_tax_rate( + taxable_income: float, config: TaxConfig | None = None +) -> float: + """ + Calculate the marginal tax rate for a given taxable income. + + Parameters + ---------- + taxable_income: float or int + The taxable income for which the marginal tax rate should be calculated. + config : TaxConfig, optional + Tax configuration (uses default if not provided) + + Returns + ------- + marginal_tax_rate: float + The marginal tax rate for the given taxable income. + + Examples + -------- + # Calculate marginal tax rate for a taxable income of 10000 + get_marginal_tax_rate(10000) + """ + if config is None: + config = TaxConfig() + + # Married couples (Ehegattensplitting): stretching the bracket boundaries + # by 2 makes the marginal rate curve equivalent to 2 * tax(income / 2) + splitting_factor = 2 if config.is_married else 1 + tax_curve = { + bracket: { + "step": data["step"] * splitting_factor, + "rate": data["rate"], + } + for bracket, data in TAX_CURVE_DATA[config.year].items() + } + if taxable_income < tax_curve[0]["step"]: + return 0 + elif taxable_income <= tax_curve[1]["step"]: + return __calc_gradient( + tax_curve[0]["step"], + tax_curve[1]["step"], + tax_curve[0]["rate"], + tax_curve[1]["rate"], + taxable_income, + ) + elif taxable_income <= tax_curve[2]["step"]: + return __calc_gradient( + tax_curve[1]["step"], + tax_curve[2]["step"], + tax_curve[1]["rate"], + tax_curve[2]["rate"], + taxable_income, + ) + elif taxable_income < tax_curve[3]["step"]: + return tax_curve[2]["rate"] + else: + return tax_curve[3]["rate"] + + +def __calc_gradient(x_i: float, x_j: float, y_i: float, y_j: float, x: float) -> float: + return (1 - (x_j - x) / (x_j - x_i)) * (y_j - y_i) + y_i + + +def calc_taxable_income( + salary: float, + deductible_social_security: float, + deductibles_other: float = 0, + config: TaxConfig | None = None, + partner_salary: float = 0, +) -> float: + """ + Calculate the taxable income for a given salary and deductibles. + + Applies the year-specific employee lump-sum deduction + (Arbeitnehmer-Pauschbetrag) per earner and the special expenses lump sum + (Sonderausgaben-Pauschbetrag), which doubles for married couples under + joint assessment. + + Parameters + ---------- + salary: float or int + The yearly salary for which the taxable income should be calculated. + deductible_social_security: float or int + The amount of deductible social security contributions + (for both partners combined if partner_salary is given). + deductibles_other: float or int, optional + Other deductibles that reduce the taxable income (default is 0). + config : TaxConfig, optional + Tax configuration (uses default if not provided) + partner_salary: float or int, optional + Yearly salary of the spouse for jointly assessed couples (default is 0). + + Returns + ------- + taxable_income: float + The taxable income for the given salary and deductibles. + + Examples + -------- + # Calculate taxable income for a salary of 50000 with deductible social security contributions of 1000 and no other deductibles + calc_taxable_income(50000, 1000) + + # Calculate taxable income for a salary of 60000 with deductible social security contributions of 2000 and other deductibles of 500 + calc_taxable_income(60000, 2000, 500) + """ + if config is None: + config = TaxConfig() + + werbungskosten = DEDUCTIONS_DATA[config.year]["werbungskosten_pauschbetrag"] + sonderausgaben = DEDUCTIONS_DATA[config.year]["sonderausgaben_pauschbetrag"] * ( + 2 if config.is_married else 1 + ) + income = max(0, salary - werbungskosten) + if partner_salary > 0: + income += max(0, partner_salary - werbungskosten) + return math.floor( + max( + 0, + income - deductible_social_security - sonderausgaben - deductibles_other, + ) + ) + + +def calc_income_tax(taxable_income: float, config: TaxConfig | None = None) -> float: + """ + Calculate the income tax for a given taxable income. + + Parameters + ---------- + taxable_income: float or int + The taxable income for which the income tax should be calculated. + config : TaxConfig, optional + Tax configuration (uses default if not provided) + + Returns + ------- + income_tax: float + The income tax for the given taxable income. + + Examples + -------- + # Calculate income tax for a taxable income of 10000 + calc_income_tax(10000) + """ + if config is None: + config = TaxConfig() + + # Ehegattensplitting: tax the halved income at the single tariff, doubled + if config.is_married: + return 2 * calc_income_tax( + taxable_income / 2, replace(config, is_married=False) + ) + + taxable_income = round(taxable_income) + if taxable_income <= TAX_CURVE_DATA[config.year][0]["step"]: + return 0 + elif taxable_income <= TAX_CURVE_DATA[config.year][1]["step"]: + y = (taxable_income - TAX_CURVE_DATA[config.year][0]["step"]) / 10000 + return ( + TAX_CURVE_DATA[config.year][1]["const"][0] * y + + TAX_CURVE_DATA[config.year][1]["const"][1] + ) * y + elif taxable_income <= TAX_CURVE_DATA[config.year][2]["step"]: + z = (taxable_income - TAX_CURVE_DATA[config.year][1]["step"]) / 10000 + return ( + TAX_CURVE_DATA[config.year][2]["const"][0] * z + + TAX_CURVE_DATA[config.year][2]["const"][1] + ) * z + TAX_CURVE_DATA[config.year][2]["const"][2] + elif taxable_income <= TAX_CURVE_DATA[config.year][3]["step"]: + return ( + TAX_CURVE_DATA[config.year][2]["rate"] * taxable_income + - TAX_CURVE_DATA[config.year][3]["const"][0] + ) + else: + return ( + TAX_CURVE_DATA[config.year][3]["rate"] * taxable_income + - TAX_CURVE_DATA[config.year][3]["const"][1] + ) + + +def calc_income_tax_by_integration( + taxable_income: float, config: TaxConfig | None = None +) -> float: + """ + Calculate income tax by numerical integration of marginal tax rates. + + Parameters + ---------- + taxable_income: float + Taxable income + config : TaxConfig, optional + Tax configuration (uses defaults if not provided) + + Returns + ------- + float + Income tax amount + + Examples + -------- + >>> calc_income_tax_by_integration(10000) + """ + if config is None: + config = TaxConfig() + + income_tax, _ = quad( + lambda ti: get_marginal_tax_rate(ti, config), 0, taxable_income + ) + return income_tax diff --git a/netto/taxes_other.py b/netto/taxes_other.py new file mode 100644 index 0000000000000000000000000000000000000000..bbccb20b393d6dc769572c434c4d79e95b229ec6 --- /dev/null +++ b/netto/taxes_other.py @@ -0,0 +1,60 @@ +from netto.config import TaxConfig +from netto.data_loader import soli_curve + + +def calc_soli(tax_assessment: float, config: TaxConfig | None = None) -> float: + """ + Calculate solidarity tax (Solidaritätszuschlag). + + Parameters + ---------- + tax_assessment : float + The income tax assessment base + config : TaxConfig, optional + Tax configuration (uses default if not provided) + + Returns + ------- + float + The solidarity tax amount + """ + if config is None: + config = TaxConfig() + + # The exemption threshold (Freigrenze) doubles for jointly assessed couples + exemption_threshold = soli_curve[config.year]["start_taxable_income"] * ( + 2 if config.is_married else 1 + ) + return round( + max( + min( + max(0, tax_assessment - exemption_threshold) + * soli_curve[config.year]["start_fraction"], + tax_assessment * soli_curve[config.year]["end_rate"], + ), + 0, + ), + 2, + ) + + +def calc_church_tax(tax_assessment: float, config: TaxConfig | None = None) -> float: + """ + Calculate church tax (Kirchensteuer). + + Parameters + ---------- + tax_assessment : float + The income tax assessment base + config : TaxConfig, optional + Tax configuration (uses default if not provided) + + Returns + ------- + float + The church tax amount + """ + if config is None: + config = TaxConfig() + + return round(max(tax_assessment * config.church_tax, 0), 2) diff --git a/scripts/generate_forecast.py b/scripts/generate_forecast.py new file mode 100644 index 0000000000000000000000000000000000000000..16618d07e4b6e3aa98d31daa72e6a4d1ba567993 --- /dev/null +++ b/scripts/generate_forecast.py @@ -0,0 +1,211 @@ +""" +Generate forecast tax data for future years (2027-2032). + +All generated values are ESTIMATES for planning purposes, extrapolated from +enacted 2026 law. Assumptions (edit below and re-run to regenerate): + +Income tax curve + - Bracket boundaries E0 (Grundfreibetrag), E1, E2 are indexed by + TARIFF_INDEXATION per year, following the pattern of recent + inflation-adjustment laws (2025->2026 was ~+2.1%). + - The top bracket boundary E3 (277,826) stays frozen, as it has been + since 2022 (deliberate policy). + - Polynomial coefficients are derived exactly from the boundaries using + the structure of § 32a EStG (marginal rate rises linearly from 14% to + 23.97% in zone 1 and from 23.97% to 42% in zone 2). + +Solidarity tax + - Exemption threshold indexed by TARIFF_INDEXATION per year. + +Social security + - Contribution ceilings (Beitragsbemessungsgrenzen) grow by BBG_GROWTH + per year (long-run wage growth; 2018-2026 average was ~3.3%), rounded + to the official grid (multiples of 600 EUR/year for pension and + unemployment, 150 EUR/year for health and nursing). + - Pension rate follows the official Rentenversicherungsbericht + projection: stable at 18.6% until 2027, then rising towards ~20% by + the early 2030s (employee half in PENSION_RATE_PATH). + - Nursing rate rises moderately (PFLEGE_RATE_PATH), reflecting projected + financing gaps; childless surcharge unchanged. + - The average health Zusatzbeitrag (health "extra") keeps rising by + 0.1 percentage points per year (HEALTH_EXTRA_PATH), continuing the + trend that reached 2.9% in 2026. + - Health base (7.3%) and unemployment (1.3%) employee rates stay flat. + +Lump-sum deductions and pension deduction factor + - Werbungskosten-Pauschbetrag (1,230) and Sonderausgaben-Pauschbetrag + (36) stay flat (no enacted changes). + - Pension contributions remain 100% deductible (factor 1.0, law since + 2023). + +Child benefits + - Kindergeld and Kinderfreibetrag (incl. BEA) are indexed by + TARIFF_INDEXATION per year, rounded to multiples of 12 EUR/year so + monthly amounts stay whole euros. + +Run from the repository root: python scripts/generate_forecast.py +""" + +import json +from pathlib import Path + +DATA_DIR = Path(__file__).parent.parent / "data" + +FORECAST_YEARS = range(2027, 2033) + +TARIFF_INDEXATION = 0.02 # yearly growth of tax bracket boundaries and soli threshold +BBG_GROWTH = 0.03 # yearly growth of social security contribution ceilings +E3_FROZEN = 277826 # top bracket boundary, frozen since 2022 + +# Employee shares; pension per Rentenversicherungsbericht projection path +PENSION_RATE_PATH = { + 2027: 0.093, + 2028: 0.094, + 2029: 0.096, + 2030: 0.098, + 2031: 0.099, + 2032: 0.100, +} +PFLEGE_RATE_PATH = { + 2027: 0.018, + 2028: 0.019, + 2029: 0.019, + 2030: 0.020, + 2031: 0.020, + 2032: 0.020, +} +# Total average Zusatzbeitrag (not halved); 2026 official average was 2.9% +HEALTH_EXTRA_PATH = { + 2027: 0.030, + 2028: 0.031, + 2029: 0.032, + 2030: 0.033, + 2031: 0.034, + 2032: 0.035, +} + + +def derive_tax_constants(e0: int, e1: int, e2: int, e3: int) -> dict: + """Derive § 32a EStG polynomial coefficients from bracket boundaries. + + Zone 1 (E0..E1): marginal rate rises linearly 14% -> 23.97%, + tax = (a*y + 1400)*y with y = (zvE - E0)/10000. + Zone 2 (E1..E2): marginal rate rises linearly 23.97% -> 42%, + tax = (b*z + 2397)*z + C with z = (zvE - E1)/10000. + Zones 3/4: tax = 0.42*zvE - s0 and 0.45*zvE - s1. + """ + a = 4985000 / (e1 - e0) # (2397 - 1400) * 10000 / (2 * (E1 - E0)) + tax_at_e1 = 1898.5 * (e1 - e0) / 10000 # (a*y1 + 1400)*y1 simplified + b = 9015000 / (e2 - e1) # (4200 - 2397) * 10000 / (2 * (E2 - E1)) + tax_at_e2 = tax_at_e1 + 3298.5 * (e2 - e1) / 10000 + s0 = 0.42 * e2 - tax_at_e2 + s1 = s0 + 0.03 * e3 + return { + "0": {"step": e0, "rate": 0.14, "const": None}, + "1": {"step": e1, "rate": 0.2397, "const": [round(a, 2), 1400]}, + "2": { + "step": e2, + "rate": 0.42, + "const": [round(b, 2), 2397, round(tax_at_e1, 2)], + }, + "3": {"step": e3, "rate": 0.45, "const": [round(s0, 2), round(s1, 2)]}, + } + + +def round_to(value: float, grid: int) -> int: + return int(round(value / grid) * grid) + + +def write_json(path: Path, data: dict) -> None: + with open(path, "w") as f: + json.dump(data, f, indent=2) + f.write("\n") + print(f"wrote {path}") + + +def main() -> None: + base_tax = json.load(open(DATA_DIR / "tax_curves" / "2026.json"))["brackets"] + e0 = base_tax["0"]["step"] + e1 = base_tax["1"]["step"] + e2 = base_tax["2"]["step"] + + base_soli = json.load(open(DATA_DIR / "soli" / "2026.json")) + soli_threshold = base_soli["start_taxable_income"] + + base_social = json.load(open(DATA_DIR / "social_security" / "2026.json")) + bbg_pension = base_social["pension"]["limit"] + bbg_health = base_social["health"]["limit"] + + base_children = json.load(open(DATA_DIR / "children" / "2026.json")) + kindergeld = base_children["kindergeld_per_child"] + kinderfreibetrag = base_children["kinderfreibetrag_per_child"] + + for year in FORECAST_YEARS: + e0 = round(e0 * (1 + TARIFF_INDEXATION)) + e1 = round(e1 * (1 + TARIFF_INDEXATION)) + e2 = round(e2 * (1 + TARIFF_INDEXATION)) + write_json( + DATA_DIR / "tax_curves" / f"{year}.json", + {"year": year, "brackets": derive_tax_constants(e0, e1, e2, E3_FROZEN)}, + ) + + soli_threshold = round(soli_threshold * (1 + TARIFF_INDEXATION)) + write_json( + DATA_DIR / "soli" / f"{year}.json", + { + "year": year, + "start_taxable_income": soli_threshold, + "start_fraction": 0.119, + "end_rate": 0.055, + }, + ) + + bbg_pension = round_to(bbg_pension * (1 + BBG_GROWTH), 600) + bbg_health = round_to(bbg_health * (1 + BBG_GROWTH), 150) + write_json( + DATA_DIR / "social_security" / f"{year}.json", + { + "year": year, + "pension": {"limit": bbg_pension, "rate": PENSION_RATE_PATH[year]}, + "unemployment": {"limit": bbg_pension, "rate": 0.013}, + "health": { + "limit": bbg_health, + "rate": 0.073, + "extra": HEALTH_EXTRA_PATH[year], + }, + "nursing": { + "limit": bbg_health, + "rate": PFLEGE_RATE_PATH[year], + "extra": 0.006, + }, + }, + ) + + write_json( + DATA_DIR / "pension_factors" / f"{year}.json", + {"year": year, "factor": 1.0}, + ) + + write_json( + DATA_DIR / "deductions" / f"{year}.json", + { + "year": year, + "werbungskosten_pauschbetrag": 1230, + "sonderausgaben_pauschbetrag": 36, + }, + ) + + kindergeld = round_to(kindergeld * (1 + TARIFF_INDEXATION), 12) + kinderfreibetrag = round_to(kinderfreibetrag * (1 + TARIFF_INDEXATION), 12) + write_json( + DATA_DIR / "children" / f"{year}.json", + { + "year": year, + "kindergeld_per_child": kindergeld, + "kinderfreibetrag_per_child": kinderfreibetrag, + }, + ) + + +if __name__ == "__main__": + main() diff --git a/test/test_config.py b/test/test_config.py new file mode 100644 index 0000000000000000000000000000000000000000..f0e0057ee3720b46db631effd981396d8305e91f --- /dev/null +++ b/test/test_config.py @@ -0,0 +1,55 @@ +import pytest + +from netto.config import TaxConfig + + +def test_taxconfig_defaults(): + """Test that TaxConfig uses correct default values""" + config = TaxConfig() + assert config.year == 2025 + assert config.has_children is False + assert config.is_married is False + assert config.extra_health_insurance is None # year-specific average + assert config.church_tax == 0.09 + + +def test_taxconfig_custom_values(): + """Test creating TaxConfig with custom values""" + config = TaxConfig( + year=2025, + has_children=True, + is_married=True, + extra_health_insurance=0.02, + church_tax=0.08, + ) + assert config.year == 2025 + assert config.has_children is True + assert config.is_married is True + assert config.extra_health_insurance == 0.02 + assert config.church_tax == 0.08 + + +def test_taxconfig_validation_year_range(): + """Test that year validation works""" + with pytest.raises(ValueError): + TaxConfig(year=2017) # Too early + with pytest.raises(ValueError): + TaxConfig(year=2033) # Too late + + +def test_taxconfig_validation_negative_rates(): + """Test that negative rates are rejected""" + with pytest.raises(ValueError): + TaxConfig(extra_health_insurance=-0.01) + with pytest.raises(ValueError): + TaxConfig(church_tax=-0.01) + + +def test_taxconfig_validation_type_errors(): + """Test that type validation works""" + with pytest.raises(TypeError): + TaxConfig(year="2022") # String instead of int + with pytest.raises(TypeError): + TaxConfig(has_children="True") # String instead of bool + with pytest.raises(TypeError): + TaxConfig(is_married=1) # Int instead of bool diff --git a/test/test_data_loader.py b/test/test_data_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..445472fe48c531d70ee6d25583b02b0ab2ffc6f2 --- /dev/null +++ b/test/test_data_loader.py @@ -0,0 +1,447 @@ +import pytest +from pydantic import ValidationError + +from netto.data_loader import ( + Deductions, + PensionFactor, + SocialSecurity, + SocialSecurityEntry, + SoliCurve, + TaxBracket, + TaxCurve, + correction_factor_pensions, + deductions, + load_all_deductions, + load_all_pension_factors, + load_all_social_security, + load_all_soli, + load_all_tax_curves, + load_deductions, + load_pension_factor, + load_social_security, + load_soli, + load_tax_curve, + social_security_curve, + soli_curve, + tax_curve, +) + +# Tests for Pydantic Models + + +def test_tax_bracket_valid(): + """Test creating a valid TaxBracket""" + bracket = TaxBracket(step=10000, rate=0.14, const=[100, 200]) + assert bracket.step == 10000 + assert bracket.rate == 0.14 + assert bracket.const == [100, 200] + + +def test_tax_bracket_no_const(): + """Test creating TaxBracket without const""" + bracket = TaxBracket(step=10000, rate=0.0) + assert bracket.step == 10000 + assert bracket.rate == 0.0 + assert bracket.const is None + + +def test_tax_bracket_invalid_step(): + """Test that TaxBracket rejects invalid step values""" + with pytest.raises(ValidationError): + TaxBracket(step=0, rate=0.14) # step must be > 0 + with pytest.raises(ValidationError): + TaxBracket(step=-100, rate=0.14) # negative not allowed + + +def test_tax_bracket_invalid_rate(): + """Test that TaxBracket rejects invalid rate values""" + with pytest.raises(ValidationError): + TaxBracket(step=10000, rate=-0.1) # negative not allowed + with pytest.raises(ValidationError): + TaxBracket(step=10000, rate=1.5) # > 1 not allowed + + +def test_tax_bracket_empty_const(): + """Test that TaxBracket rejects empty const array""" + with pytest.raises(ValidationError): + TaxBracket(step=10000, rate=0.14, const=[]) + + +def test_tax_curve_valid(): + """Test creating a valid TaxCurve""" + curve = TaxCurve( + year=2022, + brackets={ + "0": TaxBracket(step=10347, rate=0.0), + "1": TaxBracket(step=14927, rate=0.14, const=[995.21, 1400]), + "2": TaxBracket(step=58597, rate=0.2397, const=[208.85, 2397, 950.96]), + "3": TaxBracket(step=277826, rate=0.42, const=[0.42, 9336.45]), + }, + ) + assert curve.year == 2022 + assert len(curve.brackets) == 4 + + +def test_tax_curve_invalid_brackets(): + """Test that TaxCurve requires exactly 4 brackets""" + with pytest.raises(ValidationError): + TaxCurve( + year=2022, + brackets={ + "0": TaxBracket(step=10000, rate=0.0), + "1": TaxBracket(step=20000, rate=0.14), + }, + ) + + +def test_tax_curve_invalid_year(): + """Test that TaxCurve validates year range""" + with pytest.raises(ValidationError): + TaxCurve( + year=2015, # Too early + brackets={ + "0": TaxBracket(step=10000, rate=0.0), + "1": TaxBracket(step=20000, rate=0.14), + "2": TaxBracket(step=30000, rate=0.24), + "3": TaxBracket(step=40000, rate=0.42), + }, + ) + + +def test_social_security_entry_valid(): + """Test creating a valid SocialSecurityEntry""" + entry = SocialSecurityEntry(limit=84600, rate=0.093) + assert entry.limit == 84600 + assert entry.rate == 0.093 + assert entry.extra is None + + +def test_social_security_entry_with_extra(): + """Test creating SocialSecurityEntry with extra rate""" + entry = SocialSecurityEntry(limit=58050, rate=0.073, extra=0.0035) + assert entry.limit == 58050 + assert entry.rate == 0.073 + assert entry.extra == 0.0035 + + +def test_social_security_entry_invalid_limit(): + """Test that SocialSecurityEntry validates limit""" + with pytest.raises(ValidationError): + SocialSecurityEntry(limit=0, rate=0.093) # Must be > 0 + with pytest.raises(ValidationError): + SocialSecurityEntry(limit=-1000, rate=0.093) # Negative not allowed + + +def test_social_security_valid(): + """Test creating a valid SocialSecurity""" + social_sec = SocialSecurity( + year=2022, + pension=SocialSecurityEntry(limit=84600, rate=0.093), + unemployment=SocialSecurityEntry(limit=84600, rate=0.012), + health=SocialSecurityEntry(limit=58050, rate=0.073, extra=0.007), + nursing=SocialSecurityEntry(limit=58050, rate=0.01525, extra=0.0035), + ) + assert social_sec.year == 2022 + assert social_sec.pension.limit == 84600 + assert social_sec.health.extra == 0.007 + + +def test_soli_curve_valid(): + """Test creating a valid SoliCurve""" + soli = SoliCurve( + year=2022, start_taxable_income=16956, start_fraction=0.119, end_rate=0.055 + ) + assert soli.year == 2022 + assert soli.start_taxable_income == 16956 + assert soli.start_fraction == 0.119 + assert soli.end_rate == 0.055 + + +def test_pension_factor_valid(): + """Test creating a valid PensionFactor""" + factor = PensionFactor(year=2022, factor=0.88) + assert factor.year == 2022 + assert factor.factor == 0.88 + + +def test_pension_factor_invalid_factor(): + """Test that PensionFactor validates factor range""" + with pytest.raises(ValidationError): + PensionFactor(year=2022, factor=-0.1) # Negative not allowed + with pytest.raises(ValidationError): + PensionFactor(year=2022, factor=1.5) # > 1 not allowed + + +def test_deductions_valid(): + """Test creating a valid Deductions model""" + deductions_model = Deductions( + year=2022, werbungskosten_pauschbetrag=1200, sonderausgaben_pauschbetrag=36 + ) + assert deductions_model.year == 2022 + assert deductions_model.werbungskosten_pauschbetrag == 1200 + assert deductions_model.sonderausgaben_pauschbetrag == 36 + + +def test_deductions_invalid_values(): + """Test that Deductions rejects negative values""" + with pytest.raises(ValidationError): + Deductions( + year=2022, werbungskosten_pauschbetrag=-1, sonderausgaben_pauschbetrag=36 + ) + with pytest.raises(ValidationError): + Deductions( + year=2022, werbungskosten_pauschbetrag=1200, sonderausgaben_pauschbetrag=-1 + ) + + +# Tests for individual load functions + + +@pytest.mark.parametrize("year", list(range(2018, 2033))) +def test_load_tax_curve(year): + """Test loading tax curve for available years""" + curve = load_tax_curve(year) + assert isinstance(curve, dict) + assert len(curve) == 4 + assert all(k in [0, 1, 2, 3] for k in curve.keys()) + assert all("step" in v and "rate" in v for v in curve.values()) + + +def test_load_tax_curve_missing_year(): + """Test that loading tax curve for missing year raises FileNotFoundError""" + with pytest.raises(FileNotFoundError): + load_tax_curve(2035) + + +@pytest.mark.parametrize("year", list(range(2018, 2033))) +def test_load_social_security(year): + """Test loading social security for available years""" + social_sec = load_social_security(year) + assert isinstance(social_sec, dict) + assert "pension" in social_sec + assert "unemployment" in social_sec + assert "health" in social_sec + assert "nursing" in social_sec + + +def test_load_social_security_not_implemented(): + """Test that loading social security for 2033+ raises NotImplementedError""" + with pytest.raises(NotImplementedError): + load_social_security(2033) + + +def test_load_social_security_missing_year(): + """Test that loading social security for missing year raises FileNotFoundError""" + with pytest.raises(FileNotFoundError): + load_social_security(2015) + + +@pytest.mark.parametrize("year", list(range(2018, 2033))) +def test_load_soli(year): + """Test loading solidarity tax data for available years""" + soli = load_soli(year) + assert isinstance(soli, dict) + assert "start_taxable_income" in soli + assert "start_fraction" in soli + assert "end_rate" in soli + + +def test_load_soli_missing_year(): + """Test that loading soli for missing year raises FileNotFoundError""" + with pytest.raises(FileNotFoundError): + load_soli(2035) + + +@pytest.mark.parametrize("year", list(range(2018, 2033))) +def test_load_pension_factor(year): + """Test loading pension factor for available years""" + factor = load_pension_factor(year) + assert isinstance(factor, float) + assert 0 <= factor <= 1 + + +def test_load_pension_factor_missing_year(): + """Test that loading pension factor for missing year raises FileNotFoundError""" + with pytest.raises(FileNotFoundError): + load_pension_factor(2035) + + +@pytest.mark.parametrize( + "year,expected_werbungskosten", + [ + (2018, 1000), + (2019, 1000), + (2020, 1000), + (2021, 1000), + (2022, 1200), + (2023, 1230), + (2024, 1230), + (2025, 1230), + (2026, 1230), + ], +) +def test_load_deductions(year, expected_werbungskosten): + """Test loading deductions with year-specific Werbungskosten-Pauschbetrag""" + deductions_data = load_deductions(year) + assert deductions_data["werbungskosten_pauschbetrag"] == expected_werbungskosten + assert deductions_data["sonderausgaben_pauschbetrag"] == 36 + + +def test_load_deductions_missing_year(): + """Test that loading deductions for missing year raises FileNotFoundError""" + with pytest.raises(FileNotFoundError): + load_deductions(2035) + + +# Tests for bulk load functions + + +def test_load_all_tax_curves(): + """Test loading all tax curves""" + curves = load_all_tax_curves() + assert isinstance(curves, dict) + assert len(curves) >= 8 # At least 2018-2025 + for year, curve in curves.items(): + assert isinstance(year, int) + assert isinstance(curve, dict) + assert len(curve) == 4 + + +def test_load_all_social_security(): + """Test loading all social security data""" + social_security_data = load_all_social_security() + assert isinstance(social_security_data, dict) + assert len(social_security_data) >= 15 # At least 2018-2032 + + +def test_load_all_soli(): + """Test loading all solidarity tax data""" + soli_data = load_all_soli() + assert isinstance(soli_data, dict) + assert len(soli_data) >= 8 # At least 2018-2025 + for year, soli in soli_data.items(): + assert isinstance(year, int) + assert isinstance(soli, dict) + + +def test_load_all_pension_factors(): + """Test loading all pension factors""" + factors = load_all_pension_factors() + assert isinstance(factors, dict) + assert len(factors) >= 8 # At least 2018-2025 + for year, factor in factors.items(): + assert isinstance(year, int) + assert isinstance(factor, float) + assert 0 <= factor <= 1 + + +# Tests for module-level variables + + +def test_module_tax_curve(): + """Test that tax_curve is loaded at module level""" + assert isinstance(tax_curve, dict) + assert len(tax_curve) >= 8 + assert 2022 in tax_curve + assert len(tax_curve[2022]) == 4 + + +def test_module_social_security_curve(): + """Test that social_security_curve is loaded at module level""" + assert isinstance(social_security_curve, dict) + assert len(social_security_curve) >= 8 + assert 2022 in social_security_curve + assert "pension" in social_security_curve[2022] + + +def test_module_soli_curve(): + """Test that soli_curve is loaded at module level""" + assert isinstance(soli_curve, dict) + assert len(soli_curve) >= 8 + assert 2022 in soli_curve + assert "start_taxable_income" in soli_curve[2022] + + +def test_module_correction_factor_pensions(): + """Test that correction_factor_pensions is loaded at module level""" + assert isinstance(correction_factor_pensions, dict) + assert len(correction_factor_pensions) >= 8 + assert 2022 in correction_factor_pensions + assert isinstance(correction_factor_pensions[2022], float) + + +def test_load_all_deductions(): + """Test loading all deductions data""" + deductions_data = load_all_deductions() + assert isinstance(deductions_data, dict) + assert len(deductions_data) >= 15 # At least 2018-2032 + for year, entry in deductions_data.items(): + assert isinstance(year, int) + assert "werbungskosten_pauschbetrag" in entry + assert "sonderausgaben_pauschbetrag" in entry + + +def test_module_deductions(): + """Test that deductions is loaded at module level""" + assert isinstance(deductions, dict) + assert 2022 in deductions + assert deductions[2022]["werbungskosten_pauschbetrag"] == 1200 + + +# Integration tests + + +def test_tax_curve_structure_2022(): + """Test that 2022 tax curve has expected structure""" + curve_2022 = load_tax_curve(2022) + + # Bracket 0: Basic allowance + assert curve_2022[0]["step"] == 10347 + assert curve_2022[0]["rate"] == 0.14 + + # Bracket 1: Progressive zone 1 + assert curve_2022[1]["step"] == 14926 + assert curve_2022[1]["rate"] == 0.2397 + assert curve_2022[1]["const"] is not None + + # Bracket 2: Progressive zone 2 + assert curve_2022[2]["step"] == 58596 + assert curve_2022[2]["rate"] == 0.42 + assert curve_2022[2]["const"] is not None + + # Bracket 3: Top rate + assert curve_2022[3]["step"] == 277826 + assert curve_2022[3]["rate"] == 0.45 + + +def test_social_security_structure_2022(): + """Test that 2022 social security has expected structure""" + ss_2022 = load_social_security(2022) + + # Pension insurance + assert ss_2022["pension"]["limit"] == 84600 + assert ss_2022["pension"]["rate"] == 0.093 + + # Health insurance + assert ss_2022["health"]["limit"] == 58050 + assert ss_2022["health"]["rate"] == 0.073 + + # Nursing insurance + assert ss_2022["nursing"]["limit"] == 58050 + assert ss_2022["nursing"]["rate"] == 0.01525 + + +def test_soli_structure_2022(): + """Test that 2022 soli has expected structure""" + soli_2022 = load_soli(2022) + + assert soli_2022["start_taxable_income"] == 16956 + assert soli_2022["start_fraction"] == 0.119 + assert soli_2022["end_rate"] == 0.055 + + +def test_pension_factor_value_2022(): + """Test that 2022 pension factor has expected value""" + factor_2022 = load_pension_factor(2022) + + assert factor_2022 == 0.88 diff --git a/test/test_main.py b/test/test_main.py new file mode 100644 index 0000000000000000000000000000000000000000..2d980685d638de233d26474ec8524b3774d83ceb --- /dev/null +++ b/test/test_main.py @@ -0,0 +1,197 @@ +from io import StringIO +from unittest.mock import patch + +import pytest + +import netto.main as main +from netto.config import TaxConfig + + +@pytest.fixture +def default_config(): + """Fixture providing default config for tests""" + return TaxConfig( + year=2022, extra_health_insurance=0.014, church_tax=0.09, has_children=False + ) + + +@pytest.fixture +def alternate_config(): + """Fixture providing alternate config for tests""" + return TaxConfig( + year=2022, extra_health_insurance=0.015, church_tax=0.0, has_children=True + ) + + +@pytest.mark.parametrize( + "salary,expected", + [ + (0, 0), + (30000, 20554.38), + (60000, 35796.68), + (90000, 49956.92), + (120000, 64965.08), + ], +) +def test_calc_netto_with_default_config(salary, expected, default_config): + """Test calc_netto with various salaries using default config""" + result = main.calc_netto(salary, config=default_config) + assert abs(result - expected) < 1 + + +@pytest.mark.parametrize( + "salary,expected", + [ + (30000, 20894.58), + (60000, 36909.71), + (90000, 52091.39), + (120000, 68238.23), + ], +) +def test_calc_netto_with_alternate_config(salary, expected, alternate_config): + """Test calc_netto with alternate config (no church tax, with children)""" + result = main.calc_netto(salary, config=alternate_config) + assert abs(result - expected) < 1 + + +@pytest.mark.parametrize( + "desired_netto,expected_gross", + [ + (20894.58, 30000), + (36909.71, 60000), + (52091.39, 90000), + (68238.23, 120000), + ], +) +def test_calc_inverse_netto(desired_netto, expected_gross, alternate_config): + """Test inverse netto calculation""" + result = main.calc_inverse_netto(desired_netto, config=alternate_config) + assert abs(result - expected_gross) <= 1 + + +def test_calc_inverse_netto_roundtrip(alternate_config): + """Test that calc_inverse_netto and calc_netto are inverses""" + salary = 10000 + netto = main.calc_netto(salary, config=alternate_config) + gross = main.calc_inverse_netto(netto, config=alternate_config) + assert gross == salary + + +@pytest.fixture +def married_config(): + """Fixture providing a married config for tests""" + return TaxConfig(year=2025, is_married=True, church_tax=0.0) + + +@pytest.mark.parametrize( + "salary,expected", + [ + (50000, 36263.40), + (100000, 67016.96), + (150000, 98603.98), # income tax 33940 is below married soli threshold 39900 + (250000, 152445.93), + ], +) +def test_calc_netto_married(salary, expected, married_config): + """Test married netto (splitting tariff, doubled soli threshold)""" + result = main.calc_netto(salary, config=married_config) + assert abs(result - expected) < 1 + + +def test_calc_netto_married_higher_than_single(married_config): + """Splitting must never yield less netto than the single tariff""" + single_config = TaxConfig(year=2025, church_tax=0.0) + for salary in [30000, 60000, 100000, 150000, 250000]: + assert main.calc_netto(salary, config=married_config) >= main.calc_netto( + salary, config=single_config + ) + + +def test_calc_netto_dual_income(married_config): + """Test household netto for a dual-income married couple""" + result = main.calc_netto(80000, config=married_config, partner_salary=80000) + assert abs(result - 96345.38) < 1 + + +def test_calc_netto_dual_income_pays_more_social_security(married_config): + """Same household income, but two earners below the contribution ceilings + pay more social security than a single earner above them""" + single_earner = main.calc_netto(160000, config=married_config) + dual_earner = main.calc_netto(80000, config=married_config, partner_salary=80000) + assert dual_earner < single_earner + + +def test_calc_netto_partner_salary_zero_equals_single_earner(married_config): + """partner_salary=0 must behave exactly like the single-earner call""" + assert main.calc_netto( + 100000, config=married_config, partner_salary=0 + ) == main.calc_netto(100000, config=married_config) + + +def test_calc_netto_partner_salary_requires_married(default_config): + """partner_salary without is_married must raise""" + with pytest.raises(ValueError, match="is_married"): + main.calc_netto(50000, config=default_config, partner_salary=10000) + + +def test_calc_netto_negative_partner_salary(married_config): + """Negative partner_salary must raise""" + with pytest.raises(ValueError, match="non-negative"): + main.calc_netto(50000, config=married_config, partner_salary=-1) + + +def test_calc_inverse_netto_dual_income_roundtrip(married_config): + """Inverse calculation with a fixed partner salary recovers the gross salary""" + netto = main.calc_netto(80000, config=married_config, partner_salary=50000) + gross = main.calc_inverse_netto(netto, config=married_config, partner_salary=50000) + assert abs(gross - 80000) <= 1 + + +def test_calc_inverse_netto_partner_already_covers_desired(married_config): + """A desired netto already reached by the partner salary alone must raise""" + with pytest.raises(ValueError, match="partner salary alone"): + main.calc_inverse_netto(20000, config=married_config, partner_salary=100000) + + +@pytest.mark.parametrize("year", list(range(2018, 2033))) +def test_calc_netto_all_years_smoke(year): + """calc_netto must produce a plausible result for every supported year, + including the 2027-2032 forecast years""" + config = TaxConfig(year=year, church_tax=0.0) + netto = main.calc_netto(60000, config=config) + assert 30000 < netto < 60000 + + +@patch("sys.stdout", new_callable=StringIO) +def test_verbose_print(mock_stdout, default_config): + """Test that verbose mode prints expected output""" + main.calc_netto(0, verbose=True, config=default_config) + actual_output = mock_stdout.getvalue().strip() + expected_output = ( + "Yearly Evaluation:\n" + + f"Income Tax: {0.0:>12}\n" + + f"Soli: {0.0:>12}\n" + + f"Church Tax: {0.0:>12}\n" + + f"Social Security: {0.0:>12}" + ) + assert actual_output == expected_output + + +def test_calc_netto_with_default_none_config(): + """Test that calc_netto works when config=None (uses default TaxConfig)""" + result = main.calc_netto(30000) + # Should use default TaxConfig (year=2022, etc.) + assert isinstance(result, float) + assert result > 0 + + +def test_calc_inverse_netto_with_default_none_config(): + """Test that calc_inverse_netto works when config=None (uses default TaxConfig)""" + # Use a value that we know works well with Newton's method + # Use explicit year=2022 for stable test behavior + result = main.calc_inverse_netto(30000, config=TaxConfig(year=2022)) + # Should use default TaxConfig + assert isinstance(result, int | float) + assert result > 0 + # Verify the result makes sense (gross should be higher than net) + assert result > 30000 diff --git a/test/test_social_security.py b/test/test_social_security.py new file mode 100644 index 0000000000000000000000000000000000000000..fa774fef6361d7c64920d74c6427154d74f89677 --- /dev/null +++ b/test/test_social_security.py @@ -0,0 +1,251 @@ +import pytest + +import netto.social_security as social_security +from netto.config import TaxConfig + + +@pytest.fixture +def default_config(): + """Fixture providing default config for tests""" + return TaxConfig( + year=2022, extra_health_insurance=0.014, church_tax=0.09, has_children=False + ) + + +@pytest.mark.parametrize( + "salary,expected", + [ + (0, 0), + (10000, 0.093), + (84600, 0.093), + (84601, 0), + (100000, 0), + ], +) +def test_get_rate_pension(salary, expected, default_config): + """Test pension rate calculation""" + result = social_security.get_rate_pension(salary, default_config) + assert result == expected + + +@pytest.mark.parametrize( + "salary,expected", + [ + (0, 0), + (10000, 0.08), + (58050, 0.08), + (58051, 0), + (100000, 0), + ], +) +def test_get_rate_health(salary, expected, default_config): + """Test health insurance rate calculation""" + result = social_security.get_rate_health(salary, default_config) + assert result == expected + + +@pytest.mark.parametrize( + "salary,expected", + [ + (0, 0), + (10000, 0.093 * 10000), + (84600, 0.093 * 84600), + (84601, 0.093 * 84600), + (100000, 0.093 * 84600), + ], +) +def test_calc_insurance_pension(salary, expected, default_config): + """Test pension insurance calculation""" + result = social_security.calc_insurance_pension(salary, default_config) + assert result == expected + + +@pytest.mark.parametrize( + "salary,expected", + [ + (0, 0), + (10000, 0.08 * 10000), + (58050, 0.08 * 58050), + (58051, 0.08 * 58050), + (100000, 0.08 * 58050), + ], +) +def test_calc_insurance_health(salary, expected, default_config): + """Test health insurance calculation""" + result = social_security.calc_insurance_health(salary, default_config) + assert result == expected + + +def test_calc_deductible_social_security(default_config): + """Test deductible social security calculation""" + assert social_security.calc_deductible_social_security(0, default_config) == 0 + # https://www.lohn-info.de/vorsorgepauschale.html + assert ( + social_security.calc_deductible_social_security(30000, default_config) + == 2456 + 2310 + 563 + ) + + +@pytest.mark.parametrize( + "salary", [0, 10000, 20000, 30000, 40000, 50000, 60000, 70000, 80000, 90000, 100000] +) +def test_sameness_of_calc_social_security(salary, default_config): + """Test that both social security calculation methods give same results""" + result_direct = social_security.calc_social_security(salary, default_config) + result_integration = social_security.calc_social_security_by_integration( + salary, default_config + ) + assert result_direct == result_integration + + +@pytest.mark.parametrize( + "salary", [0, 10000, 20000, 30000, 40000, 50000, 60000, 70000, 80000, 90000, 100000] +) +def test_sameness_of_calc_social_security_different_config(salary): + """Test social security calculation with different config""" + config = TaxConfig(extra_health_insurance=0.015, has_children=True) + result_direct = social_security.calc_social_security(salary, config) + result_integration = social_security.calc_social_security_by_integration( + salary, config + ) + assert abs(result_direct - result_integration) < 0.02 + + +@pytest.mark.parametrize( + "salary,expected", + [ + (0, 0), + (10000, 0.0805), + (58050, 0.0805), + (58051, 0), + (100000, 0), + ], +) +def test_get_rate_health_different_config(salary, expected): + """Test health rate with different extra health insurance""" + config = TaxConfig(year=2022, extra_health_insurance=0.015) + result = social_security.get_rate_health(salary, config) + assert abs(result - expected) < 0.0001 + + +@pytest.mark.parametrize( + "salary,expected", + [ + (0, 0), + (10000, 0.01875), + (58050, 0.01875), + (58051, 0), + (100000, 0), + ], +) +def test_get_rate_nursing_no_children(salary, expected): + """Test nursing rate without children (includes extra rate)""" + config = TaxConfig(year=2022, has_children=False) + result = social_security.get_rate_nursing(salary, config) + assert result == expected + + +@pytest.mark.parametrize( + "salary,expected", + [ + (0, 0), + (10000, 0.01525), + (58050, 0.01525), + (58051, 0), + (100000, 0), + ], +) +def test_get_rate_nursing_with_children(salary, expected): + """Test nursing rate with children (no extra rate)""" + config = TaxConfig(year=2022, has_children=True) + result = social_security.get_rate_nursing(salary, config) + assert result == expected + + +@pytest.mark.parametrize( + "year,average_zusatzbeitrag", + [ + (2018, 0.010), + (2022, 0.013), + (2024, 0.017), + (2025, 0.025), + (2026, 0.029), + (2032, 0.035), # forecast + ], +) +def test_get_rate_health_uses_year_average(year, average_zusatzbeitrag): + """With extra_health_insurance=None, the official year-specific average + Zusatzbeitrag from the data files applies (employee pays half)""" + config = TaxConfig(year=year) + result = social_security.get_rate_health(10000, config) + assert result == pytest.approx(0.073 + average_zusatzbeitrag / 2) + + +def test_get_rate_health_config_overrides_year_average(): + """An explicit extra_health_insurance overrides the year average""" + config = TaxConfig(year=2026, extra_health_insurance=0.019) + result = social_security.get_rate_health(10000, config) + assert result == pytest.approx(0.073 + 0.019 / 2) + + +def test_get_rate_health_zero_override_is_honored(): + """extra_health_insurance=0.0 means no Zusatzbeitrag, not 'use average'""" + config = TaxConfig(year=2026, extra_health_insurance=0.0) + result = social_security.get_rate_health(10000, config) + assert result == pytest.approx(0.073) + + +def test_get_rate_pension_with_default_none_config(): + """Test that get_rate_pension works when config=None""" + result = social_security.get_rate_pension(50000) + assert isinstance(result, float) + assert result >= 0 + + +def test_get_rate_unemployment_with_default_none_config(): + """Test that get_rate_unemployment works when config=None""" + result = social_security.get_rate_unemployment(50000) + assert isinstance(result, float) + assert result >= 0 + + +def test_get_rate_health_with_default_none_config(): + """Test that get_rate_health works when config=None""" + result = social_security.get_rate_health(50000) + assert isinstance(result, float) + assert result >= 0 + + +def test_get_rate_nursing_with_default_none_config(): + """Test that get_rate_nursing works when config=None""" + result = social_security.get_rate_nursing(50000) + assert isinstance(result, float) + assert result >= 0 + + +def test_calc_insurance_pension_with_default_none_config(): + """Test that calc_insurance_pension works when config=None""" + result = social_security.calc_insurance_pension(50000) + assert isinstance(result, float) + assert result >= 0 + + +def test_calc_insurance_health_with_default_none_config(): + """Test that calc_insurance_health works when config=None""" + result = social_security.calc_insurance_health(50000) + assert isinstance(result, float) + assert result >= 0 + + +def test_calc_social_security_with_default_none_config(): + """Test that calc_social_security works when config=None""" + result = social_security.calc_social_security(50000) + assert isinstance(result, float) + assert result >= 0 + + +def test_calc_deductible_social_security_with_default_none_config(): + """Test that calc_deductible_social_security works when config=None""" + result = social_security.calc_deductible_social_security(50000) + assert isinstance(result, int | float) + assert result >= 0 diff --git a/test/test_taxes_children.py b/test/test_taxes_children.py new file mode 100644 index 0000000000000000000000000000000000000000..cc58b00b86f24e08e8b0f4588435c7b47a2ae367 --- /dev/null +++ b/test/test_taxes_children.py @@ -0,0 +1,147 @@ +import pytest + +import netto.main as main +import netto.social_security as social_security +import netto.taxes_children as taxes_children +import netto.taxes_income as taxes_income +from netto.config import TaxConfig + + +@pytest.fixture +def married_two_kids(): + """Married couple with two children, no church tax, 2026""" + return TaxConfig(year=2026, is_married=True, num_children=2, church_tax=0.0) + + +@pytest.fixture +def married_childless_reference(): + """Same as married_two_kids but children only via has_children + (nursing surcharge removed, no Kindergeld/Freibetrag)""" + return TaxConfig(year=2026, is_married=True, has_children=True, church_tax=0.0) + + +@pytest.mark.parametrize( + "year,expected_per_child", + [ + (2018, 2328), + (2019, 2388), # July increase: 6 x 194 + 6 x 204 + (2023, 3000), + (2025, 3060), + (2026, 3108), + ], +) +def test_calc_kindergeld_per_year(year, expected_per_child): + """Kindergeld matches the official yearly amounts (first/second child)""" + config = TaxConfig(year=year, num_children=1) + assert taxes_children.calc_kindergeld(config) == expected_per_child + + +def test_calc_kindergeld_scales_with_children(): + config = TaxConfig(year=2026, num_children=3) + assert taxes_children.calc_kindergeld(config) == 3 * 3108 + + +def test_calc_kindergeld_zero_without_children(): + assert taxes_children.calc_kindergeld(TaxConfig(year=2026)) == 0 + + +def test_child_allowance_halved_for_singles(): + """Single parents get half the allowance (other half belongs to the + other parent)""" + married = TaxConfig(year=2026, is_married=True, num_children=1) + single = TaxConfig(year=2026, num_children=1) + assert taxes_children.calc_child_allowance_per_child(married) == 9756 + assert taxes_children.calc_child_allowance_per_child(single) == 9756 / 2 + + +def test_guenstigerpruefung_kindergeld_wins_at_low_income( + married_two_kids, married_childless_reference +): + """At low income the allowance relief is below the Kindergeld, so the + net benefit is exactly the Kindergeld""" + netto_kids = main.calc_netto(30000, config=married_two_kids) + netto_ref = main.calc_netto(30000, config=married_childless_reference) + kindergeld = taxes_children.calc_kindergeld(married_two_kids) + assert netto_kids - netto_ref == pytest.approx(kindergeld, abs=0.02) + + +def test_guenstigerpruefung_freibetrag_wins_at_high_income( + married_two_kids, married_childless_reference +): + """At high income the allowance relief exceeds the Kindergeld, so the + net benefit is larger than the Kindergeld""" + netto_kids = main.calc_netto(150000, config=married_two_kids, partner_salary=80000) + netto_ref = main.calc_netto( + 150000, config=married_childless_reference, partner_salary=80000 + ) + kindergeld = taxes_children.calc_kindergeld(married_two_kids) + assert netto_kids - netto_ref > kindergeld + + +def test_child_benefit_never_below_kindergeld( + married_two_kids, married_childless_reference +): + """The Günstigerprüfung guarantees at least the Kindergeld""" + kindergeld = taxes_children.calc_kindergeld(married_two_kids) + for salary in [0, 20000, 50000, 100000, 200000, 400000]: + netto_kids = main.calc_netto(salary, config=married_two_kids) + netto_ref = main.calc_netto(salary, config=married_childless_reference) + assert netto_kids - netto_ref >= kindergeld - 0.02 + + +def test_soli_and_church_tax_use_fictitious_tax(): + """Soli and church tax are based on the income tax with child + allowances deducted, which is lower than the regular income tax""" + config = TaxConfig(year=2026, is_married=True, num_children=2) + taxable_income = 200000 + income_tax = taxes_income.calc_income_tax_by_integration(taxable_income, config) + assessed, fictitious = taxes_children.apply_guenstigerpruefung( + taxable_income, income_tax, config + ) + assert fictitious < income_tax + # at this income the Freibetrag wins, so the assessed tax reflects the + # allowance deduction plus the Kindergeld Hinzurechnung + kindergeld = taxes_children.calc_kindergeld(config) + assert assessed == pytest.approx(fictitious + kindergeld, abs=0.02) + + +def test_apply_guenstigerpruefung_no_children_passthrough(): + config = TaxConfig(year=2026, is_married=True) + assessed, fictitious = taxes_children.apply_guenstigerpruefung( + 100000, 25000.0, config + ) + assert assessed == 25000.0 + assert fictitious == 25000.0 + + +def test_num_children_implies_has_children(): + """num_children > 0 removes the nursing childless surcharge""" + config = TaxConfig(year=2026, num_children=2) + assert config.has_children is True + reference = TaxConfig(year=2026, has_children=True) + assert social_security.calc_social_security( + 50000, config + ) == social_security.calc_social_security(50000, reference) + + +def test_zero_gross_yields_kindergeld(married_two_kids): + """A household without salary still receives the Kindergeld""" + assert main.calc_netto(0, config=married_two_kids) == pytest.approx( + taxes_children.calc_kindergeld(married_two_kids) + ) + + +def test_num_children_validation(): + with pytest.raises(ValueError): + TaxConfig(num_children=-1) + with pytest.raises(TypeError): + TaxConfig(num_children=2.0) + with pytest.raises(TypeError): + TaxConfig(num_children=True) + + +def test_forecast_years_have_child_data(): + """Child benefits are available for all supported years incl. forecasts""" + for year in range(2018, 2033): + config = TaxConfig(year=year, num_children=1) + assert taxes_children.calc_kindergeld(config) > 0 diff --git a/test/test_taxes_income.py b/test/test_taxes_income.py new file mode 100644 index 0000000000000000000000000000000000000000..5d58a48cb340cf569d12aae3bd5c8a9ddab2ca23 --- /dev/null +++ b/test/test_taxes_income.py @@ -0,0 +1,178 @@ +import pytest + +import netto.taxes_income as taxes_income +from netto.config import TaxConfig + + +@pytest.fixture +def default_config(): + """Fixture providing default config for tests""" + return TaxConfig( + year=2022, extra_health_insurance=0.014, church_tax=0.09, has_children=False + ) + + +@pytest.mark.parametrize( + "taxable_income,expected_rate", + [ + (-1000, 0), + (0, 0), + (10346, 0), + (10347, 0.14), + (14926, 0.2397), + (58596, 0.42), + (58597, 0.42), + (100000, 0.42), + (277826, 0.45), + (277827, 0.45), + ], +) +def test_get_marginal_tax_rate(taxable_income, expected_rate, default_config): + """Test marginal tax rate calculation for various income levels""" + result = taxes_income.get_marginal_tax_rate(taxable_income, default_config) + assert result == expected_rate + + +@pytest.mark.parametrize( + "taxable_income,expected_rate", + [ + (10346, 0), + (10347, 0), + (10346 * 2, 0), + (10347 * 2, 0.14), + ], +) +def test_get_marginal_tax_rate_married(taxable_income, expected_rate): + """Test marginal tax rate for married couples (doubled brackets)""" + config = TaxConfig(year=2022, is_married=True) + result = taxes_income.get_marginal_tax_rate(taxable_income, config) + assert result == expected_rate + + +@pytest.mark.parametrize( + "taxable_income", + [ + 12000, + 0, + 10000, + 20000, + 30000, + 40000, + 50000, + 60000, + 70000, + 80000, + 90000, + 100000, + 300000, + ], +) +def test_sameness_of_calc_income_tax_methods(taxable_income, default_config): + """Test that both income tax calculation methods give similar results""" + result_direct = taxes_income.calc_income_tax(taxable_income, default_config) + result_integration = taxes_income.calc_income_tax_by_integration( + taxable_income, default_config + ) + assert abs(result_direct - result_integration) < 0.1 + + +@pytest.mark.parametrize( + "taxable_income", [10000, 30000, 60000, 100000, 200000, 600000] +) +def test_calc_income_tax_married_equals_splitting(taxable_income, default_config): + """Married income tax must equal the official splitting tariff: 2 * T(zvE/2)""" + married_config = TaxConfig(year=2022, is_married=True) + result = taxes_income.calc_income_tax(taxable_income, married_config) + expected = 2 * taxes_income.calc_income_tax(taxable_income / 2, default_config) + assert result == pytest.approx(expected) + + +@pytest.mark.parametrize("year", list(range(2018, 2033))) +def test_income_tax_methods_agree_all_years(year): + """The exact formula and the integration method must agree for every + supported year - this cross-checks the polynomial coefficients against + the bracket boundaries in the data files""" + config = TaxConfig(year=year, church_tax=0.0) + for taxable_income in [15000, 40000, 80000, 300000]: + direct = taxes_income.calc_income_tax(taxable_income, config) + integrated = taxes_income.calc_income_tax_by_integration(taxable_income, config) + assert abs(direct - integrated) < 2, ( + f"year {year}, taxable income {taxable_income}: " + f"formula {direct} vs integration {integrated}" + ) + + +@pytest.mark.parametrize("taxable_income", [0, 20000, 50000, 100000, 300000]) +def test_sameness_of_calc_income_tax_methods_married(taxable_income): + """Both income tax calculation methods must agree for married couples""" + married_config = TaxConfig(year=2022, is_married=True) + result_direct = taxes_income.calc_income_tax(taxable_income, married_config) + result_integration = taxes_income.calc_income_tax_by_integration( + taxable_income, married_config + ) + assert abs(result_direct - result_integration) < 0.5 + + +@pytest.mark.parametrize( + "year,expected", + [ + (2018, 48964), # 50000 - 1000 (Werbungskosten) - 36 (Sonderausgaben) + (2021, 48964), + (2022, 48764), # Werbungskosten-Pauschbetrag raised to 1200 + (2023, 48734), # Werbungskosten-Pauschbetrag raised to 1230 + (2025, 48734), + ], +) +def test_calc_taxable_income_year_aware_lump_sums(year, expected): + """Test that lump-sum deductions match the year-specific Pauschbeträge""" + config = TaxConfig(year=year) + result = taxes_income.calc_taxable_income(50000, 0, config=config) + assert result == expected + + +def test_calc_taxable_income_married_doubles_sonderausgaben(): + """Married couples get the doubled Sonderausgaben-Pauschbetrag (72 instead of 36)""" + config = TaxConfig(year=2025, is_married=True) + result = taxes_income.calc_taxable_income(50000, 0, config=config) + assert result == 48698 # 50000 - 1230 - 72 + + +def test_calc_taxable_income_dual_earner(): + """Each earner gets their own Werbungskosten-Pauschbetrag""" + config = TaxConfig(year=2025, is_married=True) + result = taxes_income.calc_taxable_income( + 50000, 0, config=config, partner_salary=40000 + ) + assert result == 87468 # (50000 - 1230) + (40000 - 1230) - 72 + + +def test_calc_taxable_income_partner_below_pauschbetrag(): + """The partner's Werbungskosten deduction cannot exceed their income""" + config = TaxConfig(year=2025, is_married=True) + result = taxes_income.calc_taxable_income( + 50000, 0, config=config, partner_salary=500 + ) + assert result == 48698 # partner income fully offset by the lump sum + + +def test_get_marginal_tax_rate_with_default_none_config(): + """Test that get_marginal_tax_rate works when config=None""" + result = taxes_income.get_marginal_tax_rate(50000) + assert isinstance(result, float) + assert 0 <= result <= 1 + + +def test_calc_income_tax_with_default_none_config(): + """Test that calc_income_tax works when config=None""" + # Use explicit year=2022 since calc_income_tax requires const values + # which are not available for 2023-2025 + result = taxes_income.calc_income_tax(50000, config=TaxConfig(year=2022)) + assert isinstance(result, float) + assert result >= 0 + + +def test_calc_income_tax_by_integration_with_default_none_config(): + """Test that calc_income_tax_by_integration works when config=None""" + result = taxes_income.calc_income_tax_by_integration(50000) + assert isinstance(result, float) + assert result >= 0 diff --git a/test/test_taxes_other.py b/test/test_taxes_other.py new file mode 100644 index 0000000000000000000000000000000000000000..1bd71865fe1a057a91c2015b4092703136aaf71f --- /dev/null +++ b/test/test_taxes_other.py @@ -0,0 +1,109 @@ +import pytest + +import netto.taxes_other as taxes_other +from netto.config import TaxConfig + + +@pytest.fixture +def default_config(): + """Fixture providing default config for tests""" + return TaxConfig( + year=2022, extra_health_insurance=0.014, church_tax=0.09, has_children=False + ) + + +@pytest.mark.parametrize( + "income_tax,expected", + [ + (-1000, 0), + (0, 0), + (16956, 0), + (100000, 5500), + ], +) +def test_calc_soli_exact(income_tax, expected, default_config): + """Test solidarity tax calculation with exact values""" + result = taxes_other.calc_soli(income_tax, default_config) + assert result == expected + + +@pytest.mark.parametrize( + "income_tax,expected", + [ + (16957, 0.119), + (17514.96, 66.48), + (26913.96, 1185.0), + ], +) +def test_calc_soli_approximate(income_tax, expected, default_config): + """Test solidarity tax calculation with approximate values""" + result = taxes_other.calc_soli(income_tax, default_config) + assert abs(result - expected) < 0.1 + + +@pytest.mark.parametrize( + "income_tax,expected", + [ + (-1000, 0), + (0, 0), + (10000, 900), + ], +) +def test_calc_church_tax(income_tax, expected, default_config): + """Test church tax calculation""" + result = taxes_other.calc_church_tax(income_tax, default_config) + assert result == expected + + +@pytest.mark.parametrize( + "income_tax,expected", + [ + (33912, 0), # doubled exemption threshold (2 * 16956) for joint assessment + (33913, 0.12), + (40000, 724.47), + (100000, 5500), # capped at 5.5% regardless of marital status + ], +) +def test_calc_soli_married(income_tax, expected): + """Test that the soli exemption threshold doubles for married couples""" + config = TaxConfig(year=2022, is_married=True) + result = taxes_other.calc_soli(income_tax, config) + assert abs(result - expected) < 0.01 + + +@pytest.mark.parametrize( + "income_tax,expected", + [ + (1944, 0), # doubled exemption threshold (2 * 972) pre-2021 + (2000, 11.2), + (100000, 5500), + ], +) +def test_calc_soli_married_pre_2021(income_tax, expected): + """Test married soli threshold doubling with pre-2021 parameters""" + config = TaxConfig(year=2018, is_married=True) + result = taxes_other.calc_soli(income_tax, config) + assert abs(result - expected) < 0.01 + + +def test_calc_soli_married_below_single_threshold_zone(default_config): + """A tax amount above the single but below the married threshold + must yield soli for singles but none for married couples""" + income_tax = 30000 # 2022: single threshold 16956, married threshold 33912 + married_config = TaxConfig(year=2022, is_married=True) + assert taxes_other.calc_soli(income_tax, default_config) > 0 + assert taxes_other.calc_soli(income_tax, married_config) == 0 + + +def test_calc_soli_with_default_none_config(): + """Test that calc_soli works when config=None""" + result = taxes_other.calc_soli(10000) + assert isinstance(result, float) + assert result >= 0 + + +def test_calc_church_tax_with_default_none_config(): + """Test that calc_church_tax works when config=None""" + result = taxes_other.calc_church_tax(10000) + assert isinstance(result, float) + assert result >= 0